Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views129 pages

Unit - 3 - DBMS

The document provides an overview of SQL commands, specifically focusing on Data Definition Language (DDL) and Data Manipulation Language (DML). It details various SQL commands such as CREATE, ALTER, DROP, TRUNCATE, RENAME for DDL, and INSERT, SELECT, UPDATE, DELETE for DML, along with syntax and practical examples using MySQL. The document serves as a guide for managing structured data in SQL databases.

Uploaded by

barhatedamodar25
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)
8 views129 pages

Unit - 3 - DBMS

The document provides an overview of SQL commands, specifically focusing on Data Definition Language (DDL) and Data Manipulation Language (DML). It details various SQL commands such as CREATE, ALTER, DROP, TRUNCATE, RENAME for DDL, and INSERT, SELECT, UPDATE, DELETE for DML, along with syntax and practical examples using MySQL. The document serves as a guide for managing structured data in SQL databases.

Uploaded by

barhatedamodar25
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
You are on page 1/ 129

Types of SQL Commands

SQL is a structured query language, which is used to deal with structured data. Structured data is
data that is generally stored in the form of relations or tables.

Whenever we store the data in tables or relations, we need SQL commands. Moreover, these
commands are also required to retrieve the data which is stored in tables.

Let us take a deeper dive into the classification of SQL commands with the help of practical
examples. We will use the MySQL database for writing all the queries.

(A) DDL
 DDL stands for data definition language. DDL Commands deal with the schema, i.e.,
the table in which our data is stored.
 All the structural changes such as creation, deletion and alteration on the table can be
carried with the DDL commands in SQL.
 Commands covered under DDL are:
1. CREATE
2. ALTER
3. DROP
4. TRUNCATE
5. RENAME

1. CREATE:

In SQL, whenever we wish to create a new database or a table in a database, we use CREATE
command.

Syntax to create a new database:

1. CREATE DATABASE DatabaseName;


Syntax to create a table:

1. CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype,….., C


olumnName3 datatype);

Example 1:

Write a query to create a database and give the name of the database as school.

Query:

1. mysql> CREATE DATABASE SCHOOL;

Here, we have executed a CREATE DATABASE query followed by the database name
'SCHOOL'.

We will execute the following command to verify that the database 'SCHOOL' is created:

1. mysql> SHOW DATABASES;


The results of the above command verify that the 'SCHOOL' database is created successfully.

Example 2:

Write a query to create a table in the database 'SCHOOL' and give the table's name as t_school.

To create a table 't_school' in the 'SCHOOL' database, we must select the 'SCHOOL' database.

To select the database in MySQL, we will execute the following query:

1. mysql> USE SCHOOL;

We have executed the 'USE command' followed by the database name, i.e., 'SCHOOL'.

Now just after the execution of this query, we will execute the following query:

1. mysql> CREATE TABLE t_school(ID INT PRIMARY KEY, School_Name VARCHAR


(40), Number_Of_Students INT, Number_Of_Teachers INT, Number_Of_Classrooms I
NT, EmailID VARCHAR(40));

Here, we have executed a CREATE TABLE query followed by the table name 't_school'.

We will execute the following command to verify that the table 't_school' is created:

1. mysql> SHOW TABLES;

The above command results verify that the 't_school' table is successfully created in the
'SCHOOL' database.

2. ALTER

In SQL, whenever we wish to alter the table structure, we will use the ALTER command. Using
alter command, we can make structural changes to the table, such as adding a new column,
removing or deleting an existing column from the table, changing the datatype of an existing
column and renaming an existing column.

Let's look at the syntax before writing the queries using ALTER command.

Syntax of ALTER command to add a new column:

1. ALTER TABLE table_name ADD column_name datatype(size);

Syntax of ALTER command to delete an existing column:

1. ALTER TABLE table_name DROP COLUMN column_name;

Syntax of ALTER command to rename the existing table's column:

1. ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_


name;

Syntax of ALTER command to change the datatype of an existing column:

1. ALTER TABLE table_name MODIFY column_name datatype(size);

Example 1:

Write a query to add a new column Board_of_Education in the t_school table of the datatype
VARCHAR.

Before executing a query to add a new column to the 't_school' table, we will execute the
following query to see the table structure:

1. mysql> DESC t_school;

1. mysql> ALTER TABLE t_school ADD Board_of_Education VARCHAR(20);


Here, we have executed the 'ALTER command' on the table t_school followed the ADD
keyword with the column 'Board_of_Education', the datatype VARCHAR and size 20. This
simply means a new column named 'Board_of_Education' with the datatype VARCHAR and
size 20 will be added to the existing 't_school' table.

Now, we will again apply the DESC command on the t_school table.

1. mysql> DESC t_school;

This verifies that the new column 'Board_of_Education' is successfully added to the t_school
table.

Example 2:

Write a query to remove the column Board_of_Education from the t_school table.

Before executing a query to remove a column from the 't_school' table, we will execute the
following query to see the table structure:

1. mysql> DESC t_school;


1. mysql> ALTER TABLE t_school DROP COLUMN Board_of_Education;

We have executed the 'ALTER command' on the table t_school followed the DROP COLUMN
keyword with the column 'Board_of_Education'. This simply means that the existing column
named 'Board_of_Education' will be removed from the 't_school' table.

Now, we will again apply the DESC command on the t_school table.

1. mysql> DESC t_school;

This verifies that the column 'Board_of_Education' has successfully removed from the t_school
table.

Example 3:
Write a query to rename the column Number_of_Students to 'Count_Students' using the alter
command from the t_school table.

Before executing a query to rename a column from the 't_school' table, we will execute the
following query to see the table structure:

1. mysql> DESC t_school;

1. mysql> ALTER TABLE t_school RENAME COLUMN Number_of_Students TO Count


_Students;

We have executed the 'ALTER command' on the table t_school followed by the RENAME
COLUMN keyword. Here, Number_of_Students is the old column name and the column name
specified after the TO keyword, i.e., Count_Students is the new column name. This simply
means that the existing column named 'Number_of_Students' will be replaced by
'Count_Students' from the 't_school' table.

Now, we will again apply the DESC command on the t_school table.

1. mysql> DESC t_school;

This verifies that the column 'Number_of_Students' is successfully renamed to 'Count_Students'


in the t_school table.

Example 4:

Write a query to change the datatype of 'Number_of_Students' and set the new datatype as
'VARCHAR' with size '20' in the t_school table.

Before executing a query to modify the column datatype and size in the 't_school' table, we will
execute the following query to see the table structure:

1. mysql> DESC t_school;


1. mysql> ALTER TABLE t_school MODIFY ID VARCHAR(20);

We have executed the 'ALTER command' on the table t_school followed by the MODIFY
keyword. Here, ID is the column name, and VARCHAR is the new datatype of the ID column
followed by the size, i.e., 20.

Now, we will again apply the DESC command on the t_school table.

1. mysql> DESC t_school;

3. DROP

DROP command is used to remove or delete the table's records and the table's structure
from the database.

Syntax:
1. DROP TABLE table_name;

Example:

Write a query to delete the t_school table from the SCHOOL database.

Query:

1. mysql> DROP TABLE t_school;

Here, we have executed a DROP TABLE command on the table 't_school'.

We will execute the following command to verify that the table 't_school' exists or not.

1. mysql> SHOW TABLES;

The above command results verify that the 't_school' table is successfully removed from the
'SCHOOL' database.

4. TRUNCATE

A TRUNCATE command is used to delete the table's records, but the table's structure will
remain unaffected in the database.

Syntax:

1. TRUNCATE TABLE table_name;

Example:

Write a query to remove all the records from the 't_school' table.

Before executing a query to remove the records from the 't_school' table, we will execute the
SELECT query to see records present in the table:

1. mysql> SELECT *FROM t_school;

I School_Na Number_Of_Stu Number_Of_Tea Number_Of_Classr


EmailID
D me dents chers ooms
Boys Town
[email protected]
1 Public 1000 80 12
m
School
Guru
Govind
[email protected]
2 Singh 800 35 15
m
Public
School
Delhi
[email protected]
3 Public 1200 30 10
m
School
Ashoka
[email protected]
4 Universal 1110 40 40
m
School
Calibers
English
5 9000 31 50 [email protected]
Medium
School
Cantonmen
t Board
6 7050 41 60 [email protected]
High
School
Podar
podaris89@gmail
7 Internation 12000 120 120
.com
al School
Barnes barnes99@gmail.
8 18000 100 100
School com
D.S
Kothari
9 10000 120 125 [email protected]
Kanya
School
Orchid
1
Internation 20000 200 180 [email protected]
0
al School

1. mysql> TRUNCATE TABLE t_school;

Here, we have executed the 'TRUNCATE command' on the table t_school. This simply means
that all the records from the 't_school' table will be removed, keeping the table structure as it is in
the database.

Now, we will again apply the SELECT query on the t_school table.

1. mysql> SELECT *FROM t_school;


The results above show that all the records from the 't_school' table are removed successfully.

5. RENAME

Rename COMMAND is used to give a new name to an existing table.

Syntax to rename a table:

1. RENAME TABLE old_table_name TO new_table_name;

Example:

Write a query to rename the t_school table as tbl_school.

We will execute the SHOW TABLES command before executing a query to rename the
't_school' table.

1. mysql>SHOW TABLES;

1. mysql> RENAME TABLE t_school TO tbl_school;

We have executed the 'RENAME command' on the table t_school followed by the 'TO' keyword
with the new table name. This simply means that the 't_school' table will now be renamed to
tbl_school.

Now, we will again execute the SHOW TABLES command.

1. mysql>SHOW TABLES;
The results above show that the table t_school is not present in the list. Instead, tbl_school is
present in the list, which means the table is now successfully renamed as tbl_school.

(B) DML
 DML stands for Data Manipulation Language. Using DML commands in SQL, we can
make changes in the data present in tables.
 Whenever we wish to manipulate the data or fetch the data present in SQL tables, we can
use DML commands in SQL.
 DML commands in SQL will change the data, such as inserting new records, deleting
or updating existing records from the SQL tables. We can also retrieve all the data
from SQL tables according to our requirements.
 Commands covered under DDL are:
1. INSERT
2. SELECT
3. UPDATE
4. DELETE

Let us see each of the commands in the DML category with more details.

1. INSERT

INSERT command is used to insert records in a table. We can insert a single as well as multiple
records for a single table at the same time.

Syntax:

