SlideShare a Scribd company logo
1 of 55
1
1
Database Systems
(4th Semester)
Module 3.1
Advances in Queries
Reference: Fundamentals of Database Systems, RamezElmasri and Shamkant B. Navathe. 7th
Edition, 2017, Pearson
OUTLINE
 Advances in SQL
 More complex SQL retrieval queries
 Specifying constraints as assertions
 Triggers, Views in SQL
 Schema change statements in SQL.
2
MORE COMPLEX SQL RETRIEVAL QUERIES
Comparisons Involving NULL and Three-Valued
Logic
 Unknown value. A person’s date of birth is not
known, so it is represented by NULL in the
database. An example of the other case of unknown
would be NULL for a person’s home phone because it
is not known whether or not the person has a home
phone.
 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 degrees because it does not apply
to that person. 3
NESTED QUERIES
 A Subquery or Inner query or a Nested query is a
query within another SQL query and embedded
within the WHERE clause.
 A subquery is used to return data that will be used in
the main query as a condition to further restrict the
data to be retrieved.
 Subqueries can be used with the SELECT, INSERT,
UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.
 A subquery can return a single value, a single row, a
single column, or a table containing one or more rows
of one or more columns.
4
SUBQUERIES
5
NESTED QUERIES (SINGLE ROW SUBQUERY EXAMPLES)
 Retrieve the customers who earn salary more than
the salary of Customer with ID 6??
SELECT * FROM CUSTOMERS
WHERE salary > (SELECT salary FROM
CUSTOMERS WHERE id=6)
 Retrieve the customers who earn salary same as
that of Ramesh
SELECT * FROM CUSTOMERS
WHERE salary = (SELECT salary FROM
CUSTOMERS WHERE NAME=‘Ramesh’)
6
NESTED QUERIES (MULTIPLE ROW SUBQUERY EXAMPLES)
 Write a query to find the employees whose salary is
greater than at least on employee in department of
id 500?
SELECT EMPLOYEE_ID, SALARY FROM
EMPLOYEES WHERE SALARY > ANY ( SELECT
SALARY FROM EMPLOYEES WHERE
DEPARTMENT_ID = 500 )
 Write a query to find the employees whose salary is
less than the salary of all employees in department
of id 100?
SELECT EMPLOYEE_ID, SALARY FROM
EMPLOYEES WHERE SALARY < ALL ( SELECT
SALARY FROM EMPLOYEES WHERE
DEPARTMENT_ID = 100 )
7
NESTED QUERIES
 Write a query to find the employees whose salary is
equal to the salary of at least one employee in
department of id 300?
SELECT EMPLOYEE_ID, SALARY FROM
EMPLOYEES WHERE SALARY IN ( SELECT
SALARY FROM EMPLOYEES WHERE
DEPARTMENT_ID = 300 )
 Update SALARY by 0.25 times in the
CUSTOMERS table for all the customers whose
salary is same as that of Ramesh.
UPDATE CUSTOMERS SET SALARY = SALARY *
0.25 WHERE salary IN (SELECT SALARY FROM
CUSTOMERS WHERE NAME=‘Ramesh’ );
8
9
10
11
12
13
14
15
The IN operator is equivalent to =ANY.
For example, to display the employees who have subordinates,
use the following SQL statement:
SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id IN
(SELECT mgr.manager_id
FROM employees mgr);
Alternatively, a WHERE clause can be included in the subquery
to display all employees who do not have any subordinates:
SELECT last_name FROM employees
WHERE employee_id NOT IN
(SELECT manager_id
FROM employees
where manager_id is not null);
16
NESTED QUERIES
 Delete the records from CUSTOMERS table for all
the customers whose salary is same as that of
Ramesh.
DELETE FROM CUSTOMERS
WHERE SALARY IN (SELECT SALARY FROM
CUSTOMERS WHERE NAME=‘Ramesh’ );
 Select the Essns of all employees who work the
same (project, hours) combination on some project
that employee ‘John Smith’ (whose Ssn =
‘123456789’) works on.
SELECT DISTINCT Essn
FROM WORKS_ON
WHERE (Pno, Hours) IN ( SELECT Pno, Hours FROM
WORKS_ON WHERE Essn = ‘123456789’ );
17
NESTED QUERY/SUB QUERY
 List products with order quantities greater than 100.
18
NESTED QUERY/SUB QUERY
 List all customers with their total number of orders
19
SELECT FirstName, LastName
FROM Customer C
WHERE OrderCount = (SELECT COUNT(O.Id)
FROM Order O
WHERE O.CustomerId = C.Id)
NESTED QUERY/SUB QUERY
 Return the names of employees whose
salary is greater than the salary of all the
employees in department 5:
SELECT Lname, Fname
FROM EMPLOYEE
WHERE Salary > ALL ( SELECT Salary
FROM EMPLOYEE
WHERE Dno = 5 );
20
GROUP BY CLAUSE
The GROUP BY Clause is utilized in SQL with the
SELECT statement to organize similar data into
groups. It combines the multiple records in single or
more columns using some functions.
 GROUP BY Clause is utilized with the SELECT
statement.
 GROUP BY aggregates the results on the basis of
selected column: COUNT, MAX, MIN, SUM, AVG,
etc.
 GROUP BY returns only one result per group of
data.
 GROUP BY Clause always follows the WHERE
Clause.
 GROUP BY Clause always precedes the ORDER
BY
21
GROUP BY CLAUSE
22
GROUP BY CLAUSE
23
 Return the AVERAGE salary of the respective
department
SELECT Avg(Salary)
FROM EMPLOYEE
GROUP BY DEPT ID ;
 Return the names of employees whose salary is greater
than the AVERAGE salary of the all the departments
SELECT Lname, Fname
FROM EMPLOYEE
WHERE Salary > ALL( SELECT Avg(Salary)
FROM EMPLOYEE
GROUP BY DEPT ID);
SQL HAVING CLAUSE
24
 HAVING is like WHERE but operates on grouped
records returned by a GROUP BY.
 HAVING applies to summarized group records,
whereas WHERE applies to individual records.
 Only the groups that meet the HAVING criteria will
be returned.
 HAVING requires that a GROUP BY clause is
present.
 WHERE and HAVING can be used in the same
query.
SQL HAVING CLAUSE
25
 List the number of customers in each country.
Only include countries with more than 10
customers.
SELECT COUNT(Id), Country
FROM Customer
GROUP BY Country
HAVING COUNT(Id) > 10
26
27
28
NESTED QUERY
29
 Retrieve the name of each employee who has a
dependent with the same first name and is the
same gender as the employee
SELECT E.Fname, E.Lname
FROM EMPLOYEE AS E
WHERE E.Ssn IN ( SELECT D.Essn
FROM DEPENDENT AS D
WHERE E.Fname = D.Dependent_name
AND E.Gender = D.Gender );
CORRELATED NESTED QUERIES
 Whenever a condition in the WHERE clause of a
nested query references some attribute of a relation
declared in the outer query, the two queries are
said to be correlated
30
CORRELATED NESTED QUERIES
 Retrieve the names and Ids of employees whOse salary
is greater than the average salary of the department
SELECT E1.EMP_NAME, E1.EMP_ID
FROM employee E1
WHERE SALARY>(SELECT AVG(SALARY)
FROM employee E2
WHERE E2.DEP_ID=E1.DEP_ID
GROUP BY DEP_ID);
31
EXISTS / NOT EXISTS
 Retrieve the names of employees who have dependents.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn );
 Retrieve the names of employees who have dependents.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE NOT EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn );
32
EXISTS / NOT EXISTS
 List the names of managers who have at least one
dependent.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE EXISTS ( SELECT *
FROM DEPENDENT
WHERE Ssn = Essn )
AND
EXISTS ( SELECT *
FROM DEPARTMENT
WHERE Ssn = Mgr_ssn );
33
RENAME
 Retrieve the last name of each employee and his or her
supervisor while renaming the resulting attribute names
as Employee_name and Supervisor_name
SELECT E.EMP_NAME AS Employee_name,
S.EMP_NAME AS Supervisor_name
FROM EMPLOYEE E, EMPLOYEE S
WHERE E.MANAGER_ID = S.EMP_ID;
34
AGGREGATE FUNCTIONS
 Find the sum of the salaries of all employees, the
maximum salary, the minimum salary, and the average
salary.
SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary)
FROM EMP
 Retrieve the total number of employees in the company
SELECT COUNT (*)
FROM EMPLOYEE;
 Retrieve the total number of employees of employees in
the ‘Research’ department
SELECT COUNT (*)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO = DNUMBER AND DNAME = ‘Research’; 35
JOIN CONDITIONS
 There may be at least one join condition either in the
FROM clause or in the WHERE clause for joining two
tables. It compares two columns from different tables
and combines pair of rows, each containing one row
from each table, for which join condition is true.
 Oracle INNER JOIN
 Inner Join is the simplest and most common type of join.
It is also known as simple join. It returns all rows from
multiple tables where the join condition is met.
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
36
JOIN CONDITIONS
 Oracle INNER JOIN
37
SELECT SUPPLIERS.SUPPLIER_ID,
SUPPLIERS.SUPPLIER_NAME, ORDER1.ORDER_NUMBER
FROM SUPPLIERS
INNER JOIN ORDER1
ON SUPPLIERS.SUPPLIER_ID = ORDER1.SUPPLIER_ID;
JOIN CONDITIONS
 Oracle OUTER JOIN
Left Outer Join
 Left Outer Join returns all rows from the left (first) table
specified in the ON condition and only those rows from
the right (second) table where the join condition is met
38
SELECT SUPPLIERS.SUPPLIER_ID,
SUPPLIERS.SUPPLIER_NAME,
ORDER1.ORDER_NUMBER
FROM SUPPLIERS
LEFT OUTER JOIN ORDER1
ON SUPPLIERS.SUPPLIER_ID =
ORDER1.SUPPLIER_ID;
;
JOIN CONDITIONS
 Oracle OUTER JOIN
Right Outer Join
 The Right Outer Join returns all rows from the right-hand
table specified in the ON condition and only those rows
from the other table where the join condition is met.
39
SELECT SUPPLIERS.SUPPLIER_ID,
SUPPLIERS.SUPPLIER_NAME,
ORDER1.ORDER_NUMBER
FROM SUPPLIERS
RIGHT OUTER JOIN ORDER1
ON SUPPLIERS.SUPPLIER_ID =
ORDER1.SUPPLIER_ID;
JOIN CONDITIONS
Full Outer Join
 The Full Outer Join returns all rows from the left
hand table and right hand table. It places NULL
where the join condition is not met.
40
SELECT SUPPLIERS.SUPPLIER_ID, SUPPLIERS.SUPPLIER_NAME,
ORDER1.ORDER_NUMBER
FROM SUPPLIERS
FULL OUTER JOIN ORDER1
ON SUPPLIERS.SUPPLIER_ID = ORDER1.SUPPLIER_ID;;
;
JOIN CONDITIONS
Oracle EQUI JOIN
Retrieve the names of the managers
SELECT ENAME
FROM EMPLOYEE, DEPARTMENT
WHERE MGR_NO=SSN;
OR
SELECT E.ENAME
FROM EMPLOYEE E, DEPARTMENT D
WHERE D.MGR_NO=E.SSN;
41
JOIN CONDITIONS
SELFJOIN
A self join is a join in which a table is joined with itself (which is also called Unary
relationships), especially when the table has a FOREIGN KEY which references
its own PRIMARY KEY.
 List of employees and their supervisor
SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee Name",
b.emp_id AS "Supervisor ID",b.emp_name AS "Supervisor Name"
FROM employee a, employee b WHERE a.emp_supv = b.emp_id; 42
JOIN CONDITIONS
 Oracle Cross Join (Cartesian Products)
 The CROSS JOIN specifies that all rows from first
table join with all of the rows of second table. If
there are "x" rows in table1 and "y" rows in table2
then the cross join result set have x*y rows.
SELECT * FROM customer,supplier
43
SPECIFYING GENERAL CONSTRAINTS AS ASSERTIONS IN
SQL
 In SQL, users can specify general Constraints
via declarative assertions, using the CREATE
ASSERTION statement of the DDL. Each assertion is given
a constraint name and is specified via a condition similar to
the WHERE clause of an SQL query.
 For example, to specify the constraint that the salary of an
employee must not be greater than the salary of the
manager of the department that the employee works
for in SQL, we can write the following assertion:
CREATE ASSERTION SALARY_CONSTRAINT
CHECK ( NOT EXISTS ( SELECT *
FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D
WHERE E.Salary>M.Salary AND E.Dno=D.Dnumber
AND D.Mgr_ssn=M.Ssn ) );
44
TRIGGERS
 A database trigger is a stored PL/SQL program unit associated
with a specific database table. ORACLE executes (fires) a
database trigger automatically when a given SQL operation
(like INSERT, UPDATE or DELETE) affects the table. Unlike a
procedure, or a function, which must be invoked explicitly,
database triggers are invoked implicitly.
 Three parts:
 Event (activates the trigger)
 Condition (tests whether the triggers should run) [Optional]
 Action (what happens if the trigger runs)
 Events could be :
