0% found this document useful (0 votes)
19 views274 pages

SQL (1)

Uploaded by

hrishikeshr.cd23
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)
19 views274 pages

SQL (1)

Uploaded by

hrishikeshr.cd23
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/ 274

Topics Covered in Todays Class

Unit 1:
- SQL Data Definition and Data Types
- Specifying basic constraints in SQL

5 April 2021 CSE, BMSCE 1


What is SQL ?

□ SQL stands for Structured Query


Language
□ SQL lets you access and manipulate
databases Database Management
System (DBMS)
Application Program
student
Input Database
Select USN, Name
SQL query student_info
from student_info;
USN Name
1BM14CS001 Arjun
Output 1BM14CS002 Balaji
1BM14CS001 Arjun
1BM14CS002 Balaji

5 April 2021 CSE, BMSCE 2


RDBMS
□ RDBMS stands for Relational Database Management
System.
□ RDBMS is the basis for SQL, and for all modern database
systems such as Oracle, MySQL, MS SQL Server, IBM DB2, and
Microsoft Access.
□ The data in RDBMS is stored in database objects called tables.
□ A table is a collection of related data entries and it consists
of columns and rows.

Column or Attribute

Row USN Name Table


or or
Tuple 1BM14CS001 Arjun Relation
or 1BM14CS002 Balaji
Record
Database table Name: student_info

5 April 2021 CSE, BMSCE 3


SQL commands fro Data Definition

Command Description
create to create new table or database
alter for alteration
truncate delete data from table
drop to drop a table
rename to rename a table

5 April 2021 CSE, BMSCE 4


SQL: create command
□ create is a DDL (Data Definition) command used to create a table or a
database.
Creating a Database
□ Syntax: create database database-name;
□ Example: create database student;

5 April 2021 CSE, BMSCE 5


SQL: create command
□ create is a DDL (Data Definition) command used to create a table or a
database.
Creating a Database
□ Syntax: create database database-name;
□ Example: create database student; student
Creating a Table Database
□ Syntax:
create table table-name ( student_info
column-name1 datatype1,
column-name2 datatype2 ); USN Name
□ Example:
create table student.student_info(
USN char(10),
Name char(30)
); student is database name or schema name
student_info is the table name

Here student_info will be created under the database student

5 April 2021 CSE, BMSCE 6


SQL: create command
What is the difference between
create table student.student_info(
USN char(10),
Name char(30)
);

create table student_info(


USN char(10),
Name char(30);
);

5 April 2021 CSE, BMSCE 7


Specifying Constraints in SQL

□ Specifying Attributes constraints and


Attribute values
□ Specifying Key and Referential
Integrity constraints
□ Specifying constraints on Tuples using
CHECK

5 April 2021 CSE, BMSCE 8


Specifying Attributes constraints and Attribute
values

create table student.student_info(


USN char(10),
Name char(30) NOT NULL,
DepName char(3) NOT NULL DEFAULT ‘CSE’,
Marks int NOT NULL CHECK (Marks > 0 AND Marks < 101)
);

Constraints on Attributes
- NOT NULL
- DEAFULT
- CHECK

5 April 2021 CSE, BMSCE 9


Specifying Key and Referential Integrity
constraints

PRIMARY KEY Constraint


create table student.student_info(
USN char(10),
Name char(30) NOT NULL,
DepName char(3) NOT NULL DEFAULT ‘CSE’,
Marks int NOT NULL CHECK (Marks > 0 AND Marks < 101)
PRIMARY KEY (USN)
);

5 April 2021 CSE, BMSCE 10


Specifying Key and Referential Integrity
constraints

PRIMARY KEY Constraint


Question: What is the difference between following two
create commands ?
create table student.student_info(
USN char(10),
Name char(30) NOT NULL,
DepName char(3) NOT NULL DEFAULT ‘CSE’,
Marks int NOT NULL CHECK (Marks > 0 AND Marks < 101)
PRIMARY KEY (USN)
);

create table student.student_info(


USN char(10),
Name char(30) NOT NULL,
DepName char(3) NOT NULL DEFAULT ‘CSE’,
Marks int NOT NULL CHECK (Marks > 0 AND Marks < 101)
CONSTRAINT usn_pk PRIMARY KEY (USN)
);

5 April 2021 CSE, BMSCE 11


Specifying Key and Referential Integrity
constraints

□ Referential Integrity constraint or


Foreign Key Constraint
USN
D-ID M
Departme 1 Student
Has
nt
D-Name
S-Name
create table Department(
D_ID int,
D_Name char(3),
PRIMARY KEY (D_ID)
create table Student(
);
USN char(10),
S_Name char(20),
Dep_Num int,
PRIMARY KEY (USN),
FOREIGN KEY(Dep_Num) REFERENCES Department(D_ID)
);
5 April 2021 CSE, BMSCE 12
Specifying Key and Referential Integrity
constraints

□ Referential Integrity constraint or Foreign Key Constraint


Student Table
Department Table USN S-Name Dep_
Num
D_ID D-Name
1BM14CS001 Akash 10
10 CSE 1BM14CS002 Bharath 10
20 ISE 1BM14CS003 Ragu 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. Assume, D_ID value of CSE department in Department table
has been updated to 50. Then how the values of Dep_Num column in
Student table should be affected
2. Assume, Department table has been deleted. Then how the values of
Dep_Num column in Student table should be affected

5 April 2021 CSE, BMSCE 13


Specifying Key and Referential Integrity
constraints

□ Referential Integrity constraint or


Foreign Key Constraint
create table Department(
D_ID int,
D_Name int(3),
PRIMARY KEY (D_ID)
);

create table Student(


USN char(10),
S_Name char(20),
Dep_Num int,
PRIMARY KEY (USN),
FOREIGN KEY(Dep_Num) REFERENCES Department(D_ID)
ON DELETE CASCADE ON UPDATE CASCADE
);

5 April 2021 CSE, BMSCE 14


Specifying Key and Referential Integrity
constraints

□ Referential Integrity constraint or


Foreign Key Constraint
create table Department(
D_ID int,
D_Name int(3),
PRIMARY KEY (D_ID)
);

create table Student(


USN char(10),
S_Name char(20),
Dep_Num int,
PRIMARY KEY (USN),
FOREIGN KEY(Dep_Num) REFERENCES Department(D_ID)
ON DELETE SET NULL ON UPDATE CASCADE
);

5 April 2021 CSE, BMSCE 15


Specifying Key and Referential Integrity
constraints

□ Referential Integrity constraint or Foreign Key Constraint


Student Table
Department Table USN S-Name Dep_
Num
D_ID D-Name
1BM14CS001 Akash 10
10 CSE 1BM14CS002 Bharath 10
20 ISE 1BM14CS003 Ragu 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the status of
Student table contents?

Update Department set D_ID=50 where D_ID=10;

5 April 2021 CSE, BMSCE 16


Specifying Key and Referential Integrity
constraints

□ Referential Integrity constraint or Foreign Key Constraint


Student Table
Department Table USN S-Name Dep_
Num
D_ID D-Name
1BM14CS001 Akash 10
10 CSE 1BM14CS002 Bharath 10
20 ISE 1BM14CS003 Ragu 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the status of
Student table contents?

Delete from Department where D_ID=10;

5 April 2021 CSE, BMSCE 17


Specifying Key and Referential Integrity
constraints

□ Following SQL commands will be


executed successfully ? YES / NO
create table Department(
D_ID int,
D_Name char(3),
PRIMARY KEY (D_ID)
);

create table Student(


USN char(10),
S_Name char(20),
Dep_Num char(3),
PRIMARY KEY (USN),
FOREIGN KEY(Dep_Num) REFERENCES Department(D_ID)
ON DELETE SET NULL ON UPDATE CASCADE
);

5 April 2021 CSE, BMSCE 18


Specifying Key and Referential Integrity
constraints

□ ON DELETE CASCADE
□ ON DELETE SET NULL
□ ON DELETE SET DEFAULT

□ ON UPDATE CASCADE
□ ON UPDATE SET NULL
□ ON UPDATE SET DEFAULT

5 April 2021 CSE, BMSCE 19


Specifying Key and Referential Integrity
constraints

□ Referential Integrity constraint or Foreign Key Constraint


Student Table
Department Table USN S-Name Dep_
Num
D_ID D-Name
1BM14CS001 Akash 10
10 CSE 1BM14CS002 Bharath 10
20 ISE 1BM14CS003 Ragu 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the status of
Student table contents?

Delete from Department where D_ID=10;

5 April 2021 CSE, BMSCE 20


Topics Covered in Todays Class

Unit 1:
- Schema change statements in SQL
- Basic SQL queries

5 April 2021 CSE, BMSCE 21


Schema change statements in SQL
□ Drop command can be used to drop tables or constraints.

□ The DROP TABLE Statement


General Syntax: DROP TABLE table_name

□ The DROP DATABASE Statement


General Syntax: DROP DATABASE database_name

□ The TRUNCATE TABLE Statement


What if we only want to delete the data inside the table, and not
the table itself ? Then, use the TRUNCATE TABLE statement:
General Syntax: TRUNCATE TABLE table_name

5 April 2021 CSE, BMSCE 22


Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Assume the above two tables were created using following create commands
create table department (D_ID integer, Dep_name varchar(3),primary key (D_ID));

create table student (USN varchar(10),Name varchar(20),Dep_num integer,


primary key(usn),foreign key (Dep_num) references department(D_ID));

Note: Assume after above two table creation, values shown above are inserted
into tables
5 April 2021 CSE, BMSCE 23
Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the output

insert into student values (‘1BM14CS006’,’Patel’,50);

5 April 2021 CSE, BMSCE 24


Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the output

insert into student values (‘1BM14CS006’,’Patel’,50);