1. INSERT INTO table_name VALUES (Column1_Value, Column2_Value, …., ColumnN


_Value);

Example:

Write a query to insert 10 records in the t_school table.

Query:

1. mysql> INSERT INTO t_school(ID, School_Name, Number_of_Students, Number_of_T


eachers, Number_of_Classrooms, EmailID) VALUES(1, "Boys Town Public School", 10
00, 80, 12, "[email protected]"), (2, "Guru Govind Singh Public School", 800, 35, 15, "
[email protected]"), (3, "Delhi Public School", 1200, 30, 10, "[email protected]"), (
4, "Ashoka Universal School", 1110, 40, 40, "[email protected]"), (5, "Calibers English
Medium School", 9000, 31, 50, "[email protected]"), (6, "Cantonment Board High Scho
ol", 7050, 41, 60, "[email protected]"), (7, "Podar International School", 12000, 120, 120,
"[email protected]"), (8, "Barnes School", 18000, 100, 100, "[email protected]
"), (9, "D.S Kothari Kanya School", 10000, 120, 125, "[email protected]"), (10, "Orchid
International School", 20000, 200, 180, "[email protected]");

Since we wanted to insert ten records in a table, so instead of writing the INSERT command ten
times, we have written a single INSERT command to insert multiple records at a time.

2. SELECT

A SELECT command is used to retrieve the records from the table. According to our
requirements, we can retrieve all the records or some specific records from the table. Whenever
we want to retrieve some specific records from the table, then we have to specify the WHERE
clause in a SELECT query. WHERE clause will contain a condition, any record that matches the
condition will be considered as a part of the output.

Syntax to retrieve all the records:

1. SELECT *FROM table_name;

Syntax to retrieve some specific records:

1. SELECT *FROM table_name WHERE condition;

Example 1:

Write a query to retrieve all the column values from all the records of the t_school table.

Query:

1. mysql> SELECT *FROM t_school;

Here, we have executed a SELECT query with the asterisk (*) on the t_school table. This will
retrieve all the column values for all the records from the t_school table.

Output:

I School_Na Number_Of_Stu Number_Of_Tea Number_Of_Classr


EmailID
D me dents chers ooms
Boys Town
[email protected]
1 Public 1000 80 12
m
School
Guru
Govind
[email protected]
2 Singh 800 35 15
m
Public
School
Delhi
[email protected]
3 Public 1200 30 10
m
School
Ashoka
[email protected]
4 Universal 1110 40 40
m
School
Calibers
English
5 9000 31 50 [email protected]
Medium
School
Cantonmen
t Board
6 7050 41 60 [email protected]
High
School
Podar
podaris89@gmail
7 Internation 12000 120 120
.com
al School
Barnes barnes99@gmail.
8 18000 100 100
School com
D.S
Kothari
9 10000 120 125 [email protected]
Kanya
School
Orchid
1
Internation 20000 200 180 [email protected]
0
al School

All the records are retrieved successfully from the t_school table.

Example 2:

Write a query to retrieve all the column values of only those schools which has more than 11
classrooms.

Query:

1. mysql> SELECT *FROM t_school WHERE Number_Of_Classrooms > 11;

We have executed a SELECT query with the asterisk (*) on the t_school table followed by a
WHERE clause condition. Due to the WHERE clause condition, only those records with a value
greater than 11 in the 'Number_of_classrooms' column will only be retrieved.

Output:
I School_Na Number_Of_Stu Number_Of_Tea Number_Of_Classr
EmailID
D me dents chers ooms
Boys Town
[email protected]
1 Public 1000 80 12
m
School
Guru
Govind
[email protected]
2 Singh 800 35 15
m
Public
School
Ashoka
[email protected]
4 Universal 1110 40 40
m
School
Calibers
English
5 9000 31 50 [email protected]
Medium
School
Cantonmen
t Board
6 7050 41 60 [email protected]
High
School
Podar
podaris89@gmail
7 Internation 12000 120 120
.com
al School
Barnes barnes99@gmail.
8 18000 100 100
School com
D.S
Kothari
9 10000 120 125 [email protected]
Kanya
School
Orchid
1
Internation 20000 200 180 [email protected]
0
al School

There are nine schools in the t_school table, which has more than 11 classrooms.

3. UPDATE

UPDATE command works for the values present in the table. Whenever we wish to update a
value for any record present in a table, we will use the UPDATE command in SQL.

Syntax:

1. UPDATE table_name SET column_name = value WHERE condition;

Example:

Write a query to update a record with ID 9 and set the updated value of the Number_of_Teachers
and Number_of_Classrooms as 125 and 9, respectively.
Query:

1. mysql> UPDATE t_school SET Number_Of_Teachers = 125, Number_Of_Classrooms =


120 WHERE ID=9;

We will execute the SELECT query to verify whether the number of teachers and classrooms is
updated for the record with ID as 9.

1. mysql> SELECT *FROM t_school WHERE ID=9;

I School_Na Number_Of_Stud Number_Of_Teac Number_Of_Classro


EmailID
D me ents hers oms
D.S Kothari
[email protected]
9 Kanya 10000 125 120
om
School

4. DELETE

DELETE command is used to remove records from a table.

Syntax:

1. DELETE FROM table_name;

Example:

Write a query to remove the record whose ID is 6 in the t_school table.

Query:

1. mysql> DELETE FROM t_school WHERE ID = 6;

We will execute the SELECT query to verify whether the record with ID 6 is deleted or not.

1. mysql> SELECT * FROM t_school;

I School_Na Number_Of_Stu Number_Of_Tea Number_Of_Classr


EmailID
D me dents chers ooms
Boys Town
[email protected]
1 Public 1000 80 12
m
School
Guru
Govind
[email protected]
2 Singh 800 35 15
m
Public
School
Delhi
[email protected]
3 Public 1200 30 10
m
School
Ashoka
[email protected]
4 Universal 1110 40 40
m
School
Calibers
English
5 9000 31 50 [email protected]
Medium
School
Podar
podaris89@gmail
7 Internation 12000 120 120
.com
al School
Barnes barnes99@gmail.
8 18000 100 100
School com
D.S
Kothari
9 10000 120 125 [email protected]
Kanya
School
Orchid
1
Internation 20000 200 180 [email protected]
0
al School

The results show that the record with ID 6 is deleted successfully from the t_school table.

(C) DCL
 DCL stands for Data Control Language.
 Whenever we want to control the access to the data present in SQL tables, we will use
DCL commands in SQL. Only the authorized users can access the data stored in the
tables.
 Every user will have some pre-defined privileges; accordingly, the data can be accessed
by that particular user. Using the DCL commands in SQL, we can give privileges to the
user on the SQL database and tables, or we can also revoke the given privileges from the
user.
 Commands covered under DCL are:

1. GRANT

Access privileges can be assigned to a user for the databases and tables using the GRANT
command.
2. REVOKE

All the access privileges which are already assigned to the user can be revoked by using the
REVOKE command.

(D) TCL:
 TCL stands for Transaction Control Language. TCL commands are generally used in
transactions.
 Using TCL commands in SQL, we can save our transactions to the database and roll them
back to a specific point in our transaction. We can also save a particular portion of our
transaction using the SAVEPOINT command.
 Commands covered under TCL are:

1. COMMIT:

To save all the operations executed in a particular transaction, we need to execute a commit
command just after the transaction completion.

2. ROLLBACK

Using the rollback command in SQL, you can roll to the last saved state of a transaction.

3. SAVEPOINT

Using the SAVEPOINT command, you can assign a name to a specific part of the transaction.

Example:

1. mysql> START TRANSACTION;

1. mysql>INSERT INTO t_school(ID, School_Name, Number_of_Students, Number_of_T


eachers, Number_of_Classrooms, EmailID) VALUES(1, "Boys Town Public School", 10
00, 80, 12, "[email protected]"), (2, "Guru Govind Singh Public School", 800, 35, 15, "
[email protected]"), (3, "Delhi Public School", 1200, 30, 10, "[email protected]"), (
4, "Ashoka Universal School", 1110, 40, 40, "[email protected]"), (5, "Calibers English
Medium School", 9000, 31, 50, "[email protected]");
1. mysql> COMMIT;

1. mysql> SET autocommit = 0;

1. mysql> SAVEPOINT ins;

Till this point, we have started a transaction, inserted records into it, committed the transaction
and also created a SAVEPOINT ins after insertion.

1. mysql> DELETE FROM t_school WHERE ID = 3;

1. mysql> SAVEPOINT del;

We have deleted a record and created a savepoint del after deletion, but later we thought that we
needed the record we had recently deleted. So, we will roll back to the SAVEPOINT ins.

1. mysql> ROLLBACK TO ins;

1. mysql> SELECT *FROM t_school;


I School_Na Number_Of_Stud Number_Of_Teac Number_Of_Classr
EmailID
D me ents hers ooms
Boys Town
[email protected]
1 Public 1000 80 12
om
School
Guru
Govind
ggps25@gmail.
2 Singh 800 35 15
com
Public
School
Delhi
dps101@gmail.
3 Public 1200 30 10
com
School
Ashoka
[email protected]
4 Universal 1110 40 40
om
School
Calibers
English [email protected]
5 9000 31 50
Medium m
School

After rolling back to ins, we can see that all the records are retrieved (including the deleted
record).
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.

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

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:

 UNION will be used to combine the result of two select statements.

 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

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

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

 This operator combines all the records from both the queries.

 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

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.

3. INTERSECT:

 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.

4. MINUS

 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.
Aggregate Functions
An aggregate function performs a calculation on a set of values, and returns a
single value. Except for COUNT(*), aggregate functions ignore null values.
Aggregate functions are often used with the GROUP BY clause of the SELECT
statement.

All aggregate functions are deterministic. In other words, aggregate functions


return the same value each time that they are called, when called with a specific set
of input values. The OVER clause may follow all aggregate functions, except the
STRING_AGG, GROUPING or GROUPING_ID functions .

Use aggregate functions as expressions only in the following situations:

• The select list of a SELECT statement (either a subquery or an outer query).


• A HAVING clause.

The main following aggregate functions used in sql are:


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.

o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.

Syntax

COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )

Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE

Item1 Com1 2 10

Item2 Com2 3 25

Item3 Com1 2 30

Item4 Com3 5 10

Item5 Com2 2 20

Item6 Cpm1 3 25

Item7 Com1 5 30

Item8 Com1 3 10

Item9 Com2 2 25
Item10 Com3 4 30

Example: COUNT()

SELECT COUNT(*)
FROM PRODUCT_MAST;

Output:

10

Example: COUNT with WHERE

SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;

Output:

Example: COUNT() with DISTINCT

SELECT COUNT(DISTINCT COMPANY)


FROM PRODUCT_MAST;

Output:

Example: COUNT() with GROUP BY

SELECT COMPANY, COUNT(*)


FROM PRODUCT_MAST
GROUP BY COMPANY;

Output:
Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING

SELECT COMPANY, COUNT(*)


FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING COUNT(*)>2;

Output:

Com1 5
Com2 3

SUM Function
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.

Syntax

SUM()
or
SUM( [ALL|DISTINCT] expression )

Example: SUM()

SELECT SUM(COST)
FROM PRODUCT_MAST;

Output:

670
Example: SUM() with WHERE

SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;

Output:

320

Example: SUM() with GROUP BY

SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3
GROUP BY COMPANY;

Output:

Com1 150
Com2 170

Example: SUM() with HAVING

SELECT COMPANY, SUM(COST)


FROM PRODUCT_MAST
GROUP BY COMPANY
HAVING SUM(COST)>=170;

Output:

Com1 335
Com3 170
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

AVG()
or
AVG( [ALL|DISTINCT] expression )

Example:

SELECT AVG(COST)
FROM PRODUCT_MAST;

Output:

67.00

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

MAX()
or
MAX( [ALL|DISTINCT] expression )

Example:

SELECT MAX(RATE)
FROM PRODUCT_MAST;

Output

30
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

MIN()
or
MIN( [ALL|DISTINCT] expression )

Example:

SELECT MIN(RATE)
FROM PRODUCT_MAST;

Output:

10
Nested Queries in SQL

Structured Query Language (SQL) is a programming language. SQL is used to manage data
stored in a relational database. SQL has the ability to nest queries. A nested query is a
query within another query. A nested query allows for more complex and specific data
retrieval. In this article, we will discuss nested queries in SQL, their syntax, and examples.

Nested Query

In SQL, a nested query involves a query that is placed within another query. The output of
the inner query is used by the outer query. A nested query has two SELECT statements: one
for the inner query and another for the outer query.

Syntax of Nested Queries

The basic syntax of a nested query involves placing one query inside of another query. The
inner query or subquery is executed first and returns a set of values that are then used by
the outer query. The syntax for a nested query is as follows:

SELECT column1, column2, ...

FROM table1

WHERE column1 IN ( SELECT column1

FROM table2

WHERE condition );

Types of Nested Queries in SQL

Subqueries can be either correlated or non-correlated


Non-correlated (or Independent) Nested Queries

Non-correlated (or Independent) Nested Queries : Non-correlated (or Independent)


subqueries are executed independently of the outer query. Their results are passed to the
outer query.

Correlated Nested Queries

Correlated subqueries are executed once for each row of the outer query. They use values
from the outer query to return results.

Execution Order in Independent Nested Queries

In independent nested queries, the execution order is from the innermost query to the
outer query. An outer query won't be executed until its inner query completes its execution.
The outer query uses the result of the inner query.

Operators Used in Independent Nested Queries

IN Operator

The IN Operator checks if a column value in the outer query's result is present in the inner
query's result. The final result will have rows that satisfy the IN condition.

NOT IN Operator

The NOT IN Operator checks if a column value in the outer query's result is not present in
the inner query's result. The final result will have rows that satisfy the NOT IN condition.

ALL Operator

The ALL Operator compares a value of the outer query's result with all the values of the
inner query's result and returns the row if it matches all the values.

ANY Operator

The ANY Operator compares a value of the outer query's result with all the inner query's
result values and returns the row if there is a match with any value.

Execution Order in Co-related Nested Queries


In correlated nested queries, the inner query uses values from the outer query, and the
execution order is di erent from that of independent nested queries.

 First, the outer query selects the first row.

 Inner query uses the value of the selected row. It executes its query and returns a
result set.

 Outer query uses the result set returned by the inner query. It determines whether
the selected row should be included in the final output.

 Steps 2 and 3 are repeated for each row in the outer query's result set.

 This process can be resource-intensive. It may lead to performance issues if the


query is not optimized properly.

Operators Used in Co-related Nested Queries

In co-related nested queries, the following operators can be used

EXISTS Operator

The EXISTS Operator checks whether a subquery returns any row. If it returns at least one
row. EXISTS operator returns true, and the outer query continues to execute. If the subquery
returns no row, the EXISTS operator returns false, and the outer query stops execution.

NOT EXISTS Operator

The NOT EXISTS Operator checks whether a subquery returns no rows. If the subquery
returns no row, the NOT EXISTS operator returns true, and the outer query continues to
execute. If the subquery returns at least one row, the NOT EXISTS operator returns false,
and the outer query stops execution.

ANY Operator

The ANY Operator compares a value of the outer query's result with one or more values
returned by the inner query. If the comparison is true for any one of the values returned by
the inner query, the row is included in the final result.

ALL Operator

The ALL Operator compares a value of the outer query's result with all the values returned
by the inner query. Only if the comparison is true for all the values returned by the inner
query, the row is included in the final result.

These operators are used to create co-related nested queries that depend on values from
the outer query for execution.

Examples

Consider the following sample table to execute nested queries on these.

Table: employees table


emp_id emp_name dept_id

1 John 1

2 Mary 2

3 Bob 1

4 Alice 3

5 Tom 1

Table: departments table

dept_id dept_name

1 Sales

2 Marketing

3 Finance

Table: sales table

sale_id emp_id sale_amt

1 1 1000

2 2 2000

3 3 3000

4 1 4000

5 5 5000

6 3 6000

7 2 7000

Example 1: Find the names of all employees in the Sales department.

Required query

SELECT emp_name

FROM employees

WHERE dept_id IN (SELECT dept_id

FROM departments

WHERE dept_name = 'Sales');


Output

emp_name

John

Bob

Tom

Example 2: Find the names of all employees who have made a sale

Required query

SELECT emp_name

FROM employees

WHERE EXISTS (SELECT emp_id

FROM sales

WHERE employees.emp_id = sales.emp_id);

Output

emp_name

John

Mary

Bob

Alice

Tom

This query selects all employees from the "employees" table where there exists a sale
record in the "sales" table for that employee.

Example 3: Find the names of all employees who have made sales greater than $1000.

Required query

SELECT emp_name

FROM employees

WHERE emp_id = ALL (SELECT emp_id

FROM sales

WHERE sale_amt > 1000);


Output

emp_name

John

Mary

Bob

Alice

Tom

This query selects all employees from the "employees" table. With the condition that where
their emp_id equals all the emp_ids in the "sales" table where the sale amount is greater
than $1000. Since all employees have made a sale greater than $1000, all employee names
are returned.

Advantages of Nested Queries

 Simplifies complex queries: Nested queries allow us to divide complicated SQL


tasks into smaller, more manageable parts. This modular approach makes queries
easier to write, debug, and maintain.

 Enhances flexibility: By enabling the use of results from one query within another,
nested queries allow dynamic filtering and indirect joins, which can simplify query
logic.

 Supports advanced analysis: Nested queries empower developers to perform


operations like conditional aggregation, subsetting, and customized calculations,
making them ideal for sophisticated data analysis tasks.

 Improves readability: When properly written, nested queries can make complex
operations more intuitive by encapsulating logic within inner queries.

Common SQL Operators for Nested Queries Examples


1. IN Operator

The IN operator is used to filter rows based on a set of values returned by a subquery. It is
commonly used to match a column value against a list or result set. This operator simplifies
queries by avoiding the need for multiple OR conditions.

Example: Retrieve student names who enrolled in ‘DSA’ or ‘DBMS’:

This query filters the students enrolled in the specified courses by chaining multiple nested
queries.
SELECT S_NAME FROM STUDENT
WHERE S_ID IN (
SELECT S_ID FROM STUDENT_COURSE
WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
)
);

