0% found this document useful (0 votes)
46 views38 pages

Relational Model and Algebra Concepts

Uploaded by

gopabandhukamila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views38 pages

Relational Model and Algebra Concepts

Uploaded by

gopabandhukamila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BCA 4 S T S E M DATABASE ENGINEERING

UNIT III

Relational Model concept


Relational model can represent as a table with columns and rows. Each row is
known as a tuple. Each table of the column has a name or attribute.
Domain: It contains a set of atomic values that an attribute can take.
Attribute: It contains the name of a column in a particular table. Each attribute Ai
must have a domain, dom(Ai)
Relational instance: In the relational database system, the relational instance is
represented by a finite set of tuples. Relation instances do not have duplicate tuples.
Relational schema: A relational schema contains the name of the relation and
name of all columns or attributes.
Relational key: In the relational key, each row has one or more attributes. It can
identify the row in the relation uniquely.
Example: STUDENT Relation
NAME ROLL_NO PHONE_NO ADDRESS AGE

Ram 14795 7305758992 Noida 24

Shyam 12839 9026288936 Delhi 35

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

Laxman 33289 8583287182 Gurugram 20

Mahesh 27857 7086819134 Ghaziabad 27

Ganesh 17282 9028 9i3988 Delhi 40


In the given table, NAME, ROLL_NO, PHONE_NO, ADDRESS, and AGE are
o
the attributes.
o The instance of schema STUDENT has 5 tuples.
o t3 = <Laxman, 33289, 8583287182, Gurugram, 20>
Properties of Relations
o Name of the relation is distinct from all other relations.
o Each relation cell contains exactly one atomic (single) value
o Each attribute contains a distinct name
o Attribute domain has no significance
o tuple has no duplicate value
o Order of tuple can have a different sequence

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

Unary Relational Operations


• SELECT (symbol: σ)
• PROJECT (symbol: π)
• RENAME (symbol: ρ)
Relational Algebra Operations From Set Theory
• UNION (υ)
• INTERSECTION ( ),
• DIFFERENCE (-)
• CARTESIAN PRODUCT ( x )
Binary Relational Operations
• JOIN
• DIVISION

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

Let‟s study them in detail with solutions:


SELECT (σ)
The SELECT operation is used for selecting a subset of the tuples according to a
given selection condition. Sigma(σ)Symbol denotes it. It is used as an expression to
choose tuples which meet the selection condition. Select operator selects tuples that
satisfy a given predicate.
σp(r)
σ is the predicate
r stands for relation which is the name of the table
p is prepositional logic
Example 1
σ topic = "Database" (Tutorials)
Output – Selects tuples from Tutorials where topic = „Database‟.
Example 2
σ topic = "Database" and author = "guru99"( Tutorials)
Output – Selects tuples from Tutorials where the topic is „Database‟ and „author‟ is
guru99.
Example 3
σ sales > 50000 (Customers)

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 (υ)

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

UNION is symbolized by ∪ symbol. It includes all tuples that are in tables A or in B. It


also eliminates duplicate tuples. So, set A UNION set B would be expressed as:
The result <- A ∪ B
For a union operation to be valid, the following conditions must hold –
• R and S must be the same number of attributes.
• Attribute domains need to be compatible.
• Duplicate tuples should be automatically removed.
Example
Consider the following tables.
Table A Table B
column 1 column 2 column 1 column 2
1 1 1 1
1 2 1 3
A ∪ B gives
Table A ∪ B
column 1 column 2
1 1
1 2
1 3
Set Difference (-)
– Symbol denotes it. The result of A – B, is a relation which includes all tuples that
are in A but not in B.
• The attribute name of A has to match with the attribute name in B.
• The two-operand relations A and B should be either compatible or Union
compatible.
• It should be defined relation consisting of the tuples that are in relation A, but
not in B.
Example
A-B
Table A – B
column 1 column 2
1 2
Intersection
An intersection is defined by the symbol ∩
A∩B
Defines a relation consisting of a set of all tuple that are in both A and B. However, A
and B must be union-compatible.

Visual Definition of Intersection


Example:
A∩B

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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

DBMS | Extended Operators in Relational Algebra