Cannot add a row: a foreign key constraint fails


5 April 2021 CSE, BMSCE 25
Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the output

drop table department;

5 April 2021 CSE, BMSCE 26


Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the output

drop table department;

Department Table will not be deleted because of foreign key constraint


5 April 2021 CSE, BMSCE 27
Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the output

drop table student;

5 April 2021 CSE, BMSCE 28


Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the output

drop table student;

student Table will be deleted


5 April 2021 CSE, BMSCE 29
Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
Num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the output

drop table department cascade constraints;

5 April 2021 CSE, BMSCE 30


Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
Num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. When the following SQL Command is executed, what will be the output

drop table department cascade constraints;

Department Table will be deleted and foreign key constraint to student


Table will be dropped
5 April 2021 CSE, BMSCE 31
Schema change statements in SQL

□ Drop command Student Table


department Table USN Name Dep_
Num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. Whether the following two SQL commands will be executed successfully

drop table department cascade constraints;


insert into student values (‘1BM14CS006’,’Patel’,50);

5 April 2021 CSE, BMSCE 32


Schema change statements in SQL

□ Drop command student Table


department Table USN Name Dep_
Num
D_ID Dep_na
me 1BM14CS001 Avinash 10
10 CSE 1BM14CS002 Balaji 10
20 ISE 1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

Question
1. Whether the following two SQL commands will be executed successfully
drop table department cascade constraints;
insert into student values (‘1BM14CS006’,’Patel’,50);

Into the student table new row will be inserted with dep_num 50

5 April 2021 CSE, BMSCE 33


Schema change statements in SQL
□ Drop Command
General syntax:
drop table table_name [drop_behavior]

There are two drop behavior options


1. Cascade: All constraints that references the table are
dropped automatically along with the table itself.
2. Restrict: Table is dropped only it is not referenced in
any constraints.

5 April 2021 CSE, BMSCE 34


Schema change statements in SQL

□ Alter command
General Syntax:
alter table table_name [add|drop|alter]
column column_name;

Adding or dropping column


Changing column definition
Adding or dropping table constraints

5 April 2021 CSE, BMSCE 35


Schema change statements in SQL

□ Alter command
Student Table
USN Name Dep_
Num
1BM14CS001 Avinash 10
1BM14CS002 Balaji 10
1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

5 April 2021 CSE, BMSCE 36


Schema change statements in SQL

□ Alter command
Student Table
USN Name Dep_
Num
1BM14CS001 Avinash 10
1BM14CS002 Balaji 10
1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20

5 April 2021 CSE, BMSCE 37


Schema change statements in SQL

□ Alter command
Student Table
USN Name Dep_
Num
1BM14CS001 Akash 10
1BM14CS002 Bharath 10
1BM14CS003 Ragu 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20
Question
1. What will be the contents of the student table when the following SQL
commands are executed ?

5 April 2021 CSE, BMSCE 38


Schema change statements in SQL

□ Alter command
Student Table
USN S-Name Dep_Nu email
m
1BM14CS001 Akash 10
1BM14CS002 Bharath 10
1BM14CS003 Ragu 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20
1BM14CS006 Patel 10 patel@gm
ail.com

5 April 2021 CSE, BMSCE 39


Basic queries in SQL

□ To retrieve data from database table,


basic SQL statement is SELECT
□ Syntax:
select column_name_list
from table_name
where condition;

5 April 2021 CSE, BMSCE 40


SQL select statement
student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90

5 April 2021 CSE, BMSCE 41


SQL select statement
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90

5 April 2021 CSE, BMSCE 42


SQL select statement
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90

5 April 2021 CSE, BMSCE 43


SQL select statement
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90

5 April 2021 CSE, BMSCE 44


SQL select statement
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90

5 April 2021 CSE, BMSCE 45


Select statement

□ Where clause conditions


=
!=
<
>
<=
>=

5 April 2021 CSE, BMSCE 46


SQL select statement
student Table
usn name dep_ marks
department Table num
D_ID D-Name 1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
10 CSE
1BM14CS003 Chandan 10 45
20 ISE
1BM14CS004 Dinesh 10 60
1BM14IS005 Avinash 20 90

1. List out the USN’s of the students who belong to department number 10?

5 April 2021 CSE, BMSCE 47


SQL select statement
student Table
usn name dep_ marks
department Table num
D_ID D-Name 1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
10 CSE
1BM14CS003 Chandan 10 45
20 ISE
1BM14CS004 Dinesh 10 60
1BM14IS005 Avinash 20 90

1. List out the USN’s of the students who belong to department number 10?

5 April 2021 CSE, BMSCE 48


SQL select statement
student Table
usn name dep_ marks
department Table num
d_id dep_na 1BM14CS001 Avinash 10 100
me
1BM14CS002 Balaji 10 80
10 CSE
1BM14CS003 Chandan 10 45
20 ISE
1BM14CS004 Dinesh 10 60
1BM14IS005 Avinash 20 90

Question
1. List out the USN’s of the students who belong to CSE department ?

5 April 2021 CSE, BMSCE 49


SQL select statement
student Table
usn name dep_ marks
department Table num
d_id dep_na 1BM14CS001 Avinash 10 100
me
1BM14CS002 Balaji 10 80
10 CSE
1BM14CS003 Chandan 10 45
20 ISE
1BM14CS004 Dinesh 10 60
1BM14IS005 Avinash 20 90

Question
1. List out the USN’s of the students who belong to CSE department ?

5 April 2021 CSE, BMSCE 50


SQL select statement
student Table
usn name dep_ marks
department Table num
d_id dep_na 1BM14CS001 Avinash 10 100
me
1BM14CS002 Balaji 10 80
10 CSE
1BM14CS003 Chandan 10 45
20 ISE
1BM14CS004 Dinesh 10 60
1BM14IS005 Avinash 20 90

5 April 2021 CSE, BMSCE 51


SQL select statement: Aliasing
student Table
usn name dep_ marks
department Table num
d_id dep_na 1BM14CS001 Avinash 10 100
me
1BM14CS002 Balaji 10 80
10 CSE
1BM14CS003 Chandan 10 45
20 ISE
1BM14CS004 Dinesh 10 60
1BM14IS005 Avinash 20 90

5 April 2021 CSE, BMSCE 52


SQL select statement: Distinct
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90

Avinash
Balaji
Chandan
Dinesh
Avinash
5 April 2021 CSE, BMSCE 53
SQL select statement: Distinct
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90

Avinash
Balaji
Chandan
Dinesh

5 April 2021 CSE, BMSCE 54


SQL select statement: Order By
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90

5 April 2021 CSE, BMSCE 55


SQL select statement: Order By
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90

5 April 2021 CSE, BMSCE 56


SQL select statement: Order By
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90
Question
List usn, name of the students who belong to department number 10 ordered by
ascending order of their marks ?

5 April 2021 CSE, BMSCE 57


SQL select statement: Order By
Student Table
usn name dep_ marks
num
1BM14CS001 Avinash 10 100
1BM14CS002 Balaji 10 80
1BM14CS003 Chandan 10 45
1BM14CS004 Dinesh 10 60
1BM14IS001 Avinash 20 90
Question
List usn, name of the students who belong to department number 10 ordered by
ascending order of their marks ?

5 April 2021 CSE, BMSCE 58


Activity: To do
Employee table
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-Dec-80 800 20
7499 ALLEN SALESMAN 7698 20-Feb-81 1600 300 30
7521 WARD SALESMAN 7698 22-Feb-81 1250 500 30
7566 JONES MANAGER 7839 02-Apr-81 2975 20
7654 MARTIN SALESMAN 7698 28-Sep-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-May-81 2850 30
7782 CLARK MANAGER 7839 09-Jun-81 2450 10
7788 SCOTT ANALYST 7566 09-Dec-82 3000 20
7839 KING PRESIDENT 17-Nov-81 5000 10
7844 TURNER SALESMAN 7698 08-Sep-81 1500 0 30
7876 ADAMS CLERK 7788 12-Jan-83 1100 20
7900 JAMES CLERK 7698 03-Dec-81 950 30
7902 FORD ANALYST 7566 03-Dec-81 3000 20
7934 MILLER CLERK 7782 23-Jan-82 1300 10

Write SQL queries for the following


1. Display all the information of the Employee table ?
2. Display unique Jobs from Employee table?
3. List names of the employees in the ascending order of their Salaries ?
5 April 2021 CSE, BMSCE 59
Topics Covered in Today’s class

Unit 1: Basic queries in SQL

w.r.t SELECT statement


SQL operators: LIKE, IN, BETWEEN

5 April 2021 CSE, BMSCE 60


Structured Query Language (SQL)
SQL can be divided into two parts:
1. The Data Manipulation Language (DML) and
2. The Data Definition Language (DDL)

1. DDL statements in SQL are:


■ CREATE DATABASE - creates a new database
■ ALTER DATABASE - modifies a database
■ CREATE TABLE - creates a new table
■ ALTER TABLE - modifies a table
■ DROP TABLE - deletes a table

2. DML part of SQL:


■ SELECT - extracts data from a database
■ UPDATE - updates data in a database
■ DELETE - deletes data from a database
■ INSERT INTO - inserts new data into a database

5 April 2021 CSE, BMSCE 61


The SQL SELECT Statement
□ The SELECT statement is used to select data from a database.
□ The result is stored in a result table, called the result-set.

□ Note: SQL is not case sensitive. SELECT is the same as select.

5 April 2021 CSE, BMSCE 62


w.r.t to SELECT SQL statement
1. SQL Alias: We can give a table or a column another name by using an
alias.
□ SQL Alias Syntax for Tables
SELECT column_name(s)
FROM table_name AS alias_name;
□ SQL Alias Syntax for Columns
SELECT column_name AS alias_name
FROM table_name;