2. NOT IN Operator

The NOT IN operator excludes rows based on a set of values from a subquery. It is
particularly useful for filtering out unwanted results. This operator helps identify records that
do not match the conditions defined in the subquery.

Example: Retrieve student IDs not enrolled in ‘DSA’ or ‘DBMS’:

This query excludes students who are enrolled in the courses ‘DSA’ or ‘DBMS’.

SELECT S_ID FROM STUDENT


WHERE S_ID NOT IN (
SELECT S_ID FROM STUDENT_COURSE
WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
)
);

Output

S_ID

S3

EXISTS

The EXISTS operator checks for the existence of rows in a subquery. It returns true if the
subquery produces any rows, making it efficient for conditional checks. This operator is
often used to test for relationships between tables.

Example: Find student names enrolled in ‘DSA’

The inner query checks for matching records in the STUDENT_COURSE table, and the
outer query returns the corresponding student names.

SELECT S_NAME FROM STUDENT S


WHERE EXISTS (
SELECT 1 FROM STUDENT_COURSE SC
WHERE S.S_ID = SC.S_ID AND SC.C_ID = 'C1'
);
ANY and ALL

The ANY operator compares a value with any value returned by the subquery, while ALL
ensures comparison with all values.

Example: Compare student age with all ages in the table:


SELECT S_NAME FROM STUDENT
WHERE S_AGE > ALL (
SELECT S_AGE FROM STUDENT WHERE S_ADDRESS = 'DELHI'
);
SQL Views
Views in SQL are a type of virtual table that simplifies how users interact with data across
one or more tables. Unlike traditional tables, a view in SQL does not store data on disk;
instead, it dynamically retrieves data based on a pre-defined query each time it’s
accessed.

SQL views are particularly useful for managing complex queries, enhancing security, and
presenting data in a simplified format. In this guide, we will cover the SQL create view
statement, updating and deleting views, and using the WITH CHECK OPTION clause.

What is a View in SQL?

A view in SQL is a saved SQL query that acts as a virtual table. It can fetch data from one or
more tables and present it in a customized format, allowing developers to:

 Simplify Complex Queries: Encapsulate complex joins and conditions into a single
object.

 Enhance Security: Restrict access to specific columns or rows.

 Present Data Flexibly: Provide tailored data views for di erent users.

We will be using these two SQL tables for examples.

StudentDetails

-- Create StudentDetails table

CREATE TABLE StudentDetails (

S_ID INT PRIMARY KEY,

NAME VARCHAR(255),

ADDRESS VARCHAR(255)

);