BEFORE|AFTER INSERT|UPDATE|DELETE ON <tableName>
e.g.: BEFORE INSERT ON Professor
45
TRIGGERS
Assume our DB has a relation schema :
Professor (pNum, pName, salary)
We want to write a trigger that :
Ensures that any new professor inserted has salary >= 100000
Eg.,
CREATE TRIGGER minSalary BEFORE INSERT ON Professor
for what context ?
BEGIN
check for violation here ?
END;
46
TRIGGERS
CREATE TRIGGER minSalary BEFORE INSERT ON
Professor
FOR EACH ROW
BEGIN
IF (:new.salary < 100000)
THEN RAISE_APPLICATION_ERROR (-20004,
‘Violation of Minimum
Professor Salary’);
END IF;
END; 47
TRIGGERS
CREATE TRIGGER min_Salary BEFORE INSERT ON
EMPLOYEE
FOR EACH ROW
BEGIN
IF (:new.salary < 10000)
THEN RAISE_APPLICATION_ERROR (-
20004,'Violation of Minimum Salary');
END IF;
END;
48
VIEW
You can present logical subsets or combinations of data by creating
views of tables. A view is a logical table based on a table or another
view. A view contains no data of its own but is like a window through
which data from tables can be viewed or changed. The tables on
which a view is based are called base tables. The view is stored as a
SELECT statement in the data dictionary.
49
CREATING A VIEW
 Create a view, EMPVU80, that contains details of
employees in department 80.
CREATE OR REPLAVE VIEW empvu80
AS SELECT employee_id, last_name,
salary
FROM employees
WHERE department_id = 80;
SELECT * FROM empvu50
DROP VIEW view_name;
50
CREATING A VIEW
51
USES OF A VIEW :
A good database should contain views due to the given reasons:
 Restricting data access –
Views provide an additional level of table security by restricting access to a
predetermined set of rows and columns of a table.
 Hiding data complexity –
A view can hide the complexity that exists in a multiple table join.
 Simplify commands for the user –
Views allows the user to select information from multiple tables without
requiring the users to actually know how to perform a join.
 Rename Columns –
Views can also be used to rename the columns without affecting the base
tables provided the number of columns in view must match the number of
columns specified in select statement. Thus, renaming helps to to hide the
names of the columns of the base tables.
 Multiple view facility –
Different views can be created on the same table for different users. 52
SCHEMA CHANGE STATEMENTS IN SQL
The DROP command can be used to drop named schema elements, such as tables,
domains, types, or constraints. One can also drop a whole schema if it is no longer
needed by using the DROP SCHEMA command. There are two drop behavior
options: CASCADE and RESTRICT. For example, to remove the COMPANY database
schema and all its tables, domains, and other elements, the CASCADE option is used
as follows:
DROP SCHEMA COMPANY CASCADE;
If the RESTRICT option is chosen in place of CASCADE, the schema is dropped only
if it has no elements in it; otherwise, the DROP command will not be executed. To
use the RESTRICT option, the user must first individually drop each element in the
schema, then drop the schema itself.
For example, if we no longer
wish to keep track of dependents of employees in the COMPANY database we can get rid of the
DEPENDENT relation by issuing the following command:
DROP TABLE DEPENDENT CASCADE;
If the RESTRICT option is chosen instead of CASCADE, a table is dropped only if it is
not referenced in any constraints (for example, by foreign key definitions in another
relation) or views
53
SCHEMA CHANGE STATEMENTS IN SQL
ALTER COMMAND
 DROP A CONSTARINT
 ADD A CONSTARINT
 ADD A COLUMN
 DROP A COLUMN
 MODIFY THE COLUMN
54
SUMMARY
 Advances in SQL
 More complex SQL retrieval queries
 Specifying constraints as assertions
 Triggers, Views in SQL
 Schema change statements in SQL.
55

More Related Content

Similar to Module 3.1.pptx

Similar to Module 3.1.pptx (20)

Chinabankppt
ChinabankpptChinabankppt
Chinabankppt
 
ALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMSALL ABOUT SQL AND RDBMS
ALL ABOUT SQL AND RDBMS
 
Les02
Les02Les02
Les02
 
Sql2
Sql2Sql2
Sql2
 
Les02
Les02Les02
Les02
 
Les02 (restricting and sorting data)
Les02 (restricting and sorting data)Les02 (restricting and sorting data)
Les02 (restricting and sorting data)
 
Sql server lab_3
Sql server lab_3Sql server lab_3
Sql server lab_3
 
sql language
sql languagesql language
sql language
 
Aggregate Functions,Final
Aggregate Functions,FinalAggregate Functions,Final
Aggregate Functions,Final
 
SQL- Introduction to MySQL
SQL- Introduction to MySQLSQL- Introduction to MySQL
SQL- Introduction to MySQL
 