2. The DISTINCT keyword can be used to return only distinct (different)


values.
□ SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s)
FROM table_name

5 April 2021 CSE, BMSCE 63


w.r.t to SELECT sql statement
3. The ORDER BY keyword is used to sort the result-set by a specified column.
□ SQL ORDER BY Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC | DESC;
4. The WHERE clause is used to filter records. The WHERE clause is used to extract
only those records that fulfill a specified criterion.
□ SQL WHERE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
□ With the WHERE clause, the following operators can be used:

5 April 2021 CSE, BMSCE 64


Substring Pattern Matching: SQL LIKE Operator

□ The LIKE operator is used in a WHERE clause to search for a


specified pattern in a column.
□ SQL LIKE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern

5 April 2021 CSE, BMSCE 65


SQL LIKE Operator
□ The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column.
□ SQL LIKE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern

Example: Write SQL statement to list the names starting with letter
“A” from following student table.

5 April 2021 CSE, BMSCE 66


SQL LIKE Operator
Write SQL statement to list the names starting
with letter “A” from the following student table.

5 April 2021 CSE, BMSCE 67


SQL LIKE Operator
Write SQL statement to list the names starting
with letter “A” from the following student table.

Note:
Wildcard character %, A substitute for zero or more characters

5 April 2021 CSE, BMSCE 68


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose names end
with letter ‘h’?

Note:
Wildcard character %, A substitute for zero or more characters

5 April 2021 CSE, BMSCE 69


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose names end
with letter ‘h’?

5 April 2021 CSE, BMSCE 70


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose names
are having the substring ‘in’?

Note:
Wildcard character %, A substitute for zero or more characters

5 April 2021 CSE, BMSCE 71


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose names
are having the substring ‘in’?

5 April 2021 CSE, BMSCE 72


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose names
start with letter ‘A’ or ‘B’

5 April 2021 CSE, BMSCE 73


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose names
start with letter ‘A’ or ‘B’

5 April 2021 CSE, BMSCE 74


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose names
start with letter ‘A’ or ‘D’ but end with letter ‘h’

5 April 2021 CSE, BMSCE 75


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose names
start with letter ‘A’ or ‘D’ but end with letter ‘h’

5 April 2021 CSE, BMSCE 76


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose third letter in the
name is ‘a’ .

5 April 2021 CSE, BMSCE 77


SQL LIKE Operator

Question
Write SQL statement to list name of the students whose third letter in the
name is ‘a’ .

Note:
An underscore (_) in the pattern matches exactly one character
A percent sign (%) in the pattern can match zero or more characters
underscore (_) and percent sign (%) are referred as wildcard characters
5 April 2021 CSE, BMSCE 78
SQL Wildcard Characters
□ In SQL, wildcard characters are used with the SQL LIKE
operator.
□ SQL wildcards are used to search for data within a table.

With SQL, the wildcards are:


Wildcard Description
% A substitute for zero or more characters
_ A substitute for a single character
[charlist] Sets and ranges of characters to match
[^charlist] Matches only a character NOT specified within the brackets
or
[!charlist]

5 April 2021 CSE, BMSCE 79


SQL IN Operator
□ The IN operator allows you to specify multiple values in a WHERE
clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

5 April 2021 CSE, BMSCE 80


SQL IN Operator
□ The IN operator allows you to specify multiple values in a WHERE
clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

Example: List USN's of the students with name equal to "Avinash" or


"Dinesh" from the table above.

5 April 2021 CSE, BMSCE 81


SQL IN Operator
□ The IN operator allows you to specify multiple values in a WHERE
clause.

Example: List USN's of the students with name equal to "Avinash" or


"Dinesh" from the table above.

5 April 2021 CSE, BMSCE 82


SQL BETWEEN operator
□ The BETWEEN operator selects a range of data between two values.
The values can be numbers, text, or dates.
SQL BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2

Example: List USN’s and Names of students whose marks is in between 40


and 80

5 April 2021 CSE, BMSCE 83


SQL BETWEEN operator
□ The BETWEEN operator selects a range of data between two values.
The values can be numbers, text, or dates.

Example: List USN’s and Names of students whose marks is in between 40


and 80

5 April 2021 CSE, BMSCE 84


Activity To Do
Consider table of Nobel prize winners:
nobel(yr, subject, winner)

Answer the following

5 April 2021 CSE, BMSCE 85


Activity To Do
Consider table of Nobel prize winners:
nobel(yr, subject, winner)

Answer the following

5 April 2021 CSE, BMSCE 86


Activity To Do
Consider table of Nobel prize winners:
nobel(yr, subject, winner)
Answer the following

5 April 2021 CSE, BMSCE 87


Activity To Do
Consider table of Nobel prize winners:
nobel(yr, subject, winner)

Answer the following

5 April 2021 CSE, BMSCE 88


Aggregate Functions in SQL
□ Why we need aggregate functions ??
□ Example say we want find maximum marks
scored by the students in the class.

□ We use aggregate function to group multiple


rows together to form a single value output.

5 April 2021 CSE, BMSCE 89


Topics Covered in Todays Class

Unit 1: Basic queries in SQL

Aggregate functions
Group BY Clause
Having Clause

5 April 2021 CSE, BMSCE 90


Arithmetic operators in Queries
□ Arithmetic operators for addition (+), subtraction (-),
multiplication(*), and division (/) can be applied to
numeric values or attributes with numeric domain.

□ Example:

5 April 2021 CSE, BMSCE 91


Aggregate Functions in SQL
□ SQL aggregate functions return a single value, calculated
from values in a column.
Useful aggregate functions:
□ AVG() - Returns the average value
□ COUNT() - Returns the number of rows
□ MAX() - Returns the largest value
□ MIN() - Returns the smallest value
□ SUM() - Returns the sum

5 April 2021 CSE, BMSCE 92


Aggregate Functions in SQL
The AVG() Function
□ The AVG() function returns the average value of a numeric column.
□ SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name

Find average marks of all the students in the class.

5 April 2021 CSE, BMSCE 93


Aggregate Functions in SQL
□ SQL COUNT() Function
The COUNT() function returns the number of rows that matches a specified
criteria.
□ SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL
values will not be counted) of the specified column:
SELECT COUNT(column_name) FROM table_name

□ SQL COUNT(*) Syntax


The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name

□ SQL COUNT(DISTINCT column_name) Syntax


The COUNT(DISTINCT column_name) function returns the number of
distinct values of the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name

5 April 2021 CSE, BMSCE 94


Aggregate Functions in SQL
□ SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table.
.

Find total number of records in the above student table

5 April 2021 CSE, BMSCE 95


Aggregate Functions in SQL
□ SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table.

Find total number of students who belong to department number


10

5 April 2021 CSE, BMSCE 96


Aggregate Functions in SQL
□ SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values
(NULL values will not be counted) of the specified column.

Find total number of students who have Email IDs

5 April 2021 CSE, BMSCE 97


Aggregate Functions in SQL

What will be the out put of following SQL queries ?

5 April 2021 CSE, BMSCE 98


Aggregate Functions in SQL

5 April 2021 CSE, BMSCE 99


SQL GROUP BY Statement
□ Why we need Group by Statement
□ Say we want to find total number of students by
department wise.

□ Partition the set of records into groups based on certain


criteria.
□ Groups are formed on the basis of certain attribute.
□ Aggregate functions are calculated for each group.

5 April 2021 CSE, BMSCE 100


SQL GROUP BY Statement
□ The GROUP BY statement is used in conjunction with the
aggregate functions to group the result-set by one or
more columns.
□ SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name

5 April 2021 CSE, BMSCE 101


SQL GROUP BY Statement
□ The GROUP BY statement is used in conjunction with the
aggregate functions to group the result-set by one or
more columns.

Find total number of students in each department

5 April 2021 CSE, BMSCE 102


SQL GROUP BY Statement

Whether the following SQL queries will “Find total number of


students in each department”

5 April 2021 CSE, BMSCE 103


SQL GROUP BY Statement

Whether the following SQL queries will “Find total number of


students in each department”

5 April 2021 CSE, BMSCE 104


SQL GROUP BY Statement
□ The GROUP BY statement is used in conjunction with the
aggregate functions to group the result-set by one or
more columns.

What will be the output of following SQL statement

5 April 2021 CSE, BMSCE 105


SQL GROUP BY Statement
□ The GROUP BY statement is used in conjunction with the
aggregate functions to group the result-set by one or
more columns.

What will be the output of following SQL statement

5 April 2021 CSE, BMSCE 106


Answer the following

5 April 2021 CSE, BMSCE 107


Answer the following

5 April 2021 CSE, BMSCE 108


SQL HAVING Clause
□ Why we need Having clause ??
□ Say we want to find USNs of the students who
have registered for atleast two courses

5 April 2021 CSE, BMSCE 109


SQL HAVING Clause
□ The HAVING clause was added to SQL because the
WHERE keyword could not be used with aggregate
functions.
SQL HAVING Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value

5 April 2021 CSE, BMSCE 110


SQL HAVING Clause

List USNs of the students who have registered for atleast


two courses

5 April 2021 CSE, BMSCE 111


SQL HAVING Clause

List USNs of the students who have registered for atleast


two courses

5 April 2021 CSE, BMSCE 112


SQL HAVING Clause

What will be the out put of the following SQL query

5 April 2021 CSE, BMSCE 113


SQL HAVING Clause

What will be the out put of the following SQL query

5 April 2021 CSE, BMSCE 114


SQL HAVING Clause

□ List number of courses registered and Names of the


student whose names end with ‘h’ and having registered
for at least two courses

5 April 2021 CSE, BMSCE 115