INSERT INTO StudentDetails (S_ID, NAME, ADDRESS)

VALUES

(1, 'Harsh', 'Kolkata'),

(2, 'Ashish', 'Durgapur'),


(3, 'Pratik', 'Delhi'),

(4, 'Dhanraj', 'Bihar'),

(5, 'Ram', 'Rajasthan');

StudentMarks

-- Create StudentMarks table

CREATE TABLE StudentMarks (

ID INT PRIMARY KEY,

NAME VARCHAR(255),

Marks INT,

Age INT

);

INSERT INTO StudentMarks (ID, NAME, Marks, Age)

VALUES

(1, 'Harsh', 90, 19),

(2, 'Suresh', 50, 20),

(3, 'Pratik', 80, 19),

(4, 'Dhanraj', 95, 21),

(5, 'Ram', 85, 18);


CREATE VIEWS in SQL

We can create a view using CREATE VIEW statement. A View can be created from a single
table or multiple tables.

Syntax:

CREATE VIEW view_name AS

SELECT column1, column2…..

FROM table_name

WHERE condition;

Parameters:

 view_name: Name for the View

 table_name: Name of the table

 condition: Condition to select rows

SQL CREATE VIEW Statement Examples

Let’s look at some examples of CREATE VIEW Statement in SQL to get a better
understanding of how to create views in SQL.

Example 1: Creating View From a Single Table

In this example, we will create a View named DetailsView from the table StudentDetails.
Query:

CREATE VIEW DetailsView AS

SELECT NAME, ADDRESS

FROM StudentDetails

WHERE S_ID < 5;

To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM DetailsView;

Output:

Example 2: Create View From Table

In this example, we will create a view named StudentNames from the table StudentDetails.
Query:

CREATE VIEW StudentNames AS

SELECT S_ID, NAME

FROM StudentDetails

ORDER BY NAME;

If we now query the view as,

SELECT * FROM StudentNames;

Output:

Example 3: Creating View From Multiple Tables

In this example we will create a View named MarksView from two tables StudentDetails
and StudentMarks. To create a View from multiple tables we can simply include multiple
tables in the SELECT statement. Query:

CREATE VIEW MarksView AS

SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS


FROM StudentDetails, StudentMarks

WHERE StudentDetails.NAME = StudentMarks.NAME;

To display data of View MarksView:

SELECT * FROM MarksView;

Output:

Listing all Views in a Database

We can list View using the SHOW FULL TABLES statement or using the
information_schema table. A View can be created from a single table or multiple tables.

Syntax:

USE "database_name";

SHOW FULL TABLES WHERE table_type LIKE "%VIEW";

Using information_schema

SELECT table_name

FROM information_schema.views

WHERE table_schema = 'database_name';

OR

SELECT table_schema, table_name, view_definition

FROM information_schema.views

WHERE table_schema = 'database_name';

Delete View in SQL


SQL allows us to delete an existing View. We can delete or drop View using the DROP
statement.

Syntax:

DROP VIEW view_name;

Example

In this example, we are deleting the View MarksView.

DROP VIEW MarksView;

Update View in SQL

If you want to update the existing data within the view, use the UPDATE statement.

Syntax:

UPDATE view_name

SET column1 = value1, column2 = value2...., columnN = valueN

WHERE [condition];

Note: Not all views can be updated using the UPDATE statement.

If you want to update the view definition without a ecting the data, use the CREATE OR
REPLACE VIEW statement. you can use this syntax

CREATE OR REPLACE VIEW view_name AS

SELECT column1, column2, ...

FROM table_name

WHERE condition;

Rules to Update Views in SQL:

Certain conditions need to be satisfied to update a view. If any of these conditions are not
met, the view can not be updated.

1. The SELECT statement which is used to create the view should not include GROUP
BY clause or ORDER BY clause.

2. The SELECT statement should not have the DISTINCT keyword.

3. The View should have all NOT NULL values.


4. The view should not be created using nested queries or complex queries.

5. The view should be created from a single table. If the view is created using multiple
tables then we will not be allowed to update the view.

Examples

Let’s look at di erent use cases for updating a view in SQL. We will cover these use cases
with examples to get a better understanding.

Example 1: Update View to Add or Replace a View Field

We can use the CREATE OR REPLACE VIEW statement to add or replace fields from a
view.

If we want to update the view MarksView and add the field AGE to this View from
StudentMarks Table, we can do this by:

CREATE OR REPLACE VIEW MarksView AS

SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS,


StudentMarks.AGE

FROM StudentDetails, StudentMarks

WHERE StudentDetails.NAME = StudentMarks.NAME;

If we fetch all the data from MarksView now as:

SELECT * FROM MarksView;

Output:

Example 2: Update View to Insert a row in a view

We can insert a row in a View in the same way as we do in a table. We can use the INSERT
INTO statement of SQL to insert a row in a View.

In the below example, we will insert a new row in the View DetailsView which we have
created above in the example of “creating views from a single table”.

INSERT INTO DetailsView(NAME, ADDRESS)


VALUES("Suresh","Gurgaon");

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;

Output:

Example 3: Deleting a row from a View

Deleting rows from a view is also as simple as deleting rows from a table. We can use the
DELETE statement of SQL to delete rows from a view. Also deleting a row from a view first
deletes the row from the actual table and the change is then reflected in the view.

In this example, we will delete the last row from the view DetailsView which we just added
in the above example of inserting rows.

DELETE FROM DetailsView

WHERE NAME="Suresh";

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;

Output:
WITH CHECK OPTION Clause

The WITH CHECK OPTION clause in SQL is a very useful clause for views. It applies to an
updatable view.

The WITH CHECK OPTION clause is used to prevent data modification (using INSERT or
UPDATE) if the condition in the WHERE clause in the CREATE VIEW statement is not
satisfied.

If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and if the
UPDATE or INSERT clause does not satisfy the conditions then they will return an error.

WITH CHECK OPTION Clause Example:

In the below example, we are creating a View SampleView from the StudentDetails Table
with a WITH CHECK OPTION clause.

CREATE VIEW SampleView AS

SELECT S_ID, NAME

FROM StudentDetails

WHERE NAME IS NOT NULL

WITH CHECK OPTION;

In this view, if we now try to insert a new row with a null value in the NAME column then it
will give an error because the view is created with the condition for the NAME column as
NOT NULL. For example, though the View is updatable then also the below query for this
View is not valid:

INSERT INTO SampleView(S_ID)

VALUES(6);

NOTE: The default value of NAME column is null.

Uses of a View

A good database should contain views for the given reasons:

1. Restricting data access – Views provide an additional level of table security by


restricting access to a predetermined set of rows and columns of a table.

2. Hiding data complexity – A view can hide the complexity that exists in multiple
joined tables.
3. Simplify commands for the user – Views allow the user to select information from
multiple tables without requiring the users to actually know how to perform a join.

4. Store complex queries – Views can be used to store complex queries.

5. Rename Columns – Views can also be used to rename the columns without
a ecting the base tables provided the number of columns in view must match the
number of columns specified in a select statement. Thus, renaming helps to hide
the names of the columns of the base tables.

6. Multiple view facility – Di erent views can be created on the same table for
di erent users.
1

PL/SQL:

 1) PL/SQL (Procedural Language/Structured Query Language):


1. PL/SQL stands for Procedural Language extension of SQL.
2. PL/SQL is a combination of SQL along with the procedural features of programming
languages.
3. It was developed by Oracle Corporation in the early 90’s to enhance the capabilities ofSQL.

PL/SQL Block Structure:


1. A PL/SQL block contains 1 or more PL/SQL statements.
2. Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQLblock.

Syntax:
Declare
Variable declaration
Begin
Process statements
Or execution statement
[Exception
Exception statement]
End;
A PL/SQL block can be divided into four sections. They are
1. Declaration section
2. Begin section
3. Exception section
4. End section
1. Declaration Section:
 Code blocks start with a declaration section
 In this block memory variable and other oracle objects can be declared
2

 They can be used in SQL statements for data manipulation.


Example:
Declare
First_name varhcar2(10);
Num number(10);

2. Begin Section:
 It consists of a set of SQL and PL/SQL statements
 It describes process that has to be applied to table data.
 Actual data manipulation, retrieval, looping and branching constructs arespecified in this
section.

3. Exception Section:
 This section deals with handling of errors
 That arise during execution of the data manipulation statements
 The errors can arise due to syntax and logic.
4. End Section:
a. This makes the end of a PL/SQL block.
Example:
Declare
a number(4);
b number(4);
c number(4);
begin
b:=20;
c:=a+b;
dbms_output.put_line(c);
end;
1. dbms_ouput: it is a package.
2. That includes a number of procedures and functions that accumulate informationin a buffer so
that it can be retrieved later.
3. These functions can also be used to display message.
4. put_line: put a piece of information in the package buffer followed by an end-of-line marker.
5. dbms_ouput.put_line(‘Hello’);
3

 PL/SQL Language Elements

There are different elements


1. Character Set
2. Lexical Units
a. Delimiters
b. Identifiers
c. Literals
d. Comments

1. Character Set
1. A PL/SQL program consists of text having specific set of characters.
2. Character set may include the following characters:
a. Alphabets, both in upper case [A–Z] and lower case [a–z]
b. Numeric digits [0–9]
c. Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ %
d. Blank spaces, tabs, and carriage returns.

2. Lexical Units
1. A line of PL/SQL program contains groups of characters known as lexical units,which can be
classified as follows:
A. Delimiters
B. Identifiers
C. Literals
D. Comments

A. Delimiters
a. A delimiter is a simple or compound symbol
b. That has a special meaning to PL/SQL.
c. Simple symbol consists of one character
d. Compound symbol consists of more than one character.
B. Identifiers
a. Identifiers are used in the PL/SQL programs
4

b. To name the PL/SQL program items


i. Like constants, variables, cursors, cursor variables, subprograms,etc.
c. Identifiers can consists of alphabets, numerals, dollar
signs,underscores, and number signs only.
d. Any other characters like hyphens, slashes, blank spaces, etc.

C. Literals
a. A literal is an explicitly defined character, string, numeric, or Booleanvalue,
D. Comments
1. Comments are used in the PL/SQL program
2. It used to improve the readability and understandability of a program.
3. A comment can appear anywhere in the program code.
4. The compiler ignores comments.
5. Generally, comments are used to describe the purpose and use of eachcode segment.
Ex: /* Hello World! This is an example of multiline comments in PL/SQL */
Q) Introduction to PL/SQL data types