In Relational Algebra, Extended Operators are those operators that are derived
from the basic operators. There are mainly three types of Extended Operators,
namely:
1. Intersection
2. Divide
3. Join
Let us consider two tables named as A and B.
A–
RollNo Name Marks
1 Aashi 98
3 Anjali 79
4 Brijesh 88
B–
RollNo Name Marks
1 Aashi 98
2 Abhishek 87
3 Anjali 79
4 Brijesh 88
1) Intersection
Intersection works on the relation as 'this and that'. In relational algebra, A ∩
B returns a relation instance that contains every tuple that occurs in relation to
instance A and relation instance B (both together). Here, A and B need to be union-
compatible, and the schema of both result and A must be identical.
Syntax:

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

SELECT * FROM A INTERSECT SELECT * FROM B;


RollNo Name Marks
1 Aashi 98
3 Anjali 79
4 Brijesh 88
2) Divide
Divide operator is used for the queries that contain the keyword ALL.
For e.g. – Find all the students who has chosen additional subjects Machine
Learning and Data Mining.
Student –
Student Name Subject
Ashish Machine Learning
Ashish Data Mining
Shivam Network Security
Shivam Data Mining
Tarun Network Security
Tarun Machine Learning
Yash Machine Learning
Yash Data Mining
Subject –
Student Name
Machine Learning
Data Mining
Output: Student ÷ Subject
Student
Ashish
Yash
3) Join
Join operation is as its name suggest, to join or combine two or more relations‟
information. Join can also be defined as a cross-product followed by selection and
projection. There are several varieties of Join operation. Let‟s discuss all of them one
by one.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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.

NATURAL JOIN (⋈)


Natural join can only be performed if there is a common attribute (column) between
the relations. The name and type of the attribute must be same.
Example
Consider the following two tables
C
Num Square
2 4
3 9
D
Num Cube
2 8
3 27
C⋈D
C⋈D
Num Square Cube
2 4 8
3 9 27
OUTER JOIN
In an outer join, along with tuples that satisfy the matching criteria, we also include
some or all tuples that do not match the criteria.
Left Outer Join(A B)

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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.

Consider the following 2 Tables


A
Num Square
2 4
3 9
4 16
B
Num Cube
2 8
3 18
5 75
A B
A⋈B
Num Square Cube
2 4 8
3 9 18

Right Outer Join: ( A B)


In the right outer join, operation allows keeping all tuple in the right relation.
However, if there is no matching tuple is found in the left relation, then the attributes
of the left 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 –

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

Full Outer Join: ( A B)


In a full outer join, all tuples from both relations are included in the result, irrespective
of the matching condition.
A B
A⋈B
Num Cube Square
2 4 8
3 9 18
4 16 –
5 – 75
Summary
Purpose
The SELECT operation is used for selecting a subset of
Select(σ)
the tuples according to a given selection condition
The projection eliminates all attributes of the input
Projection(π)
relation but those mentioned in the projection list.
Union Operation(∪) UNION is symbolized by symbol. It includes all tuples
that are in tables A or in B.
Set Difference(-)
Intersection defines a relation consisting of a set of all
Intersection(∩)
tuple that are in both A and B.
Cartesian operation is helpful to merge columns from
Cartesian Product(X)
two relations.
Inner join, includes only those tuples that satisfy the
Inner Join
matching criteria.
The general case of JOIN operation is called a Theta
Theta Join(θ)
join. It is denoted by symbol θ.
When a theta join uses only equivalence condition, it
EQUI Join
becomes a equi join.
Natural join can only be performed if there is a common
Natural Join(⋈)
attribute (column) between the relations.
In an outer join, along with tuples that satisfy the
Outer Join
matching criteria.
In the left outer join, operation allows keeping all tuple in
Left Outer Join( )
the left relation.
In the right outer join, operation allows keeping all tuple
Right Outer join( )
in the right relation.
In a full outer join, all tuples from both relations are
Full Outer Join( ) included in the result irrespective of the matching
condition.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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;

SET Operators in SQL


SET operators are special type of operators which are used to combine the result of
two queries.
Operators covered under SET operators are:
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS

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.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

All the examples will be written using the MySQL database.


Consider we have the following tables with the given data.
Table 1: t_employees

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