SQL HAVING Clause

□ List number of courses registered and Names of the student whose


names end with ‘h’ and having registered for at least two courses

5 April 2021 CSE, BMSCE 116


SQL HAVING Clause

What will be the out put of the


following SQL query

5 April 2021 CSE, BMSCE 117


Remember the following steps to a complete understanding
of SQL:

□ FROM generates the data set


□ WHERE filters the generated data set
□ GROUP BY aggregates the filtered data set
□ HAVING filters the aggregated data set
□ SELECT transforms the filters aggregated data
set
□ ORDER BY sorts the transformed data set

5 April 2021 CSE, BMSCE 118


SQL practice Questions

90

□ Write a query to get the total salaries


payable to employees.

5 April 2021 CSE, BMSCE 119


SQL practice Questions

90

□ Write a query to get the total salaries


payable to employees.

SELECT SUM(salary) FROM employees;

5 April 2021 CSE, BMSCE 120


SQL practice Questions

90

□ Write a query to list the number of


job ids available in the employees
table.

5 April 2021 CSE, BMSCE 121


SQL practice Questions

90

□ Write a query to list the number of


job ids available in the employees
table.

SELECT COUNT(DISTINCT job_id)


FROM employees;

5 April 2021 CSE, BMSCE 122


SQL practice Questions

90

Write a query to get the maximum salary of an employee


working as a IT_PROG.

5 April 2021 CSE, BMSCE 123


SQL practice Questions

90

Write a query to get the maximum salary of an employee


working as a IT_PROG.

SELECT MAX(salary)
FROM employees
WHERE job_id = 'IT_PROG';

5 April 2021 CSE, BMSCE 124


SQL practice Questions

90

Write a query to get the department ID and the total salary


payable in each department.

5 April 2021 CSE, BMSCE 125


SQL practice Questions

90

Write a query to get the department ID and the total salary


payable in each department.

SELECT department_id, SUM(salary)


FROM employees
GROUP BY department_id;

5 April 2021 CSE, BMSCE 126


SQL practice Questions

90

Write a query to get the average salary for each job ID


excluding IT_PROG.

5 April 2021 CSE, BMSCE 127


SQL practice Questions

90

Write a query to get the average salary for each job ID


excluding IT_PROG.

SELECT job_id, AVG(salary)


FROM employees
WHERE job_id != 'IT_PROG'
GROUP BY job_id;

5 April 2021 CSE, BMSCE 128


SQL practice Questions

90

Write a query to get the average salary for all departments


employing more than 10 employees.

5 April 2021 CSE, BMSCE 129


SQL practice Questions

90

Write a query to get the average salary for all departments


employing more than 10 employees.

SELECT AVG(salary), COUNT(employee_id)


FROM employees
GROUP BY department_id
HAVING COUNT(employee_id) > 10;

5 April 2021 CSE, BMSCE 130


DML statements

□ SELECT - extracts data from a


database
□ UPDATE - updates data in a database
□ DELETE - deletes data from a
database
□ INSERT INTO - inserts new data into
a database

5 April 2021 CSE, BMSCE 131


The INSERT INTO Statement
□ The INSERT INTO statement is used to insert a new row in a
table.
□ SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data
will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values
to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

5 April 2021 CSE, BMSCE 132


SQL UPDATE Statement
□ The UPDATE statement is used to update existing records in a
table.
SQL UPDATE Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

update student1
set emailid=‘[email protected]
where name=‘Dinesh’;
5 April 2021 CSE, BMSCE 133
SQL DELETE Statement
□ The DELETE statement is used to delete rows in a table.
SQL DELETE Syntax
DELETE FROM table_name
WHERE some_column=some_value

delete from student1


where usn=‘1BM14IS001’;

5 April 2021 CSE, BMSCE 134


Topics Covered in Todays Class

Unit 1: More Complex SQL queries

Nested Queries, Tuples and Set/Mutiset Comparison

5 April 2021 CSE, BMSCE 135


Subqueries or Nested Queries
□ A subquery is a SQL query nested inside a larger query.
SELECT colname1, colname2………. (SELECT ……….)
Note: Subqueries must be enclosed with in parenthesis

□ A subquery is usually added within the WHERE Clause of another SQL


SELECT statement.
■ We can use the comparison operators, such as >, <, or =. The comparison operator can
also be a multiple-row operator, such as IN, ANY, SOME, or ALL.
□ A subquery can be treated as an inner query, which is a SQL query
placed as a part of another query called as outer query.
□ The inner query executes first before its parent query so that the
results of inner query can be passed to the outer query.

Outer Query

Inner Query

5 April 2021 CSE, BMSCE 136


Subqueries or Nested Queries
□ A subquery is a SQL query nested inside a larger query.
SELECT colname1, colname2………. (SELECT ……….)
Note: Subqueries must be enclosed with in parenthesis

□ A subquery is usually added within the WHERE Clause of another SQL


SELECT statement.
■ We can use the comparison operators, such as >, <, or =. The comparison operator can
also be a multiple-row operator, such as IN, ANY, SOME, or ALL.
□ A subquery can be treated as an inner query, which is a SQL query
placed as a part of another query called as outer query.
□ The inner query executes first before its parent query so that the
results of inner query can be passed to the outer query.

Outer Query

Inner Query

5 April 2021 CSE, BMSCE 137


Subqueries

□ List names of the students whose


marks score is greater than ‘Balaji’

5 April 2021 CSE, BMSCE 138


Subqueries

□ List names of the students whose marks score is greater


than ‘Balaji’
Outer Query

Inner Query

5 April 2021 CSE, BMSCE 139


Subqueries

□ List names of the students whose marks score is greater


than ‘Balaji’
Outer Query

80
Inner Query

5 April 2021 CSE, BMSCE 140


Subqueries

□ List names of the students whose marks score is greater


than ‘Balaji’

5 April 2021 CSE, BMSCE 141


Subqueries

□ List name of the student whose


marks score is second highest

5 April 2021 CSE, BMSCE 142


Subqueries

□ List name of the student whose marks score is


second highest

5 April 2021 CSE, BMSCE 143


Subqueries : Using Comparisons
□ A subquery can be used before or after any of the comparison
operators.
□ The subquery can return at most one value. The value can be the
result of an arithmetic expression or a column function.
□ SQL then compares the value that results from the subquery with the
value on the other side of the comparison operator. You can use the
following comparison operators:

Operator Description
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
!= Not equal to
5 April 2021 CSE, BMSCE 144
Activity To Do
movie_director(movie_title,pid) person(pid,name)

movie_title pid pid name


Guru P1 P1 ManiRathnam
Dasvathaaram P2 P2 KamalHassan
Raavan P1

Write Query to,


List down the movie titles directed by 'ManiRathnam'

5 April 2021 CSE, BMSCE 145


Activity To Do
movie_director(movie_title,pid) person(pid,name)

movie_title pid pid name


Guru P1 P1 ManiRathnam
Dasvathaaram P2 P2 KamalHassan
Raavan P1

Write Query to,


List down the movie titles directed by 'ManiRathnam'

select movie_title
from movie_director
where pid=(select pid from person where name=‘ManiRatnam’);

5 April 2021 CSE, BMSCE 146


Activity To Do
movie_director(movie_title,pid) person(pid,name)

movie_title pid pid name


Guru P1 P1 ManiRathnam
Dasvathaaram P2 P2 KamalHassan
Raavan P1

Write Query to,


List down the movie titles directed by 'ManiRathnam'

5 April 2021 CSE, BMSCE 147


Subqueries with ALL, ANY, IN, or SOME
□ We can use a subquery after a comparison operator, followed by the
keyword ALL, ANY, or SOME.
□ The ALL operator compares value to every value returned by the
subquery. Therefore ALL operator (which must follow a comparison
operator) returns TRUE if the comparison is TRUE for ALL of the values
in the column that the subquery returns.
□ Syntax :
operand comparison_operator ALL (subquery)

5 April 2021 CSE, BMSCE 148


Subquery: ALL operator
□ > all means greater than every value, or greater than
the maximum value.
For example, > all (1, 2, 3) means greater than 3.

5 April 2021 CSE, BMSCE 149


Subquery: ALL operator
□ > all means greater than every value, or greater than the maximum
value.

5 April 2021 CSE, BMSCE 150


Subquery: ALL operator
□ > all means greater than every value, or greater than the maximum
value.

5 April 2021 CSE, BMSCE 151


Activity To Do
□ List EMPNO and Salary of the employees whose salary is greater
than the salary of all employees in the department 20

5 April 2021 CSE, BMSCE 152


Activity To Do
□ List EMPNO and salary of the employees whose salary is greater
than the salary of all employees in the department 20

5 April 2021 CSE, BMSCE 153


Subquery: ALL operator
□ > all means greater than all values
□ The > all operator means that, for a row to satisfy the
condition in the outer query, the value in the column that
introduces the subquery must be greater than each of the
values returned by the subquery.

□ "x = ALL (...)": The value must match all the values in the list to
evaluate to TRUE.
□ "x != ALL (...)": The value must not match any values in the list to
evaluate to TRUE.
□ "x > ALL (...)": The value must be greater than the biggest value in the
list to evaluate to TRUE.
□ "x < ALL (...)": The value must be smaller than the smallest value in
the list to evaluate to TRUE.
□ "x >= ALL (...)": The value must be greater than or equal to the
biggest value in the list to evaluate to TRUE.
□ "x <= ALL (...)": The value must be smaller than or equal to the
smallest value in the list to evaluate to TRUE.

5 April 2021 CSE, BMSCE 154


Subquery: ANY operator

□ > any means greater than at least


one value, or greater than the
minimum value.
□ Therefore, > any (1, 2, 3) means
greater than 1.

