SQL (1)
SQL (1)
Unit 1:
- SQL Data Definition and Data Types
- Specifying basic constraints in SQL
Column or Attribute
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
Constraints on Attributes
- NOT NULL
- DEAFULT
- CHECK
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
Question
1. When the following SQL Command is executed, what will be the status of
Student table contents?
Question
1. When the following SQL Command is executed, what will be the status of
Student table contents?
□ ON DELETE CASCADE
□ ON DELETE SET NULL
□ ON DELETE SET DEFAULT
□ ON UPDATE CASCADE
□ ON UPDATE SET NULL
□ ON UPDATE SET DEFAULT
Question
1. When the following SQL Command is executed, what will be the status of
Student table contents?
Unit 1:
- Schema change statements in SQL
- Basic SQL queries
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));
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
Question
1. When the following SQL Command is executed, what will be the output
Question
1. When the following SQL Command is executed, what will be the output
Question
1. When the following SQL Command is executed, what will be the output
Question
1. When the following SQL Command is executed, what will be the output
Question
1. When the following SQL Command is executed, what will be the output
Question
1. When the following SQL Command is executed, what will be the output
Question
1. When the following SQL Command is executed, what will be the output
Question
1. When the following SQL Command is executed, what will be the output
Question
1. Whether the following two SQL commands will be executed successfully
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
□ Alter command
General Syntax:
alter table table_name [add|drop|alter]
column column_name;
□ Alter command
Student Table
USN Name Dep_
Num
1BM14CS001 Avinash 10
1BM14CS002 Balaji 10
1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20
□ Alter command
Student Table
USN Name Dep_
Num
1BM14CS001 Avinash 10
1BM14CS002 Balaji 10
1BM14CS003 Ram 10
1BM14CS004 Mohan 20
1BM14CS005 Nikil 20
□ 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 ?
□ 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
1. List out the USN’s of the students who belong to department number 10?
1. List out the USN’s of the students who belong to department number 10?
Question
1. List out the USN’s of the students who belong to CSE department ?
Question
1. List out the USN’s of the students who belong to CSE department ?
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
Example: Write SQL statement to list the names starting with letter
“A” from following student table.
Note:
Wildcard character %, A substitute for zero or more characters
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
Question
Write SQL statement to list name of the students whose names end
with letter ‘h’?
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
Question
Write SQL statement to list name of the students whose names
are having the substring ‘in’?
Question
Write SQL statement to list name of the students whose names
start with letter ‘A’ or ‘B’
Question
Write SQL statement to list name of the students whose names
start with letter ‘A’ or ‘B’
Question
Write SQL statement to list name of the students whose names
start with letter ‘A’ or ‘D’ but end with letter ‘h’
Question
Write SQL statement to list name of the students whose names
start with letter ‘A’ or ‘D’ but end with letter ‘h’
Question
Write SQL statement to list name of the students whose third letter in the
name is ‘a’ .
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.
Aggregate functions
Group BY Clause
Having Clause
□ Example:
90
90
90
90
90
90
SELECT MAX(salary)
FROM employees
WHERE job_id = 'IT_PROG';
90
90
90
90
90
90
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,...)
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
Outer Query
Inner Query
Outer Query
Inner Query
Inner Query
80
Inner Query
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)
select movie_title
from movie_director
where pid=(select pid from person where name=‘ManiRatnam’);
□ "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.
□ "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.
□ Syntax
□ Syntax
select pub_name
from publisher pub_name
where pid in (select pid ------------
from titles Pearson
where type = ‘CSE’) ABP
Correlated SubQueries
EXISTS operator
Class
Group 1
Class
Group 2
Output
Class
Group 1
Class
Group 2
Class
Group 1
Class
Group 2
Class
Group 1
Class
Group 2
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
Class
Group 1
Class
Group 2
□ 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;
Class
Group 1
Class
Group 2
Output
Inner Query
Not dependent on columns of
Outer Query
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 :
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
Max
60
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 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 2
In the inner query
Find maximum unitprice of class name picked
from outer query
i.e compare class name of outer with inner
Item
Output
OUTPUT should be
pub_name
select pub_name ------------
from publisher p, titles t Pearson
where p.pid = t.pid and t.type=‘CSE’; ABP
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’;
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
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.
table1 table2
ID M ID N
1 a 2 p
2 b 3 q OUTPUT
4 c 5 r
SELECT ColumNames……..
FROM table1 join_type table2
ON join_condition;
SELECT ColumNames……..
FROM table1 join_type table2
ON join_condition;
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
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
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
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
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
Employee E Employee M
Compare
E.Manager_ID= M.EMP_ID
If equal list
E.EMP_Name, M.EMP_Name
Employee E Employee M
Compare
E.Manager_ID= M.EMP_ID
If equal list
E.EMP_Name, M.EMP_Name
Employee E Employee M
Compare
E.Manager_ID= M.EMP_ID
Output
If equal list --------------------
E.EMP_Name, M.EMP_Name Aninash, Chandan
EMP_Name Manager_ID
Avinash Chandan
Balaji Avinash
Dinesh Avinash
Cust_ID Cust_Name
Customer Purchase
OUTPUT should be
Cust_ID Cust_Name
Customer_Loans
Suplier_ID Suplier_Name
Item Order
OUTPUT
Suplier_ID Suplier_Name
Item Order
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
Unit 1:
Views in SQL
Specifying Constraints as Assertions and Triggers
□ Example
faculty(F_ID, F_name, Dnum, Email_ID, Salary) department(Dname,Dnumber)
VIRTUAL
dep_info(Dept_name, Num_of_Emps, Total_Salary)
Table
□ Example
faculty(F_ID, F_name, Dnum, Email_ID, Salary) department(Dname,Dnumber)
VIRTUAL
dep_info(Dept_name, Num_of_Emps, Total_Salary)
Table
VIRTUAL
cs_faculty_view(F_ID, F_name, Dnum, Email_ID)
Table
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;
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’;
□ Syntax
□ DROP VIEW view_name;
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.
Unit 1:
Specifying Constraints as Assertions and Triggers
Constraints on Attributes
- NOT NULL
- DEAFULT
- CHECK
Employee(emp_ID,emp_name,emp_dnum, salary)
Employee(emp_ID,emp_name,emp_dnum, salary)
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
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
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: