Relational Algebra and SQL Basics
Relational Algebra and SQL Basics
DATABASE MANAGEMENT 2
SYSTEMS
Relational Algebra
Example of selection:
▪ Notation: σ p(r)
Account(account_number, branch_name,balance)
p is called the selection predicate σ branch-name=“Perryridge”(account)
⮚Defined as:
A B C D A B C D
σp(r) = {t | t ∈r and p(t)} α 1 7 α 1 7
α α
⮚ Where p is a formula in propositional
calculus consisting of terms connected by : ∧ α β 5 7 β β 23 10
(and), ∨(or), ¬ (not)
Each term is one of: β β 12 3
<attribute> op <attribute> or <constant> σA=B ^ D > 5 (r)
β β 23 10
where op is one of: =, ≠, >, ≥. <. ≤
Relation r
DATABASE MANAGEMENT SYSTEMS 4
Relational Algebra: Project Operation
▪ Notation : rxs A B C D E
C D E
α 1 α 10 a
α 10 a
α 1 β 10 a
Assume that attributes of r(R) and s(S) are disjoint.
(That is, R ∩ S = ∅). β 10 a
A B r ⅹs α 1 β 20 b
If attributes of r(R) and s(S) are not disjoint, then 1
renaming must be used. α β 20 b
α 1 γ 10 b
β 2 γ 10 B β 2 α 10 a
β 2 β 10 a
Relation r
Relation s β 2 β 20 b
β 2 γ 10 b
▪ Notation : r ⋈s
▪ We can perform a Natural Join only if there is
at least one common attribute that exists
between two relations
▪ The common attributes must have the same
name and domain. A B A C r ⋈s A B C
▪ Natural join acts on those matching attributes
α 1 α 10 α 1 10
where the values of attributes in both the
relations are same. β 30 β 2 30
β 2
▪ It avoids duplication of columns while
providing the result as compared to other
joins/cartesian-product. Relation r Relation s
DATABASE MANAGEMENT 10
SYSTEMS
Database Languages and
Programming
8/6/2020 DBMS 1
1
Syllabus
8/6/2020 DBMS 1
2
Characteristics of SQL
DBMS 1
8/6/2020
3
Advantages of SQL
▪High Speed: SQL Queries can be used to retrieve large amounts of records from a
database quickly and efficiently.
▪No Coding Required: Using standard SQL it is easier to manage database systems
without having to write substantial amount of code.
▪ Portable: SQL can be run on any platform, Databases using SQL can be moved
8/6/2020 from a device to another without anDyBpMroSblems. 4
SQL Data Types and Literals
8/6/2020 DBMS 15
SQL language statements
8/6/2020 DBMS 16
Data Definition Language (DDL)
8/6/2020 DBMS 18
Integrity Constraints
8/6/2020 DBMS 19
Domain Integrity Constraints
Domain Integrity constraints can be defined as the definition of a valid set of values
for an attribute.
1. NOT NULL Constraint:
2. Unique Constraint :
3. Default Constraint :
4. Check Constraint :
2. Unique Constraint :
• Ensures that all values in a column are different.
• E.g. Emp_ID varchar(20) not null unique,
Emp_ ID Name Salary
Not allowed
as Emp_ID E101 ABC 20000
has unique E102 XYZ 20000
constraint
E102 PQR 18000
Roll_No Name Marks
3. Default Constraint:
•
1
Provides a default value for a column when none is s pecified. ABC NULL
• E.g. Marks int default NULL, 2 XYZ NULL
8/6/2020 DBMS 21
Domain Integrity Constraints (Cont..)
4. Check Constraint:
• The CHECK constraint ensures that all the values in a column satisfies certain conditions.
8/6/2020 DBMS 22
Entity Integrity Constraints
Primary Key constraint:
• states that primary key value can't be null.
• Because primary key value is used to identify individual rows in relation and
if the primary key has a null value, then we can't identify those rows.
• A table can contain a null value other than the primary key field.
Primary Key
Emp_ ID Name Salary
Not allowed E101 ABC 20000
as Emp_ID
is a primary E102 XYZ 20000
key. PQR 18000
8/6/2020 DBMS 23
Referential Integrity Constraints
Foreign Key constraint:
• A foreign key is a key
used to link two tables
together.
• A Foreign Key is a
column or a combination
of columns whose values
match a Primary Key in a
different table.
• The relationship between
2 tables matches the
Primary Key in one of
the tables with a Foreign
Key in the second table.
8/6/2020 DBMS 24
Referential Integrity Constraints(Cont..)
There are two type foreign key Syntax:
integrity constraints: CREATE TABLE child_table(
1. cascade delete
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ], ...
2. cascade update
CONSTRAINT fk_name
1. Cascade Delete :
FOREIGN KEY (child_col1, child_col2, ...
A foreign key with cascade delete
child_col_n)
means that if a record in the parent
REFERENCES parent_table (parent_col1, parent_col2,
table is deleted, then the
corresponding records in the child ... parent_col_n)
table will automatically be deleted. ON DELETE CASCADE
[ ON DELETE { NO ACTION | CASCADE | SET
NULL | SET DEFAULT } ] );
8/6/2020 DBMS 25
Referential Integrity Constraints(Cont..)
8/6/2020 DBMS 26
Integrity Constraints in Create Table
not null
primary key (A1, ..., An )
Foreign key (Am, ..., An ) references r
Example:
8/6/2020 DBMS 27
Alter Command
Alter command is used for altering the table structure, such as,
1. to add a column to existing table
2. to rename any existing column
3. to change datatype of any column or to modify its size.
4. to drop a column from the table.
5. To add a column
alter table <table name> add <column name> datatype
• All exiting tuples in the relation are assigned null as the value for the new
attribute, if default value is not specified.
• E.g. ALTER TABLE Customers
ADD Email varchar(255);
8/6/2020 DBMS 28
Alter Command (Cont..)
• By setting default value for new column
8/6/2020 DBMS 29
Alter Command (Cont..)
3. To Rename a Column
8/6/2020 DBMS 30
Alter Command (Cont..)
4. To drop a column
• Dropping of attributes not supported by many databases.
8/6/2020 DBMS 31
Drop Command
8/6/2020 DBMS 32
Rename Command
8/6/2020 DBMS 33
Truncate Command
8/6/2020 DBMS 34
Data Control Language (DCL)
• DCL commands control the level of access that users have on database objects.
• GRANT – provides access privileges to the users on the database objects. The
privileges could be select, delete, update and insert on the tables and views. On the
procedures, functions and packages it gives select and execute privileges.
8/6/2020 DBMS 35
GRANT Command
8/6/2020 DBMS 37
REVOKE Command
8/6/2020 DBMS 38
Continued…….
• From Root
•
8/6/2020 DBMS 39
Transaction Control Language (TCL)
8/6/2020 DBMS 40
TCL (Cont..)
1) Commit Command:
used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or DELETE, the
changes made by these commands are not permanent, until the current session
is closed, the changes made by these commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as
permanent.
Syntax:
COMMIT;
8/6/2020 DBMS 41
TCL (Cont..)
2) ROLLBACK Command:
restores the database to last committed state.
Can be used to cancel the last update made to the database, if those changes are
not committed using the COMMIT command.
Syntax:
ROLLBACK TO savepoint_name;
3) SAVEPOINT command:
used to temporarily save a transaction so that we can rollback to that point
whenever required.
Syntax:
8/6/2020
SAVEPOINT savepoint_name;
DBMS 42
Data Manipulation Language (DML)
8/6/2020 DBMS 43
INSERT Query
or equivalently
insert into course (course_id, title, dept_name, credits)
values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);
8/6/2020 DBMS 45
UPDATE Query
Increase salaries of instructors whose salary is over $100,000 by 3%, and all others by
a 5%
• Write two update statements:
update instructor
set salary = salary * 0.03
where salary > 100000;
update instructor
set salary = salary * 0.05
where salary <= 100000;
8/6/2020 36
DBMS
SELECT Query
8/6/2020 DBMS 47
SELECT Query (Cont..)
8/6/2020 DBMS 48
The FROM Clause
8/6/2020 DBMS 51
Null Values
It is possible for tuples to have a null value, denoted by null, for some of their
attributes
null signifies an unknown value or that a value does not exist.
The result of any arithmetic expression involving null is null
Example: 5 + null returns null
The predicate is null can be used to check for null values.
– Example: Find all instructors whose salary is null.
select name
from instructor
where salary is null
8/6/2020 DBMS 52
Renaming table in Select clause
The SQL allows renaming relations and attributes using the as clause:
old-name as new-name
Find the names of all instructors who have taught some course and the
course_id,
select name, course_id
from instructor as T , teaches as S
where [Link] = [Link]
Keyword as is optional and may be omitted
instructor as T ≡ instructor T
8/6/2020 DBMS 53
SQL Operators
8/6/2020 DBMS 54
Arithmetic Operators
The select clause can contain arithmetic expressions involving the operation, +, –, *, and
/, and operating on constants or attributes of tuples.
o The Query:
select ID, name, salary/12
from instructor
would return a relation that is the same as the instructor relation, except that the
value of the attribute salary is divided by 12.
o Can rename “salary/12” using the as clause:
select ID, name, salary/12 as monthly_salary
8/6/2020 DBMS 55
SQL Comparison Operators
8/6/2020 DBMS 56
SQL Logical Operators
8/6/2020 DBMS 57
Logical Operators(Cont..)
• ALL
SELECT * FROM Products WHERE Price > ALL (SELECT Price FROM
Products WHERE Price > 500);
• AND
SELECT * FROM Customers WHERE City = "London" AND Country = "UK";
• ANY
SELECT * FROM Products WHERE Price > ANY (SELECT Price FROM
Products WHERE Price > 50);
• BETWEEN AND
SELECT * FROM Products WHERE Price BETWEEN 50 AND 60;
• EXISTS
SELECT * FROM Products WHERE EXISTS (SELECT Price FROM Products
WHERE Price > 50);
8/6/2020 DBMS 58
Logical Operators(Cont..)
• IN
SELECT * FROM Customers WHERE City IN ('Paris','London');
• LIKE
SELECT * FROM Customers WHERE City LIKE 's%';
• NOT
SELECT * FROM Customers WHERE City NOT LIKE 's%';
• OR
SELECT * FROM Customers WHERE City = "London" OR Country = "UK";
• SOME
SELECT * FROM Products WHERE Price > SOME (SELECT Price FROM Products
WHERE Price > 20);
8/6/2020 DBMS 59
SQL Functions
Single Row Functions : Operate on each row and return one output for each row.
Date Functions, String Functions such as length or case conversion functions like
UPPER, LOWER.
Number functions such as ROUND, TRUNC, and MOD etc.
Multi Row Functions : Aggregate Function/Group Functions : Operates on Group of rows
and return output for the complete set of rows. Also known as Group functions.
Min, Max, Count, Sum, Avg etc.
SQL Single Row Functions can be used in Select Clause, Where Clause, Group By Clause,
Order By clause
SQL Multi Row Functions can be used in Select Clause, Group By Clause, Having Clause.
8/6/2020 DBMS 60
String Function : Use in Select, Where, group by , having , order by
Clause
Function Meaning
Char_length(string) Return number of characters in argument
Concat(expr1,expr2) Return concatenated string
Instr(expr1,expr2) Return the index of the first occurrence of substring
Lower(expr1) Return the argument in lowercase
Left(expr1,count) Return the leftmost number of characters from string
Patterns are case sensitive; that is, uppercase characters do not match lowercase characters,
or vice-versa.
To illustrate pattern matching, we consider the following examples:
Percent ( % ): The % character matches any substring.
Underscore ( _ ): The character matches any character in the string.
’Intro%’ matches any string beginning with “Intro”.
’%Comp%’ matches any string containing “Comp” as a substring, for example, ’Intro. to
Computer Science’, and ’Computational Biology’.
’---’ matches any string of exactly three characters.
’ ---%’ matches any string of at least three characters.
8/6/2020 DBMS 63
Pattern matching examples……
• Syntax is
select <column name> from <table_name >where <column_name > like/ not like 'pattern';
• To find the records starting with ‘Luck’
• SELECT * FROM student WHERE city LIKE 'Luck%';
• To find the names not starting with ‘Luck’
• SELECT name FROM student WHERE city NOT LIKE 'Luck%';
• To find the names ending with ‘ly’
• SELECT * FROM student WHERE city LIKE '%fy’ ;
• Find names containing a y
• SELECT * FROM student WHERE city LIKE '%y%‘;
• To find names containing exactly five characters
• SELECT * FROM student WHERE city LIKE ' ';
8/6/2020 DBMS 64
Ordering the Display of Tuples
8/6/2020 DBMS 65
Aggregate Functions
8/6/2020 DBMS 66
Aggregate Functions Examples
Find the average salary of instructors in the Computer Science department
◦ select avg (salary),min(salary), max(salary),sum(salary)
from instructor
where dept_name= 'Comp. Sci.';
Find the number of tuples in the course relation
◦ select count (*) from instructor;
8/6/2020 DBMS 67
Aggregate Functions – Group By
Find the average salary of instructors in each department
◦ select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name;
8/6/2020 DBMS 68
Aggregation (Cont.)
Attributes in select clause outside of aggregate functions must appear in group by list
◦ /* erroneous query */
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
8/6/2020 DBMS 69
Aggregate Functions – Having Clause
Find the names and average salaries of all departments whose average salary is
greater than 42000
8/6/2020 DBMS 70
Null Values and Aggregates
• To find the total all salaries
select sum (salary) from instructor
8/6/2020 DBMS 71
SQL Joins
▪ Join operations take two relations and return as a result another relation.
▪A join operation is a Cartesian product which requires that tuples in the two relations match
(under some condition). It also specifies the attributes that are present in the result of the join
▪ The join operations are typically used as subquery expressions in the from clause
▪Join condition – defines which tuples in the two relations match, and what attributes are
present in the result of the join.
▪ Join type – defines how tuples in each relation that do not match any tuple in the other relation
(based on the join condition) are treated.
8/6/2020 DBMS 72
v1
SQL Joins : Cross Join
• Cross JOIN is a simplest form of JOINs which matches each row from one database table
to all rows of another as a Cartesian product.
• The cross join does not establish a relationship between the joined tables.
• SELECT * FROM `Movies` CROSS JOIN `Artist` OR
• SELECT * FROM `Movies` ,`Artist`;
Artist
Movies
8/6/2020 DBMS 73
v1
Cross Join of 2 tables
8/6/2020 DBMS 74
SQL Joins : Inner Join
• The inner JOIN is used to return rows from both tables that satisfy the given condition(join
condition on common column ).
• SELECT * FROM movies INNER JOIN `Artist` on movies.movie_id = Artist.movie_id
OR
SELECT * FROM movies ,Artist WHERE movies.movie_id = Artist.movie_id
8/6/2020 DBMS 75
v1
SQL Joins : Outer Join
• MySQL Outer JOINs return all records matching from both tables. It can detect records
having no match in joined table. It returns NULL values for records of joined table if no
match is found.
The LEFT JOIN returns all
SELECT [Link] , B.first_name , B.last_name
the rows from the table on the
FROM movies “A” LEFT OUTER JOIN Artist “ B” left even if no matching rows
have been found in the table
ON B.`movie_id` = A. ‘movie_id’ on the right.
Where no matches have
# Some SQL Support keyword : Left join/natural left outer join
been found in the table on
OR the right, NULL is returned.
FROM movies “A” LEFT OUTER JOIN Artist “ B” USING ( `movie_id` ) What will full outer return?
*Use Using keyword for left and right join queries only not for full outer join queries
8/6/2020 DBMS 76
Left outer join Output (contd..)
Movie_id Title Category Id First_name Last_name Movie_id
1 ASSASSIN'S CREED: Animations 1 Adam Smith 1
8/6/2020 DBMS 77
SQL Joins - Revision
8/6/2020 DBMS 78
v1
SQL Joins on multiple tables
8/6/2020 DBMS 79
v1
Join operations – Example
● Observe that
prereq relation is missing for CS-315 and
course relation is missing for CS-347
8/6/2020 DBMS 80
v2
Left Outer Join And Right Outer Join
8/6/2020 DBMS 81
v4
Full outer Join
prereq
●select * from course left outer join prereq on
course.course_id = prereq.course_id
union
select * from course right outer join prereq on
course.course_id = prereq.course_id
8/6/2020 DBMS 72
v6
Inner join Vs. Natural Join
• Select * from course inner join prereq on
course.course_id = prereq.course_id course
8/6/2020 DBMS 73
v7
Subqueries (Nested Query)
8/6/2020 DBMS 84
Examples of Subquery in DML and Select
• SQL> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM
CUSTOMERS WHERE SALARY > 4500) ;
8/6/2020 DBMS 76
Test for Empty Relations
▪EXISTS and NOT EXISTS are used with a subquery in WHERE clause to
examine if the result the subquery returns is TRUE or FALSE.
▪ The true or false value is then used to restrict the rows from outer query select.
▪As EXISTS and NOT EXISTS only return TRUE or FALSE in the subquery, the
SELECT list in the subquery does not need to contain actual column name(s).
8/6/2020 DBMS 87
Continued…
Insert, update, delete commands can also be used with EXISTS commands
INSERT INTO contacts (contact_id, contact_name) SELECT supplier_id,
supplier_name FROM suppliers WHERE EXISTS (SELECT * FROM orders WHERE
suppliers.supplier_id = orders.supplier_id);
Delete from contacts SELECT supplier_id, supplier_name FROM suppliers WHERE
EXISTS (SELECT * FROM orders WHERE suppliers.supplier_id =
orders.supplier_id);
8/6/2020 DBMS 88
Set Operations
3 SAMEER
Select * from table1 union select * from table 2;
4 JAVED
8/6/2020 DBMS 89
Set Operations -examples
ID NAME
• select id from t1 left join t2 using (id) where [Link] is null; ID NAME
(minus) 3 SAMEER
ID NAME
4 JAVED table2
1 ABHI
2 SAMEER ID NAME
1 ABHI
• Select * from table1 union all select * from table 2; 2 SAMEER
3 SAMEER
3 SAMEER
8/6/2020 DBMS 4 JAVED 90
Set Membership
8/6/2020 DBMS 92
Views : Uses and Importance
In some cases, it is not desirable for all users to see the entire logical model
(i.e., all the actual relations stored in the database.)
Consider a person who needs to know an instructors name and department, but
not the salary. This person should see a relation described, in SQL, by
•
select ID, name, dept_name from instructor
A view provides a mechanism to hide certain data from the view of certain
users thus providing security.
Any relation that is not of the conceptual model but is made visible to a user as
a “virtual relation” is called a view.
8/6/2020 DBMS 93
View -Syntax
A view is defined using the create view statement which has the form
create view v as < query expression >
view name any legal SQL expression.
Once a view is defined, the view name can be used to refer to the virtual
relation that the view generates.
Can provide huge time savings in writing queries by already having a group of
frequently accessed tables joined together in a view .
8/6/2020 DBMS 94
Example of Views
A view of instructors without their salary
create view faculty as
select ID, name, dept_name
from instructor
Find all instructors in the Biology department
select name
from faculty
where dept_name = ‘Biology’
Create a view of department salary totals
create view departments_total_salary(dept_name, total_salary) as
select dept_name, sum (salary)
from instructor
group by dept_name;
8/6/2020 DBMS 95
Inserting a new tuple into a View
8/6/2020 DBMS 96
Update of a View
UPDATE faculty
set dept_name=“Biology”
where name=“ABC”
Updation in view reflects the original table . Means the changes will be done
in the original table.
8/6/2020 DBMS 97
Dropping a View
8/6/2020 DBMS 98
Index
Indices are data structures used to speed up access of records with specified values for
index attributes.
Indexes are used to find rows with specific column values quickly.
Without an index, MySQL must begin with the first row and then read through the entire
table to find the relevant rows. (Sequential Scan)
If the table has an index for the columns , MySQL can quickly determine the position to
seek to in the middle of the data file without having to look at all the data.
This is much faster than reading every row sequentially
MySQL create default indexes on PRIMARY KEY, UNIQUE KEY
User defined index can be created using CREATE INDEX COMMAND although they are
not visible to the user.
MySQL indices are stored in B-trees.
8/6/2020 DBMS 99
Example
Syntax:
• CREATE INDEX <index_name> ON < table_name >(column1, column2, ...);
Example:
• create table person(pid int primary key , pnm varchar(10));
• create index id1 on person(pnm); // indexes help to retrieve the data faster.
• Create unique index id2 on person(pid,pnm) ; // rows will have unique value
• alter table person drop index id1;
8/6/2020 DBMS 10
0
References
[Link], R. and Gherke, J., “Database Management Systems”, 3rd Ed., McGraw-
Hill.
8/6/2020 DBMS 10
1
References
Text Books:
• Abraham Silberschatz, Henry F. Korth and S. Sudarshan, Database System Concepts 6th
Ed, McGraw Hill, 2010.
• Elmasi, R. and Navathe, S.B., “Fundamentals of Database Systems”, 4th
• Ed., Pearson Education.
Reference Books :
• Ramakrishnan, R. and Gherke, J., “Database Management Systems”, 3rd Ed., McGraw-
Hill.
• Connally T, Begg C.,”Database Systems”,Pearson Education
DATABASE MANAGEMENT 10
SYSTEMS 2
End of Unit 2
8/6/2020 DBMS 10
3