5 April 2021 CSE, BMSCE 155


Subquery: ANY operator
□ > any means greater than at least one value, or greater than
the minimum value.

5 April 2021 CSE, BMSCE 156


Subquery: ANY operator
□ > any means greater than at least one value, or greater than
the minimum value.

5 April 2021 CSE, BMSCE 157


Activity To Do
□ List EMPNO and salary of the employees whose salary is greater
than the salary of any employees in the department 10

5 April 2021 CSE, BMSCE 158


Activity To Do
□ List EMPNO and salary of the employees whose salary is greater
than the salary of any employees in the department 10

5 April 2021 CSE, BMSCE 159


Subquery: ANY operator
□ > any means greater than at least one value
□ > any means that, for a row to satisfy the outer query, the
value in the column that introduces the subquery must be
greater than at least one of the values in the list returned by
the subquery.

□ "x = ANY (...)": The value must match one or more values in the list to
evaluate to TRUE.
□ "x != ANY (...)": The value must not match one or more values in the
list to evaluate to TRUE.
□ "x > ANY (...)": The value must be greater than the smallest value in
the list to evaluate to TRUE.
□ "x < ANY (...)": The value must be smaller than the biggest value in
the list to evaluate to TRUE.
□ "x >= ANY (...)": The value must be greater than or equal to the
smallest value in the list to evaluate to TRUE.
□ "x <= ANY (...)": The value must be smaller than or equal to the
biggest value in the list to evaluate to TRUE.

5 April 2021 CSE, BMSCE 160


Subquery: SOME operator

□ The SOME and ANY comparison


conditions do exactly the same thing
and are completely interchangeable.

5 April 2021 CSE, BMSCE 161


Subquery: IN Operator

□ Syntax

The number of values in the parenthesis can be


one or more, with each values separated by comma.
Values can be numerical or characters. If there is
only one value inside the parenthesis, this
command is equivalent to,

5 April 2021 CSE, BMSCE 162


Subquery: IN Operator

□ Syntax

The number of values in the parenthesis can be


one or more, with each values separated by comma.
Values can be numerical or characters. If there is
only one value inside the parenthesis, this
command is equivalent to,

5 April 2021 CSE, BMSCE 163


Subquery: IN Operator
Find the names of the publishers who have published CSE
books:
publisher titles
pid pub_name pid type
1 Pearson 1 CSE
2 Tata 2 ISE
3 ABP 3 CSE
4 GitaPress 4 EC

5 April 2021 CSE, BMSCE 164


Subquery: IN Operator
Find the names of the publishers who have published CSE
books:
publisher titles
pid pub_name pid type
1 Pearson 1 CSE
2 Tata 2 ISE
3 ABP 3 CSE
4 GitaPress 4 EC

select pub_name
from publisher pub_name
where pid in (select pid ------------
from titles Pearson
where type = ‘CSE’) ABP

5 April 2021 CSE, BMSCE 165


Activity To Do
□ List products with order quantities greater than 100.

5 April 2021 CSE, BMSCE 166


Activity To Do
□ List products with order quantities greater than 100.

5 April 2021 CSE, BMSCE 167


Topics Covered in Todays Class

Unit 1: More Complex SQL queries

Correlated SubQueries
EXISTS operator

5 April 2021 CSE, BMSCE 168


Illustration why we need to construct Correlated
Sub Queries

□ List the details of the item which is having


maximum unitprice in each class

5 April 2021 CSE, BMSCE 169


Illustration why we need to construct Correlated
Sub Queries

□ List the details of the item which is having


maximum unitprice in each class
Item

Class
Group 1

Class
Group 2

Output

5 April 2021 CSE, BMSCE 170


Illustration: Why we need Correlated Sub Queries

□ List the maximum unitprice in each class


Item

Class
Group 1

Class
Group 2

5 April 2021 CSE, BMSCE 171


Illustration: Why we need Correlated Sub Queries

□ List the class name and maximum unitprice in each


class
Item

Class
Group 1

Class
Group 2

5 April 2021 CSE, BMSCE 172


Illustration: Why we need Correlated Sub Queries

□ List the class name and maximum unitprice in each


class
Item

Class
Group 1

Class
Group 2

5 April 2021 CSE, BMSCE 173


Illustration: Why we need Correlated Sub Queries

□ List the Item name, maximum unitprice and class name in


each class
Item table

Class
Group 1

Class
Group 2

Output should be
ItemName max(unitPrice) Class
-------------------------------------------------
Long Book 60 Stationary
Chocolate IceCream 150 Food
5 April 2021 CSE, BMSCE 174
Illustration: Why we need Correlated Sub Queries

□ List the Item name, maximum unitprice and class name in


each class
Item table

Class
Group 1

Class
Group 2

5 April 2021 CSE, BMSCE 175


Illustration: Why we need Correlated Sub Queries

□ List the Item name, maximum unitprice and class name of the item
which is having maximum unitprice in each class
Item

select itemname,
max(unitprice) unitprice,class
from item
group by class,itemname;

5 April 2021 CSE, BMSCE 176


SQL GROUP BY Statement
□ The GROUP BY statement is used in conjunction with
the aggregate functions to group the result-set by one
or more columns.
□ SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
[Where .............]
GROUP BY column_name

One purpose of grouping is to display count, averages,


sum, minimum, maximum values for each group.
Note that in the result of such a query, we see only one
line per group.

5 April 2021 CSE, BMSCE 177


Illustration: Why we need Correlated Queries

□ List the class name and max,min,sum, average Unitprice and


number of items in each class

Class max(unitprice) min(unitprice) sum(unitprice) avg(unitprice) count(*)


----------------------------------------------------------------------------------------------
Stationary 60 5 110 27.5 4
Food 150 50 355 88.75 4
5 April 2021 CSE, BMSCE 178
Say, we want to
□ List the details of the item which is having
maximum unitprice in each class
Item

Class
Group 1

Class
Group 2

Output

5 April 2021 CSE, BMSCE 179


What is Independent Sub Query or Non Correlated
Sub Query ?

□ A subquery is a SELECT statement


within another statement.
Outer Query
SELECT t1.column1
FROM table t1 WHERE t1.column1 IN (SELECT t2.column1
FROM table t2
where t2.column2 >10 );

5 April 2021 CSE, BMSCE 180


What is Independent Sub Query or Non Correlated
Sub Query ?

□ A subquery is a SELECT statement


within another statement.
Outer Query
SELECT t1.column1
FROM table t1 WHERE t1.column1 IN (SELECT t2.column1
FROM table t2
where t2.column2 >10 );

Inner Query
Not dependent on columns of
Outer Query

5 April 2021 CSE, BMSCE 181


What is Correleated Sub Query ?

□ A correlated subquery is a subquery


that contains a reference to a table
that also appears in the outer query.
Outer Query
SELECT t1.column1
FROM table t1 WHERE t1.column1 IN (SELECT t2.column1
FROM table t2
where t2.column2 >t1.column2);

5 April 2021 CSE, BMSCE 182


What is Correleated Sub Query ?

□ A correlated subquery is a subquery


that contains a reference to a table
that also appears in the outer query.
Outer Query
SELECT t1.column1
FROM table t1 WHERE t1.column1 IN (SELECT t2.column1
FROM table t2
where t2.column2 >t1.column2);

Inner Query
is dependent on columns of
Outer Query
i.e., t2.colum2=t1.column2
5 April 2021 CSE, BMSCE 183
What is Correlated Sub Query
□ A correlated subquery is a subquery that contains a reference to a
table (in the parent query) that also appears in the outer query. SQL
evaluates from inside to outside.
□ Correlated subquery syntax :

□ The inner Query is executed separately for each row of the


outer query.SQL performs a subquery over and over again –
once for each row of the main query.

5 April 2021 CSE, BMSCE 184


Correlated Queries
□ List the details of the item which is having maximum unitprice
in each class
Item

5 April 2021 CSE, BMSCE 185


Logic of correlated sub queries
Outer item table

Inner item table

5 April 2021 CSE, BMSCE 186


Logic of correlated sub queries
Outer item table
Step 1
For every record of outer query
Pick the class name
Stationary

Inner item table

5 April 2021 CSE, BMSCE 187


Logic of correlated sub queries
Outer item table
Step 1
For every record of outer query
Pick the class name
Stationary

Step 2
In the inner query
Find maximum unitprice of class name picked
from outer query
i.e compare class name of outer with inner

Inner item table

Max
60

5 April 2021 CSE, BMSCE 188


Logic of correlated sub queries
Outer item table
Step 1
For every record of outer query
Pick the class name
Stationary

Step 2
In the inner query
Find maximum unitprice of class name picked
from outer query
i.e compare class name of outer with inner

Step 3 Inner item table


Check if equal, unit price
of outer query Max
with maximum 60
unit price of inner query

5 April 2021 CSE, BMSCE 189


Logic of correlated sub queries
Outer item table
Step 1
For every record of outer query
Pick the class name
Stationary

Step 2
In the inner query
Find maximum unitprice of class name picked
from outer query
i.e compare class name of outer with inner

Step 3 Inner item table


Check if equal, unit price
of outer query Max
with maximum 60
unit price of inner query

5 April 2021 CSE, BMSCE 190


Logic of correlated sub queries
Outer item table
Step 1
For every record of outer query
Pick the class name
Food

Step 2
In the inner query
Find maximum unitprice of class name picked
from outer query
i.e compare class name of outer with inner

Step 3 Inner item table


Check if equal, unit price
of outer query Max
with maximum 150
unit price of inner query

5 April 2021 CSE, BMSCE 191


Non Correlated Sub Query
□ Using IN Operator

Item

5 April 2021 CSE, BMSCE 192


Observation
□ Question : Why the Error is getting generated when we
run the following Query ?
Item