Each value in PL/SQL such as a constant, variable and parameter has a data type that determines the
storage format, valid values, and allowed operations.

PL/SQL has two kinds of data types: scalar and composite. The scalar types are types that store single
values such as number, Boolean, character, and datetime whereas the composite types are types that
store multiple values, for example, record and collection.

This tutorial explains the scalar data types that store values with no internal components.

PL/SQL divides the scalar data types into four families:

 Number
 Boolean
 Character
 Datetime

A scalar data type may have subtypes. A subtype is a data type that is a subset of another data type,
which is its base type. A subtype further defines a base type by restricting the value or size of the base
data type.
5

Numeric data types

The numeric data types represent real numbers, integers, and floating-point numbers. They are stored
as NUMBER, IEEE floating-point storage types (BINARY_FLOAT and BINARY_DOUBLE),
and PLS_INTEGER.

Boolean data type

The BOOLEAN datatype has three data values: TRUE, FALSE, and NULL. Boolean values are
typically used in control flow structure such as IF-THEN, CASE, and loop statements like LOOP, FOR
LOOP, and WHILE LOOP.

SQL does not have the BOOLEAN data type, therefore, you cannot:

 Assign a BOOLEAN value to a table column.


 Select the value from a table column into a BOOLEAN variable.
 Use a BOOLEAN value in a SQL function.
 Use a BOOLEAN expression in a SQL statement.
 Use a BOOLEAN value in
the DBMS_OUTPUT.PUTLINE and DBMS_OUTPUT.PUT subprograms.

Character data types

The character data types represent alphanumeric text. PL/SQL uses the SQL character data types such
as CHAR, VARCHAR2, LONG, RAW, LONG RAW, ROWID, and UROWID.

 CHAR(n) is a fixed-length character type whose length is from 1 to 32,767 bytes.


 VARCHAR2(n) is varying length character data from 1 to 32,767 bytes.

Datetime data types

The date time data types represent dates, timestamp with or without time zone and intervals.
PL/SQL datetime data types are DATE, TIMESTAMP, TIMESTAMP WITH TIME
ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL YEAR TO MONTH,
and INTERVAL DAY TO SECOND.

Data type Description


Char Character value of fixed length
Varchar2 Variable length character value
Number Numeric values
Date Date values
Inherits the data type from a variable that you declaredpreviously in
% type
database table.
6

It is used to declare variable to keep a single record, since a record is


% row
nothing but collection of column. This is also known ascomposite data
type
type.
Boolean data type can be used to store the values true, false ornull.
Boolean

PL SQL Operator Operator Precedence

Operator Description

** Exponentiation

+, - Identity, negation (unary operation)

*, / Multiplication, division

+, -, || Addition, subtraction, concatenation

=, <, >, <=, >=, <>, !=, ~= Comparison


IS NULL, LIKE, BETWEEN, IN

NOT Logical negation

AND Conjunction

OR Inclusion

Q) Explain Control Structures in PL/SQL?


The follow of control statements can be classified into the following categories.
1. Conditional control
2. Iterative control
3. Sequential control

Conditional control
1. Conditional control, which run different statements for different data values.
2. It check the condition for single time only even it is true or false
7

3. The conditional control statements are If and case.


a. IF
i. If then statement

ii. If then else statement


iii. If then else if statement
iv. Nested if statement
b. Case
 If statement
If condition is true it can execute statement 1 to statement n otherwise itcannot execute statement 1 to
statement n.

Syntax:
if(condition) then
Statement 1;
… ................ Statement n;
End if;

Example:
DECLARE
a number:=&a;
BEGIN
if(a<10)then
dbms_output.put_line(‘welcome to pl/sql’);
end if;
END;

 If then else statement


If condition is true it can execute statement 1. If the condition is false itexecute else statement or
execute statement 2.

Syntax:
if(condition) then
Statement 1;
else
end if;
statement 2;
8

Example:
declare
a integer;
b integer; begin
a:=&a; /* it take run time values*/
b:=&b; /* it take run time values*/
if(a>b) then
dbms_output.put_line(‘A is big’);
else
dbms_output.put_line(‘b is big’);
end if;
end;

 If then else if statement


If condition is true it can execute statement 1. If the condition is false its again chek for another condition
if it is true it can execute statement 2. Other execute else statement or execute statement 3.

Syntax:
if(condition) then
Statement 1;
elsif(condition) then
statement 2;
else
statement 3;
end if;

Example:
declare
a integer; b integer;
c integer;
begin
a:=&a;
b:=&b;
c:=&c;
9

if(a>b and a>c)


then dbms_output.put_line(‘a is big’);
elsif(b>c) then
dbms_output.put_line(‘b is big’);
else
dbms_output.put_line(‘c is big’);
end if;
end;

 Nested if statement
Inner if is called nested if. if condition is false it execute stamen 3. Other wise it is true its check for
another condition if it is true it execute statement 1 other wise execute statement 2.
Syntax:
if(condition) then
if(condition) then
statement 1;
else
statement 2;
end if;else
statement 3;
end if;
 Case:
Syntax
case variable_name
When value1 then stmt; When value2 then stmt;
… ............... Else stmt;
End case;
1. The case statement runs the first statements for which value equals variablename remaining
conditions are not evaluated.
2. If no value equals to variable name, the case statements runs else statements.
10

Ex:

Declare

Grade char:=’&grade’;

Begin

case grade
when ‘A’ then
dbms_output.put_line(‘Excellent’);
when ‘B’ then
dbms_output.put_line(‘Very good’);
when ‘C’ then
dbms_output.put_line(‘Good’);
when ‘D’ then
dbms_output.put_line(‘Fair’);
when ‘F’ then
dbms_output.put_line(‘poor’);
else
dbms_output.put_line(‘no such grade’);
end case;
end;

Q) Iterative control (or) Loop controls

The PL/SQL loops are used to repeat the execution of one or more statements for specified number of
times. These are also known as iterative control statements.

Syntax for a basic loop:

LOOP
Sequence of statements;
END LOOP;
11

Types of PL/SQL Loops

There are 3 types of PL/SQL Loops.

1. Basic Loop / Exit Loop


2. While Loop
3. For Loop

PL/SQL Exit Loop (Basic Loop)

PL/SQL exit loop is used when a set of statements is to be executed at least once before the termination
of the loop. There must be an EXIT condition specified in the loop, otherwise the loop will get into an
infinite number of iterations. After the occurrence of EXIT condition, the process exits the loop.

Syntax of basic loop:

LOOP
Sequence of statements;
END LOOP;

Syntax of exit loop:

LOOP
statements;
EXIT;
{or EXIT WHEN condition;} END LOOP;

Follow these steps while using PL/SQL Exit Loop.

o Initialize a variable before the loop body


o Increment the variable in the loop.
o You should use EXIT WHEN statement to exit from the Loop. Otherwise the EXIT statement
without WHEN condition, the statements in the Loop is executed only once.
12

Example :

DECLARE
i NUMBER := 1;
BEGIN
LOOP
EXIT WHEN i>10;
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;

PL/SQL While Loop

PL/SQL while loop is used when a set of statements has to be executed as long as a condition is true, the
While loop is used. The condition is decided at the beginning of each iteration and continues until the
condition becomes false.

Syntax of while loop:

WHILE <condition>
LOOP statements;
END LOOP;

Follow these steps while using PL/SQL WHILE Loop.

o Initialize a variable before the loop body.


o Increment the variable in the loop.
o You can use EXIT WHEN statements and EXIT statements in While loop but it is not done often.

Example of PL/SQL While Loop

DECLARE
i INTEGER := 1;
BEGIN
13

WHILE i <= 10 LOOP


DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;

PL/SQL FOR Loop

PL/SQL for loop is used when when you want to execute a set of statements for a predetermined number
of times. The loop is iterated between the start and end integer values. The counter is always incremented
by 1 and once the counter reaches the value of end integer, the loop ends.

Syntax of for loop:

FOR counter IN initial_value .. final_value LOOP


LOOP statements;
END LOOP;
o initial_value : Start integer value
o final_value : End integer value

Follow these steps while using PL/SQL WHILE Loop.

o You don't need to declare the counter variable explicitly because it is declared implicitly in the
declaration section.

o The counter variable is incremented by 1 and does not need to be incremented explicitly.
o You can use EXIT WHEN statements and EXIT statements in FOR Loops but it is not done often.

PL/SQL For Loop Example


DECLARE
VAR1 NUMBER;
BEGIN
VAR1:=10;
FOR VAR2 IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
END LOOP; END;
14

Q) PL/SQL Procedure

The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more
specific tasks. It is just like procedures in other programming languages.

The procedure contains a header and a body.

o Header: The header contains the name of the procedure and the parameters or variables passed to
the procedure.

o Body: The body contains a declaration section, execution section and exception section similar to
a general PL/SQL block.

Creating a Procedure

A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −

CREATE [OR REPLACE] PROCEDURE procedure_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;

Where,

 procedure-name specifies the name of the procedure.


 [OR REPLACE] option allows the modification of an existing procedure.
 The optional parameter list contains name, mode and types of the parameters. IN represents the
value that will be passed from outside and OUT represents the parameter that will be used to return
a value outside of the procedure.
 procedure-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone procedure.
15

Example :
The following example creates a simple procedure that displays the string 'Hello World!' on the screen
when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/

When the above code is executed using the SQL prompt, it will produce the following result −

Procedure created.
Executing a Standalone Procedure

A standalone procedure can be called in two ways −

 Using the EXECUTE keyword


 Calling the name of the procedure from a PL/SQL block

The above procedure named 'greetings' can be called with the EXECUTE keyword as −

EXECUTE greetings;

The above call will display −

Hello World
PL/SQL procedure successfully completed.

The procedure can also be called from another PL/SQL block −

BEGIN
greetings;
END;
/

The above call will display − Hello World . PL/SQL procedure successfully completed.

Deleting a Standalone Procedure

A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a
procedure is −
16

DROP PROCEDURE procedure-name;

You can drop the greetings procedure by using the following statement −

DROP PROCEDURE greetings;


Parameter Modes in PL/SQL Subprograms
1. IN parameters: The IN parameter can be referenced by the procedure or function. The value of
the parameter cannot be overwritten by the procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the procedure or function, but
the value of the parameter can be overwritten by the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the procedure or function and
the value of the parameter can be overwritten by the procedure or function.

