Relational Model and Algebra Concepts
Relational Model and Algebra Concepts
UNIT III
Relational Algebra
Relational algebra is a procedural query language. It gives a step by step process to
obtain the result of the query. It uses operators to perform queries.
Types of Relational operation
Output – Selects tuples from Customers where sales is greater than 50000
Projection(π)
The projection eliminates all attributes of the input relation but those mentioned in
the projection list. The projection method defines a relation that contains a vertical
subset of Relation.
This helps to extract the values of specified attributes to eliminates duplicate values.
(pi) symbol is used to choose attributes from a relation. This operator helps you to
keep specific columns from a relation and discards the other columns.
Example of Projection:
Consider the following table
CustomerID CustomerName Status
1 Google Active
2 Amazon Active
3 Apple Inactive
4 Alibaba Active
Here, the projection of CustomerName and status will give
Π CustomerName, Status (Customers)
CustomerName Status
Google Active
Amazon Active
Apple Inactive
Alibaba Active
Rename (ρ)
Rename is a unary operation used for renaming attributes of a relation.
ρ (a/b)R will rename the attribute „b‟ of relation by „a‟.
Union operation (υ)
Table A ∩ B
column 1 column 2
1 1
Cartesian Product(X) in DBMS
Cartesian Product in DBMS is an operation used to merge columns from two
relations. Generally, a cartesian product is never a meaningful operation when it
performs alone. However, it becomes meaningful when it is followed by other
operations. It is also called Cross Product or Cross Join.
Example – Cartesian product
σ column 2 = „1‟ (A X B)
Output – The above example shows all rows from relation A and B whose column 2
has value 1
σ column 2 = ‘1’ (A X B)
column 1 column 2
1 1
1 1
Student1 –
RollNo Name Marks
1 Ashish 98
2 Shivam 72
3 Tarun 53
4 Yash 89
Student2 –
RollNo Name Marks
1 Anjali 99
4 Dinesh 79
5 Harsh 95
7 Kartik 88
a. Condition Join
When you want to join two relations based on the given condition, it is termed as
Condition Join. It is denoted by the symbol ⋈c.
For e.g. – Select the students from Student1 table whose RollNo is greater than the
RollNo of Student2 table.
Student1⋈[Link]>Student2.RollNoStudent2
Syntax:
SELECT * FROM Student1, Student2 WHERE [Link] >
[Link];
Output –
RollNo Name Marks RollNo Name Marks
2 Shivam 72 1 Anjali 99
3 Tarun 53 1 Anjali 99
4 Yash 89 1 Anjali 99
b. Equi Join
It is a special case of Condition Join. When you want to join two relations based on
the equality condition, it is termed as Equi Join. It is denoted by the symbol ⋈.
For e.g. - Select the students from Student1 table whose RollNo is equalto the
RollNo of Student2 table.
Student1⋈[Link]=Student2.RollNoStudent2
Syntax:
SELECT * FROM Student1, Student2 WHERE [Link]=[Link];
Output –
RollNo Name Marks RollNo Name Marks
1 Ashish 98 1 Anjali 99
4 Yash 89 4 Dinesh 79
c. Natural Join
Natural Join is that type of join in which equijoin is by default applied to all the
attributes in two or more relation. Its specialty is if you want to consider the equality
between two relations, you don‟t need to define the equality; it is predefined for all
the attributes if you use Natural Join. It is denoted by the symbol ⋈.
For e.g. - Select the students from Student1 table whose RollNo is equal to the
RollNo of Student2 table.
Student1⋈Student2
Syntax:
SELECT * FROM Student1 NATURAL JOIN Student2;
Output –
RollNo Name Marks RollNo Name Marks
1 Ashish 98 1 Anjali 99
4 Yash 89 4 Dinesh 79
There is also one more type of Join Outer Join which further gets divided into Left
Outer Join, Right Outer Join and Full Outer Join. We will discuss it in other section
in Inner Join VS Outer Join.
Join Operations
Join operation is essentially a cartesian product followed by a selection criterion.
Join operation denoted by ⋈.
JOIN operation also allows joining variously related tuples from different relations.
Types of JOIN:
Various forms of join operation are:
Inner Joins:
• Theta join
• EQUI join
• Natural join
Outer join:
• Left Outer Join
• Right Outer Join
• Full Outer Join
Inner Join:
In an inner join, only those tuples that satisfy the matching criteria are included, while
the rest are excluded. Let‟s study various types of Inner Joins:
Theta Join:
The general case of JOIN operation is called a Theta join. It is denoted by symbol θ
Example
A ⋈θ B
Theta join can use any conditions in the selection criteria.
For example:
A ⋈ [Link] 2 > [Link] 2 (B)
A ⋈ [Link] 2 > [Link] 2 (B)
column 1 column 2
1 2
EQUI join:
When a theta join uses only equivalence condition, it becomes a equi join.
For example:
A ⋈ [Link] 2 = [Link] 2 (B)
A ⋈ [Link] 2 = [Link] 2 (B)
column 1 column 2
1 1
EQUI join is the most difficult operations to implement efficiently using SQL in an
RDBMS and one reason why RDBMS have essential performance problems.
In the left outer join, operation allows keeping all tuple in the left relation. However, if
there is no matching tuple is found in right relation, then the attributes of right relation
in the join result are filled with null values.
A B
A⋈B
Num Cube Square
2 8 4
3 18 9
5 75 –
6. ROLLBACK;
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling
back the entire transaction.
Syntax:
2. SAVEPOINT SAVEPOINT_NAME;
5. Data Query Language
DQL is used to fetch the data from the database.
It uses only one command:
o SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is
used to select the attribute based on the condition described by WHERE clause.
Syntax:
4. SELECT expressions
5. FROM TABLES
6. WHERE conditions;
For example:
3. SELECT emp_name
4. FROM employee
WHERE age > 20;
There are certain rules which must be followed to perform operations using SET
operators in SQL. Rules are as follows:
1. The number and order of columns must be the same.
2. Data types must be compatible.
Let us see each of the SET operators in more detail with the help of examples.
Table 2: t2_employees
Table 3: t_students
ID Name Hometown Percentage Favourite_Subject
Table 4: t2_students
1. UNION:
o UNION will be used to combine the result of two select statements.
o Duplicate rows will be eliminated from the results obtained after performing the
UNION operation.
Example 1:
Write a query to perform union between the table t_employees and the table
t2_employees.
Query:
1. mysql> SELECT *FROM t_employees UNION SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT
query will fetch the records from the t_employees table and perform a UNION
operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:
Since we have performed union operation between both the tables, so only the
records from the first and second table are displayed except for the duplicate
records.
Example 2:
Write a query to perform union between the table t_students and the table
t2_students.
Query:
1. mysql> SELECT *FROM t_students UNION SELECT *FROM t2_students;
Here, in a single query, we have written two SELECT queries. The first SELECT
query will fetch the records from the t_students table and perform a UNION
operation with the records fetched by the second SELECT query from the
t2_students table.
You will get the following output:
Since we have performed union operation between both the tables, so only the
records from the first and second table are displayed except for the duplicate
records.
2. UNION ALL
o This operator combines all the records from both the queries.
o Duplicate rows will be not be eliminated from the results obtained after performing
the UNION ALL operation.
Example 1:
Write a query to perform union all operation between the table t_employees and the
table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees UNION ALL SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT
query will fetch the records from the t_employees table and perform UNION ALL
operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:
Since we have performed union all operation between both the tables, so all the
records from the first and second table are displayed, including the duplicate
records.
Example 2:
Write a query to perform union all operation between the table t_students and the
table t2_students.
Query:
1. mysql> SELECT *FROM t_students UNION ALL SELECT *FROM t2_students;
Here, in a single query, we have written two SELECT queries. The first SELECT
query will fetch the records from the t_students table and perform UNION ALL
operation with the records fetched by the second SELECT query from the
t2_students table.
You will get the following output:
Since we have performed union all operation between both the tables, so all the
records from the first and second table are displayed, including the duplicate
records.
3. INTERSECT:
o It is used to combine two SELECT statements, but it only returns the records which
are common from both SELECT statements.
Example 1:
Write a query to perform intersect operation between the table t_employees and the
table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees INTERSECT SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT
query will fetch the records from the t_employees table and perform INTERSECT
operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:
Since we have performed intersect operation between both the tables, so only the
common records from both the tables are displayed.
Example 2:
Write a query to perform intersect operation between the table t_students and the
table t2_students.
Query:
1. mysql> SELECT *FROM t_students INTERSECT SELECT *FROM t2_students;
Here, in a single query, we have written two SELECT queries. The first SELECT
query will fetch the records from the t_students table and perform a UNION
operation with the records fetched by the second SELECT query from the
t2_students table.
You will get the following output:
Since we have performed intersect operation between both the tables, so only the
common records from both the tables are displayed.
4. MINUS
o It displays the rows which are present in the first query but absent in the second
query with no duplicates.
Example 1:
Write a query to perform a minus operation between the table t_employees and the
table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees MINUS SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT
query will fetch the records from the t_employees table and perform MINUS
operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:
Since we have performed Minus operation between both the tables, so only the
unmatched records from both the tables are displayed.
Example 2:
Write a query to perform a minus operation between the table t_students and the
table t2_students.
Query:
1. mysql> SELECT *FROM t_students MINUS SELECT *FROM t2_students;
Here, in a single query, we have written two SELECT queries. The first SELECT
query will fetch the records from the t_employees table and perform a UNION
operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:
Since we have performed a minus operation between both the tables, so only the
Unmatched records from both the tables are displayed.
1. COUNT FUNCTION
o COUNT function is used to Count the number of rows in a database table. It
can work on both numeric and non-numeric data types.
oCOUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670
Example: SUM() with WHERE
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
Example: SUM() with GROUP BY
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Example: SUM() with HAVING
1. SELECT COMPANY, SUM(COST)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;
Output:
Com1 335
Com3 170
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values.
Syntax
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10
Constraints in SQL
Constraints in SQL means we are applying certain conditions or restrictions on the
database. This further means that before inserting data into the database, we are
checking for some conditions. If the condition we have applied to the database holds
true for the data which is to be inserted, then only the data will be inserted into the
database tables.
Constraints in SQL can be categorized into two types:
1. Column Level Constraint:
Column Level Constraint is used to apply a constraint on a single column.
2. Table Level Constraint:
Table Level Constraint is used to apply a constraint on multiple columns.
Some of the real-life examples of constraints are as follows:
1. Every person has a unique email id. This is because while creating an email account
for any user, the email providing services such as Gmail, Yahoo or any other email
providing service will always check for the availability of the email id that the user
wants for himself. If some other user already takes the email id that the user wants,
then that id cannot be assigned to another user. This simply means that no two users
can have the same email ids on the same email providing service. So, here the email
id is the constraint on the database of email providing services.
2. Whenever we set a password for any system, there are certain constraints that are to
be followed. These constraints may include the following:
o There must be one uppercase character in the password.
o Password must be of at least eight characters in length.
o Password must contain at least one special symbol.
Constraints available in SQL are:
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
7. CREATE INDEX
Now let us try to understand the different constraints available in SQL in more detail
with the help of examples. We will use MySQL database for writing all the queries.
1. NOT NULL
o NULL means empty, i.e., the value is not available.
o Whenever a table's column is declared as NOT NULL, then the value for that column
cannot be empty for any of the table's records.
o There must exist a value in the column to which the NOT NULL constraint is applied.
NOTE: NULL does not mean zero. NULL means empty column, not even zero.
Syntax to apply the NOT NULL constraint during table creation:
1. CREATE TABLE TableName (ColumnName1 datatype NOT NULL, ColumnName2 datatyp
e,…., ColumnNameN datatype);
Example:
Create a student table and apply a NOT NULL constraint on one of the table's
column while creating a table.
1. CREATE TABLE student(StudentID INT NOT NULL, Student_FirstName VARCHAR(20), St
udent_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_I
D VARCHAR(40));
To verify that the not null constraint is applied to the table's column and the student
table is created successfully, we will execute the following query:
To verify that the not null constraint is applied to the student table's column, we will
execute the following query:
1. mysql> DESC student;
2. UNIQUE
o Duplicate values are not allowed in the columns to which the UNIQUE constraint is
applied.
o The column with the unique constraint will always contain a unique value.
o This constraint can be applied to one or more than one column of a table, which
means more than one unique constraint can exist on a single table.
o Using the UNIQUE constraint, you can also modify the already created tables.
Syntax to apply the UNIQUE constraint on a single column:
1. CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2 datatype,
…., ColumnNameN datatype);
Example:
Create a student table and apply a UNIQUE constraint on one of the table's column
while creating a table.
1. mysql> CREATE TABLE student(StudentID INT UNIQUE, Student_FirstName VARCHAR(2
0), Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_E
mail_ID VARCHAR(40));
To verify that the unique constraint is applied to the table's column and the student
table is created successfully, we will execute the following query:
1. mysql> DESC student;
To verify that the unique constraint is applied to more than one table's column and
the student table is created successfully, we will execute the following query:
1. mysql> DESC student;
To verify that the unique constraint is applied to the table's column and the student
table is created successfully, we will execute the following query:
1. mysql> DESC student;
3. PRIMARY KEY
o PRIMARY KEY Constraint is a combination of NOT NULL and Unique constraints.
o NOT NULL constraint and a UNIQUE constraint together forms a PRIMARY
constraint.
o The column to which we have applied the primary constraint will always contain a
unique value and will not allow null values.
Syntax of primary key constraint during table creation:
1. CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY, ColumnName2 dat
atype,…., ColumnNameN datatype);
Example:
Create a student table and apply the PRIMARY KEY constraint while creating a
table.
1. mysql> CREATE TABLE student(StudentID INT PRIMARY KEY, Student_FirstName VARC
HAR(20), Student_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20), Stud
ent_Email_ID VARCHAR(40));
To verify that the primary key constraint is applied to the table's column and the
student table is created successfully, we will execute the following query:
1. mysql> DESC student;
To verify that the primary key constraint is applied to the student table's column, we
will execute the following query:
1. mysql> DESC student;
4. FOREIGN KEY
o A foreign key is used for referential integrity.
o When we have two tables, and one table takes reference from another table, i.e., the
same column is present in both the tables and that column acts as a primary key in
one table. That particular column will act as a foreign key in another table.
Syntax to apply a foreign key constraint during table creation:
1. CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY, ColumnName
N Datatype(SIZE), FOREIGN KEY( ColumnName ) REFERENCES PARENT_TABLE_NAM
E(Primary_Key_ColumnName));
Example:
Create an employee table and apply the FOREIGN KEY constraint while creating a
table.
To create a foreign key on any table, first, we need to create a primary key on a
table.
1. mysql> CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name
VARCHAR (40), Emp_Salary VARCHAR (40));
To verify that the primary key constraint is applied to the employee table's column,
we will execute the following query:
1. mysql> DESC employee;
Now, we will write a query to apply a foreign key on the department table referring to
the primary key of the employee table, i.e., Emp_ID.
1. mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name
VARCHAR(40), Emp_ID INT NOT NULL, FOREIGN KEY(Emp_ID) REFERENCES employ
ee(Emp_ID));
To verify that the foreign key constraint is applied to the department table's column,
we will execute the following query:
1. mysql> DESC department;
To verify that the primary key constraint is applied to the student table's column, we
will execute the following query:
1. mysql> DESC employee;
Now, we will write a query to apply a foreign key with a constraint name on the
department table referring to the primary key of the employee table, i.e., Emp_ID.
1. mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name
VARCHAR(40), Emp_ID INT NOT NULL, CONSTRAINT emp_id_fk FOREIGN KEY(Emp_I
D) REFERENCES employee(Emp_ID));
To verify that the foreign key constraint is applied to the department table's column,
we will execute the following query:
1. mysql> DESC department;
mysql> ALTER TABLE department ADD FOREIGN KEY (Emp_ID) REFERENCES employ
ee (Emp_ID);
To verify that the foreign key constraint is applied to the department table's column,
we will execute the following query:
5. CHECK
o Whenever a check constraint is applied to the table's column, and the user wants to
insert the value in it, then the value will first be checked for certain conditions before
inserting the value into that column.
o For example: if we have an age column in a table, then the user will insert any value
of his choice. The user will also enter even a negative value or any other invalid
value. But, if the user has applied check constraint on the age column with the
condition age greater than 18. Then in such cases, even if a user tries to insert an
invalid value such as zero or any other value less than 18, then the age column will
not accept that value and will not allow the user to insert it due to the application of
check constraint on the age column.
Syntax to apply check constraint on a single column:
To verify that the check constraint is applied to the student table's column, we will
execute the following query:
To verify that the check constraint is applied to the age and percentage column, we
will execute the following query:
1. mysql> DESC student;
To verify that the check constraint is applied to the student table's column, we will
execute the following query:
1. mysql> DESC student;
6. DEFAULT
Whenever a default constraint is applied to the table's column, and the user has not
specified the value to be inserted in it, then the default value which was specified
while applying the default constraint will be inserted into that particular column.
Syntax to apply default constraint during table creation:
1. CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value, ColumnName2 da
tatype,…., ColumnNameN datatype);
Example:
Create a student table and apply the default constraint while creating a table.
1. mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Stude
nt_LastName VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID V
ARCHAR(40) DEFAULT "anuja.k8@[Link]");
To verify that the default constraint is applied to the student table's column, we will
execute the following query:
To verify that the default constraint is applied to the student table's column, we will
execute the following query:
1. mysql> DESC student;
7. CREATE INDEX
CREATE INDEX constraint is used to create an index on the table. Indexes are not
visible to the user, but they help the user to speed up the searching speed or
retrieval of data from the database.
To verify that the create index constraint is applied to the student table's column, we
will execute the following query:
1. mysql> DESC student;
To verify that the create index constraint is applied to the student table's column, we
will execute the following query:
To verify that the create index constraint is applied to the student table's column, we
will execute the following query:
1. mysql> DESC student;