5 April 2021 CSE, BMSCE 193


Observation
□ Question: Justify why we are getting the following
output when we run the query as shown below
Item

Output

5 April 2021 CSE, BMSCE 194


Illustration of Subquery EXISTS Operator
Find the names of the publishers who have published CSE
books:

OUTPUT should be

5 April 2021 CSE, BMSCE 195


Without using Subquery EXISTS Operator
Find the names of the publishers who have published CSE
books:
□ Non Correlated Sub Query: Using IN operator

5 April 2021 CSE, BMSCE 196


Without using Subquery EXISTS Operator
Find the names of the publishers who have published CSE
books:
Using Cartesian product or Cross Join
publisher titles
pid pub_name pid type
1 Pearson 1 CSE
2 Tata 2 ISE
3 ABP 3 CSE
4 GitaPress 4 EC

pub_name
select pub_name ------------
from publisher p, titles t Pearson
where p.pid = t.pid and t.type=‘CSE’; ABP

5 April 2021 CSE, BMSCE 197


Without using Subquery EXISTS Operator
Find the names of the publishers who have published CSE
books:
Using Correlated sub query
publisher titles
pid pub_name pid type
1 Pearson 1 CSE
2 Tata 2 ISE
3 ABP 3 CSE
4 GitaPress 4 EC

pub_name
select pub_name ------------
from publisher p Pearson
where p.pid = (select t.pid from titles t ABP
where t.pid = p.pid and t.type=‘CSE’;

5 April 2021 CSE, BMSCE 198


Subquery: EXISTS Operator
□ The EXISTS keyword is used to check whether
a sub query produces any row(s) of result.
□ If the query following the EXISTS return at
least one row, then EXISTS returns TRUE
□ If the query following the EXISTS returns no
rows, then EXISTS returns FALSE

5 April 2021 CSE, BMSCE 199


Subquery: EXISTS Operator
Find the names of the publishers who have published CSE
books:
Using Exists Operator
publisher titles
pid pub_name pid type
1 Pearson 1 CSE
2 Tata 2 ISE
3 ABP 3 CSE
4 GitaPress 4 EC

select pub_name
pub_name
from publisher p
------------
where exists (select * from titles t
Pearson
where t.pid = p.pid
ABP
and type = ‘CSE’)
5 April 2021 CSE, BMSCE 200
Subquery: EXISTS Operator
Why we will get the following output when we run the query
as shown below ?
publisher titles
pid pub_name pid type
1 Pearson 1 CSE
2 Tata 2 ISE
3 ABP 3 CSE
4 GitaPress 4 EC
OUTPUT
pub_name
select pub_name ------------
from publisher p Pearson
where exists (select * from titles t Tata
where type = ‘CSE’) ABP
GitaPress
5 April 2021 CSE, BMSCE 201
Different ways of framing query for same output

S4
S1 select pub_name
from publisher p
where exists (select * from titles t
where t.pid = p.pid
and type = ‘CSE’)

select pub_name
from publisher p, titles t S2
where p.pid = t.pid and t.type=‘CSE’;

select pub_name
from publisher p S3
where p.pid = (select t.pid from titles t
where t.pid = p.pid and t.type=‘CSE’;
5 April 2021 CSE, BMSCE 202
Subquery: NOT EXISTS Operator
□ The NOT EXISTS keyword is used to check
whether a sub query produces any row(s) of
result.
□ If the query following the NOT EXISTS returns
no row, then NOT EXISTS returns TRUE
□ If the query following the NOT EXISTS returns
any row(s), then NOT EXISTS returns FALSE

5 April 2021 CSE, BMSCE 203


Subquery: NOT EXISTS Operator
□ not exists is just like exists except that the where clause in which it
is used is satisfied when no rows are returned by the subquery.
□ Find the names of publishers who do not publish CSE books

publisher titles
pid pub_name pid type
1 Pearson 1 CSE
2 Tata 2 ISE
3 ABP 3 CSE
4 GitaPress 4 EC

OUTPUT should be
pub_name
------------
Tata
GitaPress
5 April 2021 CSE, BMSCE 204
Subquery: NOT EXISTS Operator
□ not exists is just like exists except that the where clause in which it
is used is satisfied when no rows are returned by the subquery.
□ Find the names of publishers who do not publish CSE books:

publisher titles
pid pub_name pid type
1 Pearson 1 CSE
2 Tata 2 ISE
3 ABP 3 CSE
4 GitaPress 4 EC

select pub_name
from publisher pub_name
where not exists (select * from titles ------------
where pid = publisher.pid Tata
and type = ‘CSE’) GitaPress
5 April 2021 CSE, BMSCE 205
Subqueries with EXISTS or NOT EXISTS
□ The EXISTS operator tests for existence of rows in the
results set of the subquery. If a subquery row value is
found, EXISTS subquery is TRUE and in this case NOT
EXISTS subquery is FALSE.
□ Syntax :
SELECT column1 FROM table1 WHERE EXISTS (SELECT *
FROM table2);
□ Use the exists keyword with a subquery to test for the
existence of some result from the subquery:
□ {where | having} [not] exists (subquery)
□ That is, the where clause of the outer query tests for
the existence of the rows returned by the subquery. The
subquery does not actually produce any data, but
returns a value of TRUE or FALSE.

5 April 2021 CSE, BMSCE 206


Subquery: UNIQUE Operator
□ The UNIQUE keyword is used to check whether
a sub query produces any row(s) of result.
□ If the subquery following the UNIQUE returns
no two rows identical then UNIQUE returns
TRUE
□ If the subquery following the UNIQUE returns
atleast any two rows identical, then UNIQUE
returns FALSE

5 April 2021 CSE, BMSCE 207


Summary
□ In independent sub query the inner query executes
first and then the outer query executes utilizing the
result obtained by inner query.
□ In correlated sub query the inner query executed once
for every row of the outer query.
□ EXISTS returns TRUE if the inner query used returns
any one record.
□ NOT EXISTS returns TRUE if the inner query does not
return anything.

5 April 2021 CSE, BMSCE 208


SQL JOIN statement

□ The SQL Joins clause is used to


combine records from two or more
tables.
□ A JOIN is a means for combining
fields from two tables by using values
common to each.

5 April 2021 CSE, BMSCE 209


Types of JOIN operator

□ Cartesian product or Cross Join


□ Inner Join
□ Outer Join
■ Left-outer Join or Left Join
■ Right-outer Join or Right Join
□ Full Join
□ Self Join

5 April 2021 CSE, BMSCE 210


CARTESIAN JOIN or CROSS JOIN
□ The CARTESIAN JOIN or CROSS JOIN returns the Cartesian
product of the sets of records from the two or more joined
tables.
□ Syntax of CARTESIAN JOIN or CROSS JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1, table2 ;

5 April 2021 CSE, BMSCE 211


CARTESIAN JOIN or CROSS JOIN
□ The CARTESIAN JOIN or CROSS JOIN returns the Cartesian
product of the sets of records from the two or more joined
tables.
□ Syntax of CARTESIAN JOIN or CROSS JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1, table2 ;
Query

table1 table2
ID M ID N
1 a 2 p
2 b 3 q OUTPUT

4 c 5 r

5 April 2021 CSE, BMSCE 212


General Syntax of JOIN types: Inner, Left Outer,
Right Outer and Full Join

□ In order to perform a JOIN query, the required


information we need are:
a) The name of the tables
b) Name of the columns of two or more tables,
based on which a condition will perform.
□ SYNTAX

SELECT ColumNames……..
FROM table1 join_type table2
ON join_condition;

5 April 2021 CSE, BMSCE 213


General Syntax of JOIN operation
□ In order to perform a JOIN query, the required
information we need are:
a) The name of the tables
b) Name of the columns of two or more tables,
based on which a condition will perform.
□ SYNTAX

SELECT ColumNames……..
FROM table1 join_type table2
ON join_condition;

First table or Second table or


Left table Right table
5 April 2021 CSE, BMSCE 214
Inner Join
□ Inner Join or Equi Join returns rows when there is a match in
both tables.
□ The INNER JOIN creates a new result table by combining
column values of two tables (table1 and table2) based upon
the join-predicate. The query compares each row of table1 with
each row of table2 to find all pairs of rows which satisfy the
join-predicate. When the join-predicate is satisfied, column
values for each matched pair of rows of A and B are combined
into a result row.
□ Syntax of INNER JOIN:

SELECT table1.column1, table2.column2...


FROM table1 INNER JOIN table2
ON table1.common_field = table2.common_field;

5 April 2021 CSE, BMSCE 215


Inner Join

SELECT table1.column1, table2.column2...


FROM table1 INNER JOIN table2
ON table1.common_field = table2.common_field;

table1 table2
ID M ID N
1 a 2 p
ID M ID N
2 b 3 q
2 b 2 p
4 c 5 r

5 April 2021 CSE, BMSCE 216


Inner Join

SELECT table1.column1, table2.column2...


FROM table1 INNER JOIN table2
ON table1.common_field = table2.common_field;

table1 table2
ID M ID N
1 a 2 p
ID M ID N
2 b 3 q
2 b 2 p
4 c 5 r

5 April 2021 CSE, BMSCE 217


Inner Join: More than two tables
SELECT table1.column1, table2.column2,table3.colum3…....
FROM table1 INNER JOIN table2
ON table1.common_field = table2.common_field
INNER JOIN table3 ON table2.common_field = table3.common_field;
table1 table2
ID M ID N
1 a 2 p
2 b 3 q
4 c 5 r
table3 ID M ID N ID S
ID S 2 b 2 p 2 x
2 x
6 y
7 z
5 April 2021 CSE, BMSCE 218
Left Outer Join
□ Left-Outer Join returns all rows from the left table, even if
there are no matches in the right table.
□ This means that if the ON clause matches 0 (zero) records in
right table, the join will still return a row in the result, but with
NULL in each column from right table.
□ This means that a left join returns all the values from the left
table, plus matched values from the right table or NULL in case
of no matching join predicate.
□ Syntax of Left Outer Join or left join