Q) PL/SQL Function

The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between procedure and
a function is, a function must always return a value, and on the other hand a procedure may or may not
return a value. Except this, all the other things of PL/SQL procedure are true for PL/SQL function too.

Syntax to create a function:

CREATE [OR REPLACE] FUNCTION function_name [parameters]


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

Here:

o Function_name: specifies the name of the function.


o [OR REPLACE] option allows modifying an existing function.
o The optional parameter list contains name, mode and types of the parameters.
o IN represents that value will be passed from outside and OUT represents that this parameter will
be used to return a value outside of the procedure.
17

The function must contain a return statement.


o RETURN clause specifies that data type you are going to return from the function.
o Function_body contains the executable part.
o The AS keyword is used instead of the IS keyword for creating a standalone function.

EXAMPLE :
create or replace function adder(n1 in number, n2 in number)
return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;
/
Calling PL/SQL Function:While creating a function, you have to give a definition of what the function
has to do. To use a function, you will have to call that function to perform the defined task. Once the
function is called, the program control is transferred to the called function.

After the successful completion of the defined task, the call function returns program control back to the
main program.

To call a function you have to pass the required parameters along with function name and if function
returns a value then you can store returned value

Example

Create Function:

CREATE OR REPLACE FUNCTION totalCustomers


RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
18

RETURN total;
END;
/

After the execution of above code, you will get the following result.

Function created.
Calling function code:
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
PL/SQL Drop Function

If you want to remove your created function from the database, you should use the following syntax.

DROP FUNCTION function_name;

Q) TRIGGERS AND ITS TYPES

Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers
are, in fact, written to be executed in response to any of the following events −

 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)


 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVER ERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

Triggers can be defined on the table, view, schema, or database with which the event is associated.

Benefits of Triggers

Triggers can be written for the following purposes −

 Generating some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
19

 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions
Creating a trigger:

Syntax for creating trigger:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Here,

o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger with
the trigger_name.

o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The
INSTEAD OF clause is used for creating trigger on a view.

o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
20

o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various
DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each
row being affected. Otherwise the trigger will execute just once when the SQL statement is
executed, which is called a table level trigger.

o WHEN (condition): This provides a condition for rows for which the trigger would fire. This
clause is valid only for row level triggers.

Type of Triggers

1. BEFORE Trigger: BEFORE trigger execute before the triggering DML statement (INSERT,
UPDATE, DELETE) execute. Triggering SQL statement is may or may not execute, depending
on the BEFORE trigger conditions block.
2. AFTER Trigger: AFTER trigger execute after the triggering DML statement (INSERT,
UPDATE, DELETE) executed. Triggering SQL statement is execute as soon as followed by the
code of trigger before performing Database operation.
3. ROW Trigger: ROW trigger fire for each and every record which are performing INSERT,
UPDATE, DELETE from the database table. If row deleting is define as trigger event, when
trigger file, deletes the five rows each times from the table.
4. Statement Trigger: Statement trigger fire only once for each statement. If row deleting is define
as trigger event, when trigger file, deletes the five rows at once from the table.
5. Combination Trigger: Combination trigger are combination of two trigger type,
1. Before Statement Trigger: Trigger fire only once for each statement before the
triggering DML statement.
2. Before Row Trigger : Trigger fire for each and every record before the triggering DML
statement.
3. After Statement Trigger: Trigger fire only once for each statement after the triggering
DML statement executing.
4. After Row Trigger: Trigger fire for each and every record after the triggering DML
statement executing.
DBMS
(DATABASE MANAGEMENT SYSTEM)
II Year ,IV Sem
Integrity Constraints
•Integrity constraints are a set of rules.
•Condition that is satisfied.
•It is used to maintain the quality of information.
• Integrity constraints ensure that the changes ,data
insertion, updating, and other processes have to be
performed in such a way that data integrity is not
affected.
•Thus, integrity constraint is used to guard against
accidental damage to the database.
•It is the rules that database is not permitted to
violate.
Integrity Constraints..
•Integrity constraints used to ensure accuracy and
consistency of the data in a relational database,
•Constraints may apply to each attribute or they
may apply to the relationship between
tables(foreign key).
•Here changes made to the database by authorized
users donot result in a loss of data consistency.
•Example :- Blood Group:- A,B,AB,O not C D E
1. Domain constraints
•Domain constraints can be defined as the definition of a valid set of
values for an attribute.
•It defines domain only.
•The data type of domain includes string, character, integer, time,
date, currency, etc. The value of the attribute must be available in
the corresponding domain. Example is phone number has only 10
digits.

Example:-
2. Entity integrity constraints

•The entity integrity constraint states that primary key


value can't be null.
•This is because the 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.
•Entity integrity constraints will violate here.
•A table can contain a null value other than the primary
key field.
2. Entity integrity constraints…..

Example:-
3. Referential Integrity Constraints

•A referential integrity constraint is specified between


two tables.

•In the Referential integrity constraints, if a foreign key


in Table 1 refers to the Primary Key of Table 2, then
every value of the Foreign Key in Table 1 must be null or
be available in Table 2.
3. Referential Integrity Constraints……
4. Key constraints

Keys are the entity set that is used to identify an


entity within its entity set uniquely.
An entity set can have multiple keys, but out of
which one key will be the primary key. A primary
key can contain a unique and null value in the
relational table.
Example:
Functional Dependency
The functional dependency is a relationship that exists
between two attributes. It typically exists between the
primary key and non-key attribute within a table.

X → Y
The left side of FD is known as a determinant, the right
side of the production is known as a dependent.
For example:
Assume we have an employee table with attributes:
Emp_Id, Emp_Name, Emp_Address.
Functional Dependency…

Here Emp_Id attribute can uniquely identify the


Emp_Name attribute of employee table because if we
know the Emp_Id, we can tell that employee name
associated with it.

Functional dependency can be written as:


Emp_Id → Emp_Name

Here Emp_Name is functionally dependent on Emp_Id.


Types of Functional dependency
1. Trivial functional dependency
A → B has trivial functional dependency if B is a subset of
A.
The following dependencies are also trivial like: A → A, B
→B

Consider a table with two columns Employee_Id and Empl


oyee_Name. {Employee_id, Employee_Name} → Empl
oyee_Id is a trivial functional dependency as Employee_I
d is a subset of {Employee_Id, Employee_Name}. Also, E
mployee_Id → Employee_Id and Employee_Name → E
mployee_Name are trivial dependencies too.
2. Non- Trivial functional dependency

A → B has a non-trivial functional dependency if B is not a


subset of A.
When A intersection B is NULL, then A → B is called as
complete non-trivial.
Example:
ID → Name,
Name → DOB
Inference Rule (IR):

➢The Armstrong's axioms are the basic inference rule.


➢Armstrong's axioms are used to conclude functional
dependencies on a relational database.
➢The inference rule is a type of assertion. It can apply to a
set of FD(functional dependency) to derive other FD.
➢Using the inference rule, we can derive additional
functional dependency from the initial set.
➢The Functional dependency has 6 types of inference rule:
1. Reflexive Rule (IR1)
In the reflexive rule, if Y is a subset of X, then X determines
Y.
If X ⊇ Y then X → Y

Example:
X = {a, b, c, d, e}
Y = {a, b, c}
2. Augmentation Rule (IR2)
The augmentation is also called as a partial dependency. In
augmentation, if X determines Y, then XZ determines YZ for
any Z.

If X → Y then XZ → YZ
Example:
For R(ABCD), if A → B then AC → BC
3. Transitive Rule (IR3)
In the transitive rule, if X determines Y and Y determine Z,
then X must also determine Z.
If X → Y and Y → Z then X → Z
4. Union Rule (IR4)
Union rule says, if X determines Y and X determines Z, then
X must also determine Y and Z.
If X → Y and X → Z then X → YZ
Proof:
1. X → Y (given)
2. X → Z (given)
3. X → XY (using IR2 on 1 by augmentation with X. Where
XX = X)
4. XY → YZ (using IR2 on 2 by augmentation with Y)
5. X → YZ (using IR3 on 3 and 4)
5. Decomposition Rule (IR5)
Decomposition rule is also known as project rule. It is the
reverse of union rule.
This Rule says, if X determines Y and Z, then X determines Y
and X determines Z separately.
If X → YZ then X → Y and X → Z
Proof:
1. X → YZ (given)
2. YZ → Y (using IR1 Rule)
3. X → Y (using IR3 on 1 and 2)
6. Pseudo transitive Rule (IR 6)
In Pseudo transitive Rule, if X determines Y and YZ
determines W, then XZ determines W.
If X → Y and YZ → W then XZ → W
Proof:
1. X → Y (given)
2. WY → Z (given)
3. WX → WY (using IR2 on 1 by augmenting with W)
4. WX → Z (using IR3 on 3 and 2)
Normalization
❖Normalization is the process of organizing the data in the
database.
❖Normalization is used to minimize the redundancy from a
relation or set of relations.
❖It is also used to eliminate the undesirable characteristics
like Insertion, Update and Deletion Anomalies.
❖Normalization divides the larger table into the smaller
table and links them using relationship.
❖The normal form is used to reduce redundancy from the
database table.
Normalization
➢ This is the process which allows you to winnow out
redundant data within your database.
➢ This involves restructuring the tables to successively
meeting higher forms of Normalization.
➢ A properly normalized database should have the
following characteristics
1. Scalar values in each fields
2. Absence of redundancy.
3. Minimal use of null values.
4. Minimal loss of information.
Levels of Normalization
Levels of normalization based on the amount of
redundancy in the database.
Various levels of normalization are:
1. First Normal Form (1NF)
2. Second Normal Form (2NF)

Redundancy

Number of Tables
3. Third Normal Form (3NF)

Complexity
4. Boyce-Codd Normal Form (BCNF)
5. Fourth Normal Form (4NF)
6. Fifth Normal Form (5NF)

Most databases should be 3NF or BCNF in order to avoid the database anomalies.
Levels of Normalization
1NF
2NF
3NF
4NF
5NF

Each higher level is a subset of the lower level


First Normal Form (1NF)
➢A relation will be 1NF if it contains an atomic value.
➢It states that an attribute of a table cannot hold
multiple values. It must hold only single-valued
attribute.
➢First normal form disallows the multi-valued
attribute, composite attribute, and their combinations.
First Normal Form (1NF)
A table is considered to be in 1NF if all the fields contain
only scalar values (as opposed to list of values).
Example (Not 1NF)
AuName & Auphone is not in 1NF