Table 2: t2_employees

ID Name Department Salary Year_of_Experience

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4

6 Bhushan Wagh R&D 75000 2

7 Anand Singh Marketing 28000 1

Table 3: t_students
ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

Table 4: t2_students

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Ishwari Dixit Delhi 86 Hindi

3 Anuja Rajput Jaipur 78 History

4 Pakhi Arora Surat 70 Sanskrit

5 Renuka Deshmukh Panipat 90 Biology

6 Jayshree Patel Pune 91 Maths

7 Prachi Jaiswal Gurugram 96 Hindi

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:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

3 Gautam Jain Development 56000 4

5 Rahul Thakur Production 76000 4

7 Anand Singh Marketing 28000 1

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:

ID Name Department Salary Year_of_Experience

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

2 Ishwari Dixit Delhi 86 Hindi

4 Pakhi Arora Surat 70 Sanskrit

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

6 Jayshree Patel Pune 91 Maths

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:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4

6 Bhushan Wagh R&D 75000 2

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

7 Anand Singh Marketing 28000 1

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:

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

1 Soniya Jain Udaipur 89 Physics

2 Ishwari Dixit Delhi 86 Hindi

3 Anuja Rajput Jaipur 78 History

4 Pakhi Arora Surat 70 Sanskrit

5 Renuka Deshmukh Panipat 90 Biology

6 Jayshree Patel Pune 91 Maths

7 Prachi Jaiswal Gurugram 96 Hindi

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.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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:

ID Name Hometown Percentage Favourite_Subject

2 Abhishek Pawar Production 45000 1

4 Shubham Mahale Accounts 57000 2

6 Bhushan Wagh R&D 75000 2

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:

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

3 Anuja Rajput Jaipur 78 History

5 Renuka Deshmukh Panipat 90 Biology

7 Prachi Jaiswal Gurugram 96 Hindi

Since we have performed intersect operation between both the tables, so only the
common records from both the tables are displayed.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

3 Pranav Deshmukh HR 59900 3

5 Sunil Kulkarni Development 87000 3

7 Paras Jaiswal Marketing 32000 1

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:

ID Name Hometown Percentage Favourite_Subject

2 Harshada Sharma Kanpur 92 Chemistry

4 Pranali Singh Nashik 88 Geography

6 Swati Kumari Faridabad 93 English

Since we have performed a minus operation between both the tables, so only the
Unmatched records from both the tables are displayed.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

SQL Aggregate Functions


o SQL aggregation function is used to perform the calculations on multiple rows
of a single column of a table. It returns a single value.
o It is also used to summarize the data.
Types of SQL Aggregation Function

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

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120


Example: COUNT()
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
Example: COUNT with WHERE
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
7
Example: COUNT() with DISTINCT
1. SELECT COUNT(DISTINCT COMPANY)
2. FROM PRODUCT_MAST;
Output:
3
Example: COUNT() with GROUP BY
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2
Example: COUNT() with HAVING
1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;
Output:
Com1 5
Com2 3

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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)

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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,

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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:

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

mysql> DESC student;

Syntax to apply the NOT NULL constraint on an existing table's column:

ALTER TABLE TableName CHANGE Old_ColumnName New_ColumnName Datatype NO


T NULL;
Example:
Consider we have an existing table student, without any constraints applied to it.
Later, we decided to apply a NOT NULL constraint to one of the table's column.
Then we will execute the following query:
1. mysql> ALTER TABLE student CHANGE StudentID StudentID INT NOT NULL;

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;

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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;

Syntax to apply the UNIQUE constraint on more than one column:

CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype,…., Colum


nNameN datatype, UNIQUE (ColumnName1, ColumnName 2));
Example:
Create a student table and apply a UNIQUE constraint on more than one table's
column while creating a table.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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), UNIQUE(StudentID, Student_PhoneNumber));

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;

Syntax to apply the UNIQUE constraint on an existing table's column:


1. ALTER TABLE TableName ADD UNIQUE (ColumnName);
Example:
Consider we have an existing table student, without any constraints applied to it.
Later, we decided to apply a UNIQUE constraint to one of the table's column. Then
we will execute the following query:
1. mysql> ALTER TABLE student ADD UNIQUE (StudentID);

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;

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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;

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