SELECT table1.column1, table2.column2...


FROM table1 LEFT OUTER JOIN table2
ON table1.common_field = table2.common_field;

5 April 2021 CSE, BMSCE 219


Left Outer Join
SELECT table1.column1, table2.column2...
FROM table1 LEFT OUTER JOIN table2
ON table1.common_field = table2.common_field;

table1 table2
ID M ID N
1 a 2 p ID M ID N
2 b 3 q 2 b 2 P
4 c 5 r 1 a
4 c

5 April 2021 CSE, BMSCE 220


Right Outer Join
□ RIGHT JOIN or RIGHT OUTER JOIN returns all rows from
the right table, even if there are no matches in the left table.
□ This means that if the ON clause matches 0 (zero) records in
left table, the join will still return a row in the result, but with
NULL in each column from left table.
□ This means that a right join returns all the values from the
right table, plus matched values from the left table or NULL in
case of no matching join predicate.
□ Syntax of Right Outer Join or Right join

SELECT table1.column1, table2.column2...


FROM table1 RIGHT OUTER JOIN table2
ON table1.common_field = table2.common_field;

5 April 2021 CSE, BMSCE 221


Right Outer Join

SELECT table1.column1, table2.column2...


FROM table1 RIGHT OUTER JOIN table2
ON table1.common_field = table2.common_field;

table1 table2
ID M ID N
1 a 2 p
ID M ID N
2 b 3 q
2 b 2 P
4 c 5 r
3 q
5 r

5 April 2021 CSE, BMSCE 222


Full Join
□ FULL JOIN combines the results of both left and right outer
joins.
□ The joined table will contain all records from both tables, and
fill in NULLs for missing matches on either side.
□ Syntax of Full join

SELECT table1.column1, table2.column2...


FROM table1 FULL JOIN table2
ON table1.common_field = table2.common_field;

5 April 2021 CSE, BMSCE 223


Full Join

SELECT table1.column1, table2.column2...


FROM table1 FULL JOIN table2
ON table1.common_field = table2.common_field;

table1 table2
ID M ID N
1 a 2 p
ID M ID N
2 b 3 q
2 b 2 p
4 c 5 r
3 q
5 r
1 a
4 c
5 April 2021 CSE, BMSCE 224
Types of
Joins

5 April 2021 CSE, BMSCE 225


Self Join
□ SELF JOIN is used to join a table to itself as if
the table were two tables, temporarily
renaming at least one table in the SQL
statement.
□ Syntax:
SELECT a.column1, b.column2...
FROM table1 a , table1 b
WHERE table1.common_field = table1.common_field;

5 April 2021 CSE, BMSCE 226


Self Join
Write SQL query
To list all employee names along with their manager’s name
Employee table
EMP_ID EMP_Name Manager_ID
101 Avinash 103
102 Balaji 101
103 Chandan
104 Dinesh 101
OUTPUT
EMP_Name Manager_ID
Avinash Chandan
Balaji Avinash
Dinesh Avinash

5 April 2021 CSE, BMSCE 227


Logic of Self Join

Employee E Employee M

Compare
E.Manager_ID= M.EMP_ID

If equal list
E.EMP_Name, M.EMP_Name

5 April 2021 CSE, BMSCE 228


Logic of Self Join

Employee E Employee M

Compare
E.Manager_ID= M.EMP_ID

If equal list
E.EMP_Name, M.EMP_Name

5 April 2021 CSE, BMSCE 229


Logic of Self Join

Employee E Employee M

Compare
E.Manager_ID= M.EMP_ID
Output
If equal list --------------------
E.EMP_Name, M.EMP_Name Aninash, Chandan

5 April 2021 CSE, BMSCE 230


Self Join
Write SQL query
To list all employee names along with their manager’s name
Employee table

EMP_Name Manager_ID
Avinash Chandan
Balaji Avinash
Dinesh Avinash

5 April 2021 CSE, BMSCE 231


Practice SQL Query

□ List details of customer who have


purchased some items
Customer

Cust_ID Cust_Name

Customer Purchase

Cust_ID ItemID QtyPurchased TotalPrice

5 April 2021 CSE, BMSCE 232


Practice SQL Query
□ List details of customer who have purchased
some items

OUTPUT should be

5 April 2021 CSE, BMSCE 233


Practice SQL Query
□ List details of customer who have purchased
some items

5 April 2021 CSE, BMSCE 234


Practice SQL Query
□ List details of customer who have purchased
some items

5 April 2021 CSE, BMSCE 235


Practice SQL Query
□ List all customer details and loan details if they
have availed loans or yet to avail loan
Customer_Account_Details

Cust_ID Cust_Name

Customer_Loans

Loan_ID Cust_ID Amount_in_Rupees

5 April 2021 CSE, BMSCE 236


Practice SQL Query
□ List all customer details and loan details if they
have availed loans or yet to avail loan

5 April 2021 CSE, BMSCE 237


Practice SQL Query
□ List all customer details and loan details if they
have availed loans or yet to avail loan

5 April 2021 CSE, BMSCE 238


Practice SQL Query
□ Display details of Supplier who has been
ordered to supply more than one item
Supplier

Suplier_ID Suplier_Name

Item Order

Item_ID Item_name Supplier_ID

5 April 2021 CSE, BMSCE 239


Practice SQL Query
□ Display details of Supplier who has been
ordered to supply more than one item

OUTPUT

5 April 2021 CSE, BMSCE 240


Practice SQL Query
□ Display details of Supplier who has been
ordered to supply more than one item

5 April 2021 CSE, BMSCE 241


Practice SQL Query
□ Display details of Supplier who has been
ordered to supply more than one item
Supplier

Suplier_ID Suplier_Name

Item Order

Item_ID Item_name Supplier_ID

Select s.Supplier_ID,s.Supplier_Name
From Supplier s,ItemOrder i
Where s.Supplier_ID=i.SupplierID
Group By s.Supplier_ID,s.Supplier_Name
Having Count(*) > 1
5 April 2021 CSE, BMSCE 242
NULL Values
□ It is possible for tuples to have a null value, denoted by null,
for some of their attributes
□ null signifies an unknown value or that a value does not exist.
□ The predicate is null can be used to check for null values.
■ Example: Find all loan number which appear in the loan relation
with null values for amount.
select loan_number
from loan
where amount is null
□ The result of any arithmetic expression involving null is null
■ Example: 5 + null returns null
□ However, aggregate functions simply ignore nulls

5 April 2021 CSE, BMSCE 243


Null value interpretation
□ Unknown value: A particular person has date
of birth but it is not known, so it is represented
by NULL in the database.
□ Unavailable or withheld value: A person has
a home phone but does not want it to be listed,
so it is withheld and represented as NULL in the
database.
□ Not applicable attribute: An attribute
LastCollegeDegree would be NULL for a person
who has no college degree because it does not
apply to that person.

5 April 2021 CSE, BMSCE 244


Null Values and Three Valued Logic
□ TRUE, FALSE and UNKNOWN
□ A comparison between known values gives you a result of TRUE or FALSE. This is Boolean
logic.
□ When you do a comparison with a NULL, you cannot get a Boolean (i.e. TRUE or FALSE)
result. This is where the logical value UNKNOWN was invented.
□ Logical Connectives in Three-valued logic

5 April 2021 CSE, BMSCE 245


Topics Covered in Todays Class

Unit 1:
Views in SQL
Specifying Constraints as Assertions and Triggers

5 April 2021 CSE, BMSCE 246


Views in SQL
□ A view is a kind of “Virtual Table”
□ A view is customized representation of data from one or more
tables. The tables that the view is referencing are know as
base tables.
□ A view is considered as a stored query or a virtual table.
□ Why we need Views ?
Views, which are kind of virtual tables, allow users to do the following:
■ Structure data in a way that users or classes of users find natural or
intuitive.
■ Restrict access to the data such that a user can see and (sometimes)
modify exactly what they need and no more.
■ Summarize data from various tables which can be used to generate
reports.

5 April 2021 CSE, BMSCE 247


Creating Views
□ Database views are created using the CREATE
VIEW statement. Views can be created from a single
table, multiple tables, or another view.
□ To create a view, a user must have the appropriate
system privilege according to the specific
implementation.
□ The basic CREATE VIEW syntax is as follows:

CREATE VIEW view_name


AS SELECT column1, column2.....
FROM table_name
WHERE [condition];

5 April 2021 CSE, BMSCE 248


Creating Views

□ Example
faculty(F_ID, F_name, Dnum, Email_ID, Salary) department(Dname,Dnumber)

VIRTUAL
dep_info(Dept_name, Num_of_Emps, Total_Salary)
Table

5 April 2021 CSE, BMSCE 249


Creating Views

□ Example
faculty(F_ID, F_name, Dnum, Email_ID, Salary) department(Dname,Dnumber)

VIRTUAL
dep_info(Dept_name, Num_of_Emps, Total_Salary)
Table

CREATE VIEW dep_info(Dept_name,Num_of_Emps,Total_Salary)


AS Select d.Dname,count(*),sum(salary)
From department d, faculty f
Where d.Dnumber=f.Dnum
Group By d.Dname;

5 April 2021 CSE, BMSCE 250


Updating View
faculty(F_ID, F_name, Dnum, Email_ID, Salary)

VIRTUAL
cs_faculty_view(F_ID, F_name, Dnum, Email_ID)
Table