ISBN Title AuName AuPhone PubName PubPhone Price

0-321-32132-1 Balloon Sleepy, 321-321-1111, Small House 714-000-0000 $34.00


Snoopy, 232-234-1234,
Grumpy 665-235-6532

0-55-123456-9 Main Street Jones, 123-333-3333, Small House 714-000-0000 $22.95


Smith 654-223-3455
0-123-45678-0 Ulysses Joyce 666-666-6666 Alpha Press 999-999-9999 $34.00

1-22-233700-0 Visual Roman 444-444-4444 Big House 123-456-7890 $25.00


Basic

Author and AuPhone columns are not scalar


1NF - Decomposition
1. Place all items that appear in the repeating group in a new
table
2. Designate a primary key for each new table produced.
3. Duplicate in the new table the primary key of the table from
which the repeating group was extracted or vice versa.
Example (1NF)

ISBN AuName AuPhone

0-321-32132-1 Sleepy 321-321-1111

ISBN Title PubName PubPhone Price 0-321-32132-1 Snoopy 232-234-1234

0-321-32132-1 Balloon Small House 714-000-0000 $34.00 0-321-32132-1 Grumpy 665-235-6532

0-55-123456-9 Main Street Small House 714-000-0000 $22.95 0-55-123456-9 Jones 123-333-3333

0-123-45678-0 Ulysses Alpha Press 999-999-9999 $34.00 0-55-123456-9 Smith 654-223-3455

1-22-233700-0 Visual Big House 123-456-7890 $25.00 0-123-45678-0 Joyce 666-666-6666


Basic
1-22-233700-0 Roman 444-444-4444
Functional Dependencies
1. If one set of attributes in a table determines another
set of attributes in the table, then the second set of
attributes is said to be functionally dependent on the
first set of attributes.

Example 1

ISBN Title Price Table Scheme: {ISBN, Title, Price}


0-321-32132-1 Balloon $34.00 Functional Dependencies: {ISBN} → {Title}
0-55-123456-9 Main Street $22.95
{ISBN} → {Price}
0-123-45678-0 Ulysses $34.00

1-22-233700-0 Visual $25.00


Basic
Functional Dependencies
Example 2
PubID PubName PubPhone Table Scheme: {PubID, PubName, PubPhone}
1 Big House 999-999-9999 Functional Dependencies: {PubId} → {PubPhone}
2 Small House 123-456-7890 {PubId} → {PubName}
3 Alpha Press 111-111-1111 {PubName, PubPhone} → {PubID}

Example 3

AuID AuName AuPhone


1 Sleepy 321-321-1111
Table Scheme: {AuID, AuName, AuPhone}
2 Snoopy 232-234-1234
Functional Dependencies: {AuId} → {AuPhone}
3 Grumpy 665-235-6532
{AuId} → {AuName}
4 Jones 123-333-3333
{AuName, AuPhone} → {AuID}
5 Smith 654-223-3455

6 Joyce 666-666-6666

7 Roman 444-444-4444
Second Normal Form (2NF)
For a table to be in 2NF, there are two requirements
➢ The database is in first normal form
➢ All non-key attributes in the table must be functionally
dependent on the entire primary key
➢ The table should not contain any partial dependency.
Note: Remember that we are dealing with non-key attributes

Example 1 (Not 2NF)


Scheme → {Title, PubId, AuId, Price, AuAddress}
1. Key → {Title, PubId, AuId}
2. {Title, PubId, AuID} → {Price}
3. {AuID} → {AuAddress}
4. AuAddress does not belong to a key
5. AuAddress functionally depends on AuId which is a
subset of a key
Second Normal Form (2NF)
Example 2 (Not 2NF)
Scheme → {City, Street, HouseNumber, HouseColor, CityPopulation}
1. key → {City, Street, HouseNumber}
2. {City, Street, HouseNumber} → {HouseColor}
3. {City} → {CityPopulation}
4. CityPopulation does not belong to any key.
5. CityPopulation is functionally dependent on the City which is a proper subset of
the key

Example 3 (Not 2NF)


Scheme → {studio, movie, budget, studio_city}
1. Key → {studio, movie}
2. {studio, movie} → {budget}
3. {studio} → {studio_city}
4. studio_city is not a part of a key
5. studio_city functionally depends on studio which is a proper subset of the key
2NF - Decomposition
1. If a data item is fully functionally dependent on only a part of the
primary key, move that data item and that part of the primary key
to a new table.
2. If other data items are functionally dependent on the same part of
the key, place them in the new table also
3. Make the partial primary key copied from the original table the
primary key for the new table. Place all items that appear in the
repeating group in a new table
Example 1 (Convert to 2NF)
Old Scheme → {Title, PubId, AuId, Price, AuAddress}
New Scheme → {Title, PubId, AuId, Price}
New Scheme → {AuId, AuAddress}
2NF - Decomposition
Example 2 (Convert to 2NF)
Old Scheme → {Studio, Movie, Budget, StudioCity}
New Scheme → {Movie, Studio, Budget}
New Scheme → {Studio, City}

Example 3 (Convert to 2NF)


Old Scheme → {City, Street, HouseNumber, HouseColor, CityPopulation}
New Scheme → {City, Street, HouseNumber, HouseColor}
New Scheme → {City, CityPopulation}
Third Normal Form (3NF)
This form dictates that all non-key attributes of a table must be functionally
dependent on a candidate key i.e. there can be no interdependencies among
non-key attributes.

For a table to be in 3NF, there are two requirements


The table should be second normal form
No attribute is transitively dependent on the primary key
➢. The table or relation should be in 2NF.
➢It should not contain any transitive dependency. A Transitive Dependency is that
any non-prime attribute determines or depends on the other non-prime attribute.
➢It is used to reduce the data duplication. It is also used to achieve the data integrity.
➢If there is no transitive dependency for non-prime attributes, then the relation must
be in third normal form
Example (Not in 3NF)
Scheme → {Title, PubID, PageCount, Price }
1. Key → {Title, PubId}
2. {Title, PubId} → {PageCount}
3. {PageCount} → {Price}
4. Both Price and PageCount depend on a key hence 2NF
5. Transitively {Title, PubID} → {Price} hence not in 3NF
Third Normal Form (3NF)
Example 2 (Not in 3NF)
Scheme → {Studio, StudioCity, CityTemp}
1. Primary Key → {Studio}
2. {Studio} → {StudioCity}
3. {StudioCity} → {CityTemp}
4. {Studio} → {CityTemp}
5. Both StudioCity and CityTemp depend on the entire key hence 2NF
6. CityTemp transitively depends on Studio hence violates 3NF

Example 3 (Not in 3NF)


Scheme → {BuildingID, Contractor, Fee} BuildingID Contractor Fee
1. Primary Key → {BuildingID} 100 Randolph 1200
2. {BuildingID} → {Contractor}
150 Ingersoll 1100
3. {Contractor} → {Fee}
4. {BuildingID} → {Fee} 200 Randolph 1200
5. Fee transitively depends on the BuildingID 250 Pitkin 1100
6. Both Contractor and Fee depend on the entire key hence 2NF
300 Randolph 1200
3NF - Decomposition
1. Move all items involved in transitive dependencies to a new
entity.
2. Identify a primary key for the new entity.
3. Place the primary key for the new entity as a foreign key on the
original entity.

Example 1 (Convert to 3NF)


Old Scheme → {Title, PubID, PageCount, Price }
New Scheme → {PubID, PageCount, Price}
New Scheme → {Title, PubID, PageCount}
3NF - Decomposition
Example 2 (Convert to 3NF)
Old Scheme → {Studio, StudioCity, CityTemp}
New Scheme → {Studio, StudioCity}
New Scheme → {StudioCity, CityTemp}

Example 3 (Convert to 3NF) BuildingID Contractor Contractor Fee

Old Scheme → {BuildingID, Contractor, Fee} 100 Randolph Randolph 1200


150 Ingersoll Ingersoll 1100
New Scheme → {BuildingID, Contractor}
200 Randolph Pitkin 1100
New Scheme → {Contractor, Fee} 250 Pitkin
300 Randolph
Boyce-Codd Normal Form (BCNF)
BCNF does not allow dependencies between attributes that belong to candidate keys.
BCNF is a refinement of the third normal form in which it drops the restriction of a non-key
attribute from the 3rd normal form.
Third normal form and BCNF are not same if the following conditions are true:
The table has two or more candidate keys
At least two of the candidate keys are composed of more than one attribute
The keys are not disjoint i.e. The composite candidate keys share some attributes

•A table or relation must be in 3NF.


•If a relation R has functional dependencies (FD) and if A determines B, where A is
a super Key, the relation is in BCNF.

Example 1 - Address (Not in BCNF)


Scheme → {City, Street, ZipCode }
1. Key1 → {City, Street }
2. Key2 → {ZipCode, Street}
3. No non-key attribute hence 3NF
4. {City, Street} → {ZipCode}
5. {ZipCode} → {City}
6. Dependency between attributes belonging to a key
Boyce Codd Normal Form (BCNF)
Example 2 - Movie (Not in BCNF)
Scheme → {MovieTitle, MovieID, PersonName, Role, Payment }
1. Key1 → {MovieTitle, PersonName}
2. Key2 → {MovieID, PersonName}
3. Both role and payment functionally depend on both candidate keys thus 3NF
4. {MovieID} → {MovieTitle}
5. Dependency between MovieID & MovieTitle Violates BCNF

Example 3 - Consulting (Not in BCNF)


Scheme → {Client, Problem, Consultant}
1. Key1 → {Client, Problem}
2. Key2 → {Client, Consultant}
3. No non-key attribute hence 3NF
4. {Client, Problem} → {Consultant}
5. {Client, Consultant} → {Problem}
6. Dependency between attributess belonging to keys violates BCNF
BCNF - Decomposition
1. Place the two candidate primary keys in separate
entities
2. Place each of the remaining data items in one of the
resulting entities according to its dependency on the
primary key.
Example 1 (Convert to BCNF)
Old Scheme → {City, Street, ZipCode }
New Scheme1 → {ZipCode, Street}
New Scheme2 → {City, Street}
Loss of relation {ZipCode} → {City}
Alternate New Scheme1 → {ZipCode, Street }
Alternate New Scheme2 → {ZipCode, City}
Decomposition – Loss of
Information
1. If decomposition does not cause any loss of information it is
called a lossless decomposition.
2. If a decomposition does not cause any dependencies to be lost it
is called a dependency-preserving decomposition.
3. Any table scheme can be decomposed in a lossless way into a
collection of smaller schemas that are in BCNF form. However
the dependency preservation is not guaranteed.
4. Any table can be decomposed in a lossless way into 3rd normal
form that also preserves the dependencies.
• 3NF may be better than BCNF in some cases