sql statement
sql statementsql statement
sql statement
 
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
 
75864 sql
75864 sql75864 sql
75864 sql
 
Module03
Module03Module03
Module03
 
Basic SQL Statments
Basic SQL StatmentsBasic SQL Statments
Basic SQL Statments
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptxSQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
 
Les06
Les06Les06
Les06
 

Recently uploaded

VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfRachmat Ramadhan H
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023ymrp368
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxolyaivanovalion
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationshipsccctableauusergroup
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxfirstjob4
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxMohammedJunaid861692
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxolyaivanovalion
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxolyaivanovalion
 

Recently uploaded (20)

VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdfMarket Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
Market Analysis in the 5 Largest Economic Countries in Southeast Asia.pdf
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships04242024_CCC TUG_Joins and Relationships
04242024_CCC TUG_Joins and Relationships
 
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Punjabi Bagh 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptx
 
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptxBPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
BPAC WITH UFSBI GENERAL PRESENTATION 18_05_2017-1.pptx
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
BigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptxBigBuy dropshipping via API with DroFx.pptx
BigBuy dropshipping via API with DroFx.pptx
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Carero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptxCarero dropshipping via API with DroFx.pptx
Carero dropshipping via API with DroFx.pptx
 

Module 3.1.pptx

  • 1. 1 1 Database Systems (4th Semester) Module 3.1 Advances in Queries Reference: Fundamentals of Database Systems, RamezElmasri and Shamkant B. Navathe. 7th Edition, 2017, Pearson
  • 2. OUTLINE  Advances in SQL  More complex SQL retrieval queries  Specifying constraints as assertions  Triggers, Views in SQL  Schema change statements in SQL. 2
  • 3. MORE COMPLEX SQL RETRIEVAL QUERIES Comparisons Involving NULL and Three-Valued Logic  Unknown value. A person’s date of birth is not known, so it is represented by NULL in the database. An example of the other case of unknown would be NULL for a person’s home phone because it is not known whether or not the person has a home phone.  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 degrees because it does not apply to that person. 3
  • 4. NESTED QUERIES  A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause.  A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.  Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.  A subquery can return a single value, a single row, a single column, or a table containing one or more rows of one or more columns. 4
  • 6. NESTED QUERIES (SINGLE ROW SUBQUERY EXAMPLES)  Retrieve the customers who earn salary more than the salary of Customer with ID 6?? SELECT * FROM CUSTOMERS WHERE salary > (SELECT salary FROM CUSTOMERS WHERE id=6)  Retrieve the customers who earn salary same as that of Ramesh SELECT * FROM CUSTOMERS WHERE salary = (SELECT salary FROM CUSTOMERS WHERE NAME=‘Ramesh’) 6
  • 7. NESTED QUERIES (MULTIPLE ROW SUBQUERY EXAMPLES)  Write a query to find the employees whose salary is greater than at least on employee in department of id 500? SELECT EMPLOYEE_ID, SALARY FROM EMPLOYEES WHERE SALARY > ANY ( SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID = 500 )  Write a query to find the employees whose salary is less than the salary of all employees in department of id 100? SELECT EMPLOYEE_ID, SALARY FROM EMPLOYEES WHERE SALARY < ALL ( SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID = 100 ) 7
  • 8. NESTED QUERIES  Write a query to find the employees whose salary is equal to the salary of at least one employee in department of id 300? SELECT EMPLOYEE_ID, SALARY FROM EMPLOYEES WHERE SALARY IN ( SELECT SALARY FROM EMPLOYEES WHERE DEPARTMENT_ID = 300 )  Update SALARY by 0.25 times in the CUSTOMERS table for all the customers whose salary is same as that of Ramesh. UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE salary IN (SELECT SALARY FROM CUSTOMERS WHERE NAME=‘Ramesh’ ); 8
  • 9. 9
  • 10. 10
  • 11. 11
  • 12. 12
  • 13. 13
  • 14. 14
  • 15. 15
  • 16. The IN operator is equivalent to =ANY. For example, to display the employees who have subordinates, use the following SQL statement: SELECT emp.last_name FROM employees emp WHERE emp.employee_id IN (SELECT mgr.manager_id FROM employees mgr); Alternatively, a WHERE clause can be included in the subquery to display all employees who do not have any subordinates: SELECT last_name FROM employees WHERE employee_id NOT IN (SELECT manager_id FROM employees where manager_id is not null); 16
  • 17. NESTED QUERIES  Delete the records from CUSTOMERS table for all the customers whose salary is same as that of Ramesh. DELETE FROM CUSTOMERS WHERE SALARY IN (SELECT SALARY FROM CUSTOMERS WHERE NAME=‘Ramesh’ );  Select the Essns of all employees who work the same (project, hours) combination on some project that employee ‘John Smith’ (whose Ssn = ‘123456789’) works on. SELECT DISTINCT Essn FROM WORKS_ON WHERE (Pno, Hours) IN ( SELECT Pno, Hours FROM WORKS_ON WHERE Essn = ‘123456789’ ); 17
  • 18. NESTED QUERY/SUB QUERY  List products with order quantities greater than 100. 18
  • 19. NESTED QUERY/SUB QUERY  List all customers with their total number of orders 19 SELECT FirstName, LastName FROM Customer C WHERE OrderCount = (SELECT COUNT(O.Id) FROM Order O WHERE O.CustomerId = C.Id)
  • 20. NESTED QUERY/SUB QUERY  Return the names of employees whose salary is greater than the salary of all the employees in department 5: SELECT Lname, Fname FROM EMPLOYEE WHERE Salary > ALL ( SELECT Salary FROM EMPLOYEE WHERE Dno = 5 ); 20
  • 21. GROUP BY CLAUSE The GROUP BY Clause is utilized in SQL with the SELECT statement to organize similar data into groups. It combines the multiple records in single or more columns using some functions.  GROUP BY Clause is utilized with the SELECT statement.  GROUP BY aggregates the results on the basis of selected column: COUNT, MAX, MIN, SUM, AVG, etc.  GROUP BY returns only one result per group of data.  GROUP BY Clause always follows the WHERE Clause.  GROUP BY Clause always precedes the ORDER BY 21
  • 23. GROUP BY CLAUSE 23  Return the AVERAGE salary of the respective department SELECT Avg(Salary) FROM EMPLOYEE GROUP BY DEPT ID ;  Return the names of employees whose salary is greater than the AVERAGE salary of the all the departments SELECT Lname, Fname FROM EMPLOYEE WHERE Salary > ALL( SELECT Avg(Salary) FROM EMPLOYEE GROUP BY DEPT ID);
  • 24. SQL HAVING CLAUSE 24  HAVING is like WHERE but operates on grouped records returned by a GROUP BY.  HAVING applies to summarized group records, whereas WHERE applies to individual records.  Only the groups that meet the HAVING criteria will be returned.  HAVING requires that a GROUP BY clause is present.  WHERE and HAVING can be used in the same query.
  • 25. SQL HAVING CLAUSE 25  List the number of customers in each country. Only include countries with more than 10 customers. SELECT COUNT(Id), Country FROM Customer GROUP BY Country HAVING COUNT(Id) > 10
  • 26. 26
  • 27. 27
  • 28. 28
  • 29. NESTED QUERY 29  Retrieve the name of each employee who has a dependent with the same first name and is the same gender as the employee SELECT E.Fname, E.Lname FROM EMPLOYEE AS E WHERE E.Ssn IN ( SELECT D.Essn FROM DEPENDENT AS D WHERE E.Fname = D.Dependent_name AND E.Gender = D.Gender );
  • 30. CORRELATED NESTED QUERIES  Whenever a condition in the WHERE clause of a nested query references some attribute of a relation declared in the outer query, the two queries are said to be correlated 30
  • 31. CORRELATED NESTED QUERIES  Retrieve the names and Ids of employees whOse salary is greater than the average salary of the department SELECT E1.EMP_NAME, E1.EMP_ID FROM employee E1 WHERE SALARY>(SELECT AVG(SALARY) FROM employee E2 WHERE E2.DEP_ID=E1.DEP_ID GROUP BY DEP_ID); 31
  • 32. EXISTS / NOT EXISTS  Retrieve the names of employees who have dependents. SELECT Fname, Lname FROM EMPLOYEE WHERE EXISTS ( SELECT * FROM DEPENDENT WHERE Ssn = Essn );  Retrieve the names of employees who have dependents. SELECT Fname, Lname FROM EMPLOYEE WHERE NOT EXISTS ( SELECT * FROM DEPENDENT WHERE Ssn = Essn ); 32
  • 33. EXISTS / NOT EXISTS  List the names of managers who have at least one dependent. SELECT Fname, Lname FROM EMPLOYEE WHERE EXISTS ( SELECT * FROM DEPENDENT WHERE Ssn = Essn ) AND EXISTS ( SELECT * FROM DEPARTMENT WHERE Ssn = Mgr_ssn ); 33
  • 34. RENAME  Retrieve the last name of each employee and his or her supervisor while renaming the resulting attribute names as Employee_name and Supervisor_name SELECT E.EMP_NAME AS Employee_name, S.EMP_NAME AS Supervisor_name FROM EMPLOYEE E, EMPLOYEE S WHERE E.MANAGER_ID = S.EMP_ID; 34
  • 35. AGGREGATE FUNCTIONS  Find the sum of the salaries of all employees, the maximum salary, the minimum salary, and the average salary. SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary) FROM EMP  Retrieve the total number of employees in the company SELECT COUNT (*) FROM EMPLOYEE;  Retrieve the total number of employees of employees in the ‘Research’ department SELECT COUNT (*) FROM EMPLOYEE, DEPARTMENT WHERE DNO = DNUMBER AND DNAME = ‘Research’; 35
  • 36. JOIN CONDITIONS  There may be at least one join condition either in the FROM clause or in the WHERE clause for joining two tables. It compares two columns from different tables and combines pair of rows, each containing one row from each table, for which join condition is true.  Oracle INNER JOIN  Inner Join is the simplest and most common type of join. It is also known as simple join. It returns all rows from multiple tables where the join condition is met. SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column; 36
  • 37. JOIN CONDITIONS  Oracle INNER JOIN 37 SELECT SUPPLIERS.SUPPLIER_ID, SUPPLIERS.SUPPLIER_NAME, ORDER1.ORDER_NUMBER FROM SUPPLIERS INNER JOIN ORDER1 ON SUPPLIERS.SUPPLIER_ID = ORDER1.SUPPLIER_ID;
  • 38. JOIN CONDITIONS  Oracle OUTER JOIN Left Outer Join  Left Outer Join returns all rows from the left (first) table specified in the ON condition and only those rows from the right (second) table where the join condition is met 38 SELECT SUPPLIERS.SUPPLIER_ID, SUPPLIERS.SUPPLIER_NAME, ORDER1.ORDER_NUMBER FROM SUPPLIERS LEFT OUTER JOIN ORDER1 ON SUPPLIERS.SUPPLIER_ID = ORDER1.SUPPLIER_ID; ;
  • 39. JOIN CONDITIONS  Oracle OUTER JOIN Right Outer Join  The Right Outer Join returns all rows from the right-hand table specified in the ON condition and only those rows from the other table where the join condition is met. 39 SELECT SUPPLIERS.SUPPLIER_ID, SUPPLIERS.SUPPLIER_NAME, ORDER1.ORDER_NUMBER FROM SUPPLIERS RIGHT OUTER JOIN ORDER1 ON SUPPLIERS.SUPPLIER_ID = ORDER1.SUPPLIER_ID;
  • 40. JOIN CONDITIONS Full Outer Join  The Full Outer Join returns all rows from the left hand table and right hand table. It places NULL where the join condition is not met. 40 SELECT SUPPLIERS.SUPPLIER_ID, SUPPLIERS.SUPPLIER_NAME, ORDER1.ORDER_NUMBER FROM SUPPLIERS FULL OUTER JOIN ORDER1 ON SUPPLIERS.SUPPLIER_ID = ORDER1.SUPPLIER_ID;; ;
  • 41. JOIN CONDITIONS Oracle EQUI JOIN Retrieve the names of the managers SELECT ENAME FROM EMPLOYEE, DEPARTMENT WHERE MGR_NO=SSN; OR SELECT E.ENAME FROM EMPLOYEE E, DEPARTMENT D WHERE D.MGR_NO=E.SSN; 41
  • 42. JOIN CONDITIONS SELFJOIN A self join is a join in which a table is joined with itself (which is also called Unary relationships), especially when the table has a FOREIGN KEY which references its own PRIMARY KEY.  List of employees and their supervisor SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee Name", b.emp_id AS "Supervisor ID",b.emp_name AS "Supervisor Name" FROM employee a, employee b WHERE a.emp_supv = b.emp_id; 42
  • 43. JOIN CONDITIONS  Oracle Cross Join (Cartesian Products)  The CROSS JOIN specifies that all rows from first table join with all of the rows of second table. If there are "x" rows in table1 and "y" rows in table2 then the cross join result set have x*y rows. SELECT * FROM customer,supplier 43
  • 44. SPECIFYING GENERAL CONSTRAINTS AS ASSERTIONS IN SQL  In SQL, users can specify general Constraints via declarative assertions, using the CREATE ASSERTION statement of the DDL. Each assertion is given a constraint name and is specified via a condition similar to the WHERE clause of an SQL query.  For example, to specify the constraint that the salary of an employee must not be greater than the salary of the manager of the department that the employee works for in SQL, we can write the following assertion: CREATE ASSERTION SALARY_CONSTRAINT CHECK ( NOT EXISTS ( SELECT * FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D WHERE E.Salary>M.Salary AND E.Dno=D.Dnumber AND D.Mgr_ssn=M.Ssn ) ); 44
  • 45. TRIGGERS  A database trigger is a stored PL/SQL program unit associated with a specific database table. ORACLE executes (fires) a database trigger automatically when a given SQL operation (like INSERT, UPDATE or DELETE) affects the table. Unlike a procedure, or a function, which must be invoked explicitly, database triggers are invoked implicitly.  Three parts:  Event (activates the trigger)  Condition (tests whether the triggers should run) [Optional]  Action (what happens if the trigger runs)  Events could be : BEFORE|AFTER INSERT|UPDATE|DELETE ON <tableName> e.g.: BEFORE INSERT ON Professor 45
  • 46. TRIGGERS Assume our DB has a relation schema : Professor (pNum, pName, salary) We want to write a trigger that : Ensures that any new professor inserted has salary >= 100000 Eg., CREATE TRIGGER minSalary BEFORE INSERT ON Professor for what context ? BEGIN check for violation here ? END; 46
  • 47. TRIGGERS CREATE TRIGGER minSalary BEFORE INSERT ON Professor FOR EACH ROW BEGIN IF (:new.salary < 100000) THEN RAISE_APPLICATION_ERROR (-20004, ‘Violation of Minimum Professor Salary’); END IF; END; 47
  • 48. TRIGGERS CREATE TRIGGER min_Salary BEFORE INSERT ON EMPLOYEE FOR EACH ROW BEGIN IF (:new.salary < 10000) THEN RAISE_APPLICATION_ERROR (- 20004,'Violation of Minimum Salary'); END IF; END; 48
  • 49. VIEW You can present logical subsets or combinations of data by creating views of tables. A view is a logical table based on a table or another view. A view contains no data of its own but is like a window through which data from tables can be viewed or changed. The tables on which a view is based are called base tables. The view is stored as a SELECT statement in the data dictionary. 49
  • 50. CREATING A VIEW  Create a view, EMPVU80, that contains details of employees in department 80. CREATE OR REPLAVE VIEW empvu80 AS SELECT employee_id, last_name, salary FROM employees WHERE department_id = 80; SELECT * FROM empvu50 DROP VIEW view_name; 50
  • 52. USES OF A VIEW : A good database should contain views due to the given reasons:  Restricting data access – Views provide an additional level of table security by restricting access to a predetermined set of rows and columns of a table.  Hiding data complexity – A view can hide the complexity that exists in a multiple table join.  Simplify commands for the user – Views allows the user to select information from multiple tables without requiring the users to actually know how to perform a join.  Rename Columns – Views can also be used to rename the columns without affecting the base tables provided the number of columns in view must match the number of columns specified in select statement. Thus, renaming helps to to hide the names of the columns of the base tables.  Multiple view facility – Different views can be created on the same table for different users. 52
  • 53. SCHEMA CHANGE STATEMENTS IN SQL The DROP command can be used to drop named schema elements, such as tables, domains, types, or constraints. One can also drop a whole schema if it is no longer needed by using the DROP SCHEMA command. There are two drop behavior options: CASCADE and RESTRICT. For example, to remove the COMPANY database schema and all its tables, domains, and other elements, the CASCADE option is used as follows: DROP SCHEMA COMPANY CASCADE; If the RESTRICT option is chosen in place of CASCADE, the schema is dropped only if it has no elements in it; otherwise, the DROP command will not be executed. To use the RESTRICT option, the user must first individually drop each element in the schema, then drop the schema itself. For example, if we no longer wish to keep track of dependents of employees in the COMPANY database we can get rid of the DEPENDENT relation by issuing the following command: DROP TABLE DEPENDENT CASCADE; If the RESTRICT option is chosen instead of CASCADE, a table is dropped only if it is not referenced in any constraints (for example, by foreign key definitions in another relation) or views 53
  • 54. SCHEMA CHANGE STATEMENTS IN SQL ALTER COMMAND  DROP A CONSTARINT  ADD A CONSTARINT  ADD A COLUMN  DROP A COLUMN  MODIFY THE COLUMN 54
  • 55. SUMMARY  Advances in SQL  More complex SQL retrieval queries  Specifying constraints as assertions  Triggers, Views in SQL  Schema change statements in SQL. 55

Editor's Notes

  1. 1