5 April 2021 CSE, BMSCE 251


Updating View
faculty(F_ID, F_name, Dnum, Email_ID, Salary)

VIRTUAL
cs_faculty_view(F_ID, F_name, Dnum, Email_ID)
Table
CREATE VIEW cs_faculty_view(F_ID, F_name, Dnum, Email_ID)
AS Select *
From faculty
Where Dnum=10;

5 April 2021 CSE, BMSCE 252


Updating View
faculty(F_ID, F_name, Dnum, Email_ID, Salary)

VIRTUAL
cs_faculty_view(F_ID, F_name, Dnum, Email_ID)
Table
CREATE VIEW cs_faculty_view(F_ID, F_name, Dnum, Email_ID)
AS Select *
From faculty
Where Dnum=10;
Update cs_faculty_view
Set Email_ID=‘[email protected]
Where Emp_name=‘Balaji’;

5 April 2021 CSE, BMSCE 253


Updating a View
A view can be updated under certain conditions:
□ The SELECT clause may not contain the keyword DISTINCT.
□ The SELECT clause may not contain aggregate functions.
□ The SELECT clause may not contain set functions.
□ The SELECT clause may not contain set operators.
□ The SELECT clause may not contain an ORDER BY clause.
□ The FROM clause may not contain multiple tables.
□ The WHERE clause may not contain subqueries.
□ The query may not contain GROUP BY or HAVING.
□ Calculated columns may not be updated.
□ All NOT NULL columns from the base table must be included in the
view in order for the INSERT query to function.
So if a view satisfies all the above-mentioned rules then you can update a
view.
Note: Similarly
□ Rows of data can be inserted into a view.
□ Rows of data can be deleted from a view.

5 April 2021 CSE, BMSCE 254


Dropping Views:

□ Syntax
□ DROP VIEW view_name;

□ Example: drop view cs_faculty_view;

5 April 2021 CSE, BMSCE 255


Advantages and Disadvantages of views
Advantages of views
□ Security: Each user can be given permission to access the database only through a small set
of views that contain the specific data the user is authorized to see, thus restricting the user's
access to stored data
□ Query Simplicity: A view can draw data from several different tables and present it as a
single table, turning multi-table queries into single-table queries against the view.
□ Structural simplicity: Views can give a user a "personalized" view of the database structure,
presenting the database as a set of virtual tables that make sense for that user.
□ Consistency: A view can present a consistent, unchanged image of the structure of the
database, even if the underlying source tables are split, restructured, or renamed.
□ Data Integrity: If data is accessed and entered through a view, the DBMS can automatically
check the data to ensure that it meets the specified integrity constraints.
□ Logical data independence: View can make the application and database tables to a certain
extent independent. If there is no view, the application must be based on a table. With the
view, the program can be established in view of above, to view the program with a database
table to be separated.

Disadvantages of views
□ Performance: Views create the appearance of a table, but the DBMS must still translate
queries against the view into queries against the underlying source tables. If the view is
defined by a complex, multi-table query then simple queries on the views may take
considerable time.
□ Update restrictions: When a user tries to update rows of a view, the DBMS must translate
the request into an update on rows of the underlying base tables. This is possible for simple
views, but more complex views are often restricted to read-only.

5 April 2021 CSE, BMSCE 256


Topics Covered in Todays Class

Unit 1:
Specifying Constraints as Assertions and Triggers

5 April 2021 CSE, BMSCE 257


Specifying Constraints in SQL

□ Specifying Attributes constraints and


Attribute values
□ Specifying Key and Referential
Integrity constraints
□ Specifying constraints on Tuples using
CHECK

5 April 2021 CSE, BMSCE 258


Specifying Attributes constraints and Attribute
values

create table student.student_info(


USN char(10),
Name char(30) NOT NULL,
DepName char(3) NOT NULL DEFAULT ‘CSE’,
Marks int NOT NULL CHECK (Marks > 0 AND Marks < 101)
);

Constraints on Attributes
- NOT NULL
- DEAFULT
- CHECK

5 April 2021 CSE, BMSCE 259


Specifying Key and Referential Integrity
constraints

□ Referential Integrity constraint or


Foreign Key Constraint

create table Department(


D_ID int,
D_Name char(3),
PRIMARY KEY (D_ID)
);

create table Student(


USN char(10),
S_Name char(20),
Dep_Num int,
PRIMARY KEY (USN),
FOREIGN KEY(Dep_Num) REFERENCES Department(D_ID)
);

5 April 2021 CSE, BMSCE 260


General Assertions

□ Constraints on entire relation or entire database


□ Syntax: CREATE ASSERTION <name> CHECK(<condition>);
Example: Salary of the employee must not be greater than the salary of the
manager of the department that the employee works for

Employee(emp_ID,emp_name,emp_dnum, salary)

Deaprtment(D_ID, D_name, Mgr_ID)

5 April 2021 CSE, BMSCE 261


General Assertions

□ Constraints on entire relation or entire database


□ Syntax: CREATE ASSERTION <name> CHECK(<condition>);
Example: Salary of the employee must not be greater than the salary of the
manager of the department that the employee works for

Employee(emp_ID,emp_name,emp_dnum, salary)

Deaprtment(D_ID, D_name, Mgr_ID)

CREATE ASSERTION Salary_constraint


CHECK (NOT EXISTS (Select e.emp_name
From Employee e, Employee m, Department d
Where e.salary > m.salary
and e.emp_dnum=d.D_ID
and d.Mgr_ID=m.emp_ID));

5 April 2021 CSE, BMSCE 262


General Assertions

□ Constraints on entire relation or entire database


□ Syntax: CREATE ASSERTION <name> CHECK(<condition>);
Example: Salary of the employee must not be greater than the salary of the
manager of the department that the employee works for

Employee(emp_ID,emp_name,emp_dnum, salary)

ASSERTION
Deaprtment(D_ID, D_name, Mgr_ID) Salary Constraint
Not Violated
CREATE ASSERTION Salary_constraint Employee(ID,name,dnum,sal)
CHECK (NOT EXISTS (Select e.emp_name ---------------------------------
From Employee e, Employee m, Department d E1,Avinash,10,1000
E2,Balaji,10,2000
Where e.salary > m.salary
and e.emp_dnum=d.D_ID
Department(D_ID,D_name,Mgr_ID)
and d.Mgr_ID=m.emp_ID)); ----------------------------------------
D1, 10, E2

5 April 2021 CSE, BMSCE 263


General Assertions

□ Constraints on entire relation or entire database


□ Syntax: CREATE ASSERTION <name> CHECK(<condition>);
Example: Salary of the employee must not be greater than the salary of the
manager of the department that the employee works for

Employee(emp_ID,emp_name,emp_dnum, salary)

ASSERTION
Deaprtment(D_ID, D_name, Mgr_ID) Salary Constraint
Violated
CREATE ASSERTION Salary_constraint Employee(ID,name,dnum,sal)
CHECK (NOT EXISTS (Select e.emp_name ---------------------------------
From Employee e, Employee m, Department d E1,Avinash,10,2000
E2,Balaji,10,1000
Where e.salary > m.salary
and e.emp_dnum=d.D_ID
Department(D_ID,D_name,Mgr_ID)
and d.Mgr_ID=m.emp_ID)); ----------------------------------------
D1, 10, E2

5 April 2021 CSE, BMSCE 264


Assertion: To Do
Write Assertion to check,
The minimum price charged for products made by Coca-Cola
Company should be Rs.20/-
Tables are:
□ cool_drink(name, manf)
□ sells(cooldrink_name, price)

General Syntax of assertions

CREATE ASSERTION <assertion_name>


CHECK (NOT EXISTS <SQL Query>);

5 April 2021 CSE, BMSCE 265


Assertion: To Do
Write Assertion to check,
The minimum price charged for products made by Coca-Cola
Company should be Rs.20/-
Tables are:
□ cool_drink(name, manf)
□ sells(cooldrink_name, price)

CREATE ASSERTION NoCheapCooolDrink


CHECK( NOT EXISTS( SELECT * FROM cool_drink, sells
WHERE sells.cooldrink_name = cool_drink.name
AND cool_drink.manf = 'Coca-Cola'
AND sells.price < 20
));

5 April 2021 CSE, BMSCE 266


Triggers
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 (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
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
□ Auditing
□ Synchronous replication of tables
□ Imposing security authorizations
□ Preventing invalid transactions

5 April 2021 CSE, BMSCE 267


Creating Triggers: Syntax

5 April 2021 CSE, BMSCE 268


Creating Triggers: Syntax
Where,
□ CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing
trigger with the trigger_name.
□ {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be
executed. The INSTEAD OF clause is used for creating trigger on a view.
□ {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
□ [OF col_name]: This specifies the column name that would be updated.
□ [ON table_name]: This specifies the name of the table associated with the
trigger.
□ [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.
□ [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.
□ WHEN (condition): This provides a condition for rows for which the trigger would
fire. This clause is valid only for row level triggers.

5 April 2021 CSE, BMSCE 269


Triggers: Example
□ To start with, we will be using the CUSTOMERS table we had created
and used in the previous chapters:

The following program creates a row level trigger for the customers table that would
fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table.
This trigger will display the salary difference between the old values and new values:

5 April 2021 CSE, BMSCE 270


Thank You for Your Time and Attention !

5 April 2021 CSE, BMSCE 271


5 April 2021 CSE, BMSCE 272
Subquery: EXISTS Operator
□ List EMPNO of the employees whose salary is greater than the
salary of any employees in the department 10

5 April 2021 CSE, BMSCE 273


Subquery: NOT EXISTS Operator
□ List EMPNO of the employees whose salary is greater than the
salary of all employees in the department 20

5 April 2021 CSE, BMSCE 274

You might also like