Use your own judgment when decomposing schemas


BCNF - Decomposition
Example 2 (Convert to BCNF)
Old Scheme → {MovieTitle, MovieID, PersonName, Role, Payment }
New Scheme → {MovieID, PersonName, Role, Payment}
New Scheme → {MovieTitle, PersonName}

Loss of relation {MovieID} → {MovieTitle}


New Scheme → {MovieID, PersonName, Role, Payment}
New Scheme → {MovieID, MovieTitle}

We got the {MovieID} → {MovieTitle} relationship back


Example 3 (Convert to BCNF)
Old Scheme → {Client, Problem, Consultant}
New Scheme → {Client, Consultant}
New Scheme → {Client, Problem}
Fourth Normal Form (4NF)
Fourth normal form eliminates independent many-to-one relationships
between columns.
To be in Fourth Normal Form,
a relation must first be in Boyce-Codd Normal Form.
a given relation may not contain more than one multi-valued attribute.
•A table must be in BCNF.
•There should be no multivalued dependency in the table.

Example (Not in 4NF)


Scheme → {MovieName, ScreeningCity, Genre)
Primary Key: {MovieName, ScreeningCity, Genre)
1. All columns are a part of the only candidate key, hence BCNF
2. Many Movies can have the same Genre Movie ScreeningCity Genre
3. Many Cities can have the same movie
Hard Code Los Angles Comedy
4. Violates 4NF
Hard Code New York Comedy

Bill Durham Santa Cruz Drama

Bill Durham Durham Drama

The Code Warrier New York Horror


Fourth Normal Form (4NF)
Example 2 (Not in 4NF) Manager Child Employee
Scheme → {Manager, Child, Employee} Jim Beth Alice
1. Primary Key → {Manager, Child, Employee}
Mary Bob Jane
2. Each manager can have more than one child
Mary NULL Adam
3. Each manager can supervise more than one employee
4. 4NF Violated

Example 3 (Not in 4NF)


Scheme → {Employee, Skill, ForeignLanguage}
1. Primary Key → {Employee, Skill, Language }
2. Each employee can speak multiple languages
3. Each employee can have multiple skills
4. Thus violates 4NF

Employee Skill Language


1234 Cooking French

1234 Cooking German


1453 Carpentry Spanish

1453 Cooking Spanish


2345 Cooking Spanish
4NF - Decomposition
1. Move the two multi-valued relations to separate tables
2. Identify a primary key for each of the new entity.

Example 1 (Convert to 3NF)


Old Scheme → {MovieName, ScreeningCity, Genre}
New Scheme → {MovieName, ScreeningCity}
New Scheme → {MovieName, Genre}

Movie Genre Movie ScreeningCity


Hard Code Comedy Hard Code Los Angles

Bill Durham Drama Hard Code New York

The Code Warrier Horror Bill Durham Santa Cruz

Bill Durham Durham

The Code Warrier New York


4NF - Decomposition
Example 2 (Convert to 4NF) Manager Employee
Manager Child
Old Scheme → {Manager, Child, Employee} Jim Beth Jim Alice

New Scheme → {Manager, Child} Mary Bob Mary Jane

New Scheme → {Manager, Employee} Mary Adam

Example 3 (Convert to 4NF)


Old Scheme → {Employee, Skill, ForeignLanguage}
New Scheme → {Employee, Skill}
New Scheme → {Employee, ForeignLanguage}

Employee Skill Employee Language


1234 Cooking 1234 French

1453 Carpentry 1234 German

1453 Cooking 1453 Spanish

2345 Cooking 2345 Spanish


Fifth Normal Form (5NF)
Fifth normal form is satisfied when all tables are broken into as
many tables as possible in order to avoid redundancy.
Once it is in fifth normal form it cannot be broken into
smaller relations without changing the facts or the
meaning.
•The table should be in 4NF.
•There should not be Join Dependency or further non-loss
decomposed.
It is also known as Project Join Normal Form (PJNF).
Join dependency: A relation (R) is said to be a Join dependency if the
relation (R) schema can be divided into smaller sets of tables R1, R2
… Rn that can be redesigned by joining multiple tables to the original
table (R).
Levels of Normalization
Normal Form
•1NF A relation is in 1NF if it contains an atomic value.
•2NF A relation will be in 2NF if it is in 1NF and all non-
key attributes are fully functional dependent on the
primary key.
•3NFA relation will be in 3NF if it is in 2NF and no
transition dependency exists.
•4NFA relation will be in 4NF if it is in Boyce Codd normal
form and has no multi-valued dependency.
•5NFA relation is in 5NF if it is in 4NF and not contains
any join dependency and joining should be lossless.
​ ​ Triggers

In Database Management Systems (DBMS), Stored Procedures and Triggers are two
powerful and distinct database objects used to encapsulate and automate SQL code,
but they serve different purposes and are invoked differently.

Stored Procedures
A stored procedure is a pre-compiled set of one or more SQL statements (and often
includes procedural logic like IF-THEN-ELSE, loops, etc.) that is stored in the
database. It can be executed as a single unit, performing a specific task or a series of
tasks.

Key characteristics of Stored Procedures:


●​ Explicitly Invoked: You call a stored procedure by its name using a command like
EXEC or CALL. It doesn't run automatically in response to database events.
●​ Modular Programming: They allow you to encapsulate complex business logic
into reusable modules. This promotes code reusability, reduces redundancy, and
makes applications easier to maintain.
●​ Performance Optimization: Since they are pre-compiled and stored, they can
execute faster than individual, ad-hoc SQL queries, reducing network traffic
between the application and the database.
●​ Security: You can grant users permission to execute a stored procedure without
giving them direct access to the underlying tables, enhancing data security.
●​ Parameters: Stored procedures can accept input parameters and can also return
output parameters or result sets.
●​ Transaction Control: They can include transaction control statements like BEGIN
TRANSACTION, COMMIT, and ROLLBACK.
●​ Debugging: They are generally easier to test and debug because they can be run
directly.
Example (Conceptual):

CREATE PROCEDURE GetEmployeeDetails (IN employee_id INT)​


BEGIN​
SELECT *​
FROM Employees​
WHERE EmployeeID = employee_id;​
END;​

-- To call the stored procedure:​
CALL GetEmployeeDetails(101);​

Triggers
A trigger is a special type of stored procedure that automatically executes (or "fires")
in response to specific events occurring in the database. These events are typically
Data Manipulation Language (DML) operations (INSERT, UPDATE, DELETE) on a table
or view.

Key characteristics of Triggers:


●​ Implicitly Invoked: Triggers are executed automatically when the defined event
occurs on the specified table or view. You don't call them directly.
●​ Event-Driven: They are designed to react to database events.
●​ Enforce Business Rules and Data Integrity: Triggers are often used to enforce
complex business rules, maintain data consistency, audit changes, or cascade
updates/deletions across related tables.
●​ BEFORE or AFTER: Triggers can be defined to fire before or after the triggering
DML event.
○​ BEFORE triggers: Can be used to validate or modify data before it's inserted
or updated, or to prevent an operation if certain conditions are not met.
○​ AFTER triggers: Are typically used for logging, auditing, or performing
actions on other tables based on the changes.
●​ No Parameters: Triggers do not accept parameters directly from the user. They
operate on the data that is being modified by the triggering event (often
accessed via special NEW and OLD row references).
●​ Limited Transaction Control: In many DBMS, transaction control statements
(COMMIT, ROLLBACK) are not allowed directly within a trigger's body, as the
trigger operates within the context of the triggering statement's transaction. If
the trigger fails, the entire transaction typically rolls back.
●​ Debugging Challenges: Because they run automatically "behind the scenes,"
debugging triggers can be more challenging than debugging stored procedures.
Example (Conceptual):

-- Create a log table to store changes​


CREATE TABLE AuditLog (​
LogID INT AUTO_INCREMENT PRIMARY KEY,​
TableName VARCHAR(50),​
ActionType VARCHAR(10),​
OldValue VARCHAR(255),​
NewValue VARCHAR(255),​
ChangeDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP​
);​

-- Create an AFTER UPDATE trigger to log salary changes​
CREATE TRIGGER LogSalaryChanges​
AFTER UPDATE ON Employees​
FOR EACH ROW​
BEGIN​
IF OLD.Salary <> NEW.Salary THEN​
INSERT INTO AuditLog (TableName, ActionType, OldValue, NewValue)​
VALUES ('Employees', 'UPDATE', OLD.Salary, NEW.Salary);​
END IF;​
END;​

-- Now, if you update an employee's salary, the trigger will automatically log it:​
UPDATE Employees​
SET Salary = 65000​
WHERE EmployeeID = 101;​

Key Differences Summarized

Feature Stored Procedures Triggers

Invocation Explicitly called by Implicitly fired by a database


user/application. event (INSERT, UPDATE,
DELETE).

Purpose Perform specific tasks, Automate actions, enforce


reusable logic, complex business rules, maintain data
queries. integrity, auditing.

Parameters Can accept input and return Do not accept parameters.


output parameters. Operate on data of the
triggering statement.

Return Values Can return values or result Do not return values.


sets.

Transaction Control Can contain COMMIT, Usually restricted from


ROLLBACK, SAVEPOINT. containing explicit transaction
control statements.

Execution Run independently on Run as part of the transaction


demand. that caused the triggering
event.

Debugging Generally easier to debug. Can be harder to debug due


to implicit execution.

Nesting Can call other stored Can sometimes call stored


procedures. procedures, but triggers
cannot call other triggers
directly (though nesting of
triggers on different tables
might occur).

Both stored procedures and triggers are vital components of a robust DBMS, offering
ways to improve performance, security, and data integrity by centralizing and
automating database logic. The choice between using a stored procedure or a trigger
depends on the specific requirements and how the logic needs to be invoked.

Join Dependency

In DBMS, a join dependency (JD) exists when a table can be reconstructed by


joining multiple tables, each containing a subset of the original table's
attributes. This means the original table is "losslessly" decomposed into
smaller tables that can be joined back together to recreate the original

You might also like