Syntax to apply the primary key constraint on an existing table's column:


1. ALTER TABLE TableName ADD PRIMARY KEY (ColumnName);
Example:
Consider we have an existing table student, without any constraints applied to it.
Later, we decided to apply the PRIMARY KEY constraint to the table's column. Then
we will execute the following query:
1. mysql> ALTER TABLE student ADD PRIMARY KEY (StudentID);

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.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

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;

Syntax to apply the foreign key constraint with constraint name:

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

CREATE TABLE tablename(ColumnName1 Datatype PRIMARY KEY, ColumnNameN Data


type(SIZE), CONSTRAINT ConstraintName FOREIGN KEY( ColumnName ) REFERENCES
PARENT_TABLE_NAME(Primary_Key_ColumnName));
Example:
Create an employee table and apply the FOREIGN KEY constraint with a constraint
name 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 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;

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

Syntax to apply the foreign key constraint on an existing table's column:


1. ALTER TABLE Parent_TableName ADD FOREIGN KEY (ColumnName) REFERENCES C
hild_TableName (ColumnName);
Example:
Consider we have an existing table employee and department. Later, we decided to
apply a FOREIGN KEY constraint to the department table's column. Then we will
execute the following query:
1. mysql> DESC employee;

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:

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

1. mysql> DESC department;

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:

REATE TABLE TableName (ColumnName1 datatype CHECK (ColumnName1 Condition),


ColumnName2 datatype,…., ColumnNameN datatype);
Example:
Create a student table and apply CHECK constraint to check for the age less than or
equal to 15 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), Age INT CHECK( Age <= 15));

To verify that the check constraint is applied to the student table's column, we will
execute the following query:

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

mysql> DESC student;

Syntax to apply check constraint on multiple columns:


1. CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype CHECK (
ColumnName1 Condition AND ColumnName2 Condition),…., ColumnNameN datatype);
Example:
Create a student table and apply CHECK constraint to check for the age less than or
equal to 15 and a percentage greater than 85 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), Age INT, Percentage INT, CHECK( Age <= 15 AND Percentage > 85));

To verify that the check constraint is applied to the age and percentage column, we
will execute the following query:
1. mysql> DESC student;

Syntax to apply check constraint on an existing table's column:

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

ALTER TABLE TableName ADD CHECK (ColumnName Condition);


Example:
Consider we have an existing table student. Later, we decided to apply the CHECK
constraint on the student table's column. Then we will execute the following query:
1. mysql> ALTER TABLE student ADD CHECK ( Age <=15 );

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:

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

1. mysql> DESC student;

Syntax to apply default constraint on an existing table's column:


1. ALTER TABLE TableName ALTER ColumnName SET DEFAULT Value;
Example:
Consider we have an existing table student. Later, we decided to apply the
DEFAULT constraint on the student table's column. Then we will execute the
following query:
1. mysql> ALTER TABLE student ALTER Student_Email_ID SET DEFAULT "anuja.k8@gmail
.com";

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.

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

Syntax to create an index on single column:


1. CREATE INDEX IndexName ON TableName (ColumnName 1);
Example:
Create an index on the student table and apply the default constraint while creating a
table.
1. mysql> CREATE INDEX idx_StudentID ON student (StudentID);

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;

Syntax to create an index on multiple columns:


1. CREATE INDEX IndexName ON TableName (ColumnName 1, ColumnName 2, ColumnNa
me N);
Example:
1. mysql> CREATE INDEX idx_Student ON student (StudentID, Student_PhoneNumber);

To verify that the create index constraint is applied to the student table's column, we
will execute the following query:

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720


BCA 4 S T S E M DATABASE ENGINEERING

1. mysql> DESC student;

Syntax to create an index on an existing table:


1. ALTER TABLE TableName ADD INDEX (ColumnName);
Consider we have an existing table student. Later, we decided to apply the
DEFAULT constraint on the student table's column. Then we will execute the
following query:
1. mysql> ALTER TABLE student ADD INDEX (StudentID);

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;

Gopabandhu Kamila– MCA(Comp. Sc) ,UNIPOWER,BDK - 6290829720

You might also like