0% found this document useful (0 votes)
2 views61 pages

Lecture - Subqueries

The document is a lecture outline on subqueries in database systems, covering topics such as single row and multiple row subqueries, execution examples, and rules for using subqueries. It includes practical SQL examples for retrieving, updating, and deleting data using subqueries, as well as discussions on correlated and non-correlated subqueries. The lecture is presented by Ms. Hirra Anwar, an Assistant Professor in the Faculty of Computing.

Uploaded by

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

Lecture - Subqueries

The document is a lecture outline on subqueries in database systems, covering topics such as single row and multiple row subqueries, execution examples, and rules for using subqueries. It includes practical SQL examples for retrieving, updating, and deleting data using subqueries, as well as discussions on correlated and non-correlated subqueries. The lecture is presented by Ms. Hirra Anwar, an Assistant Professor in the Faculty of Computing.

Uploaded by

maryamanuur91
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

CS220 – DATABASE SYSTEMS

WEEK 9 LECTURE 1
SUBQUERIES

Ms. Hirra Anwar


Assistant Professor
Faculty of Computing
[email protected]
LECTURE OUTLINE
 Subquery
 Single Row Subquery

 Multiple row subquery

 Null with Subquery

2
SUBQUERY
PROBLEM

4
SOLUTION- SUBQUERY

5
SUBQUERY

6
RULES FOR SUBQUERY

7
TYPES OF SUBQUERIES

8
SINGLE ROW SUBQUERY
SINGLE ROW SUBQUERY

10
EXECUTION OF SINGLE ROW QUERY

Display the employees whose job ID is the same as that


of employee 141 and salary equal to employee 143.

Schema:
Employees(employee_id, first_name, last_name,
department_id, job_id, salary)
Departments(department_id, dname)

11
EXECUTION OF SINGLE ROW QUERY

Display the employees whose job ID is the same as that


of employee 141 and salary equal to employee 143.

12
EXECUTION OF SINGLE ROW QUERY

13
GROUP FUNCTION IN SUBQUERY

14
HAVING CLAUSE IN SUBQUERY

15
EXAMPLE: OUTPUT OF QUERY

16
SOLUTION: OUTPUT

17
MULTIPLE ROW SUBQUERY
MULTIPLE ROW SUBQUERY

19
MULTIPLE ROW OPERATORS

20
PRACTICE QUESTIONS
• Product(ProductID, ProductName, Price, Category)
• Department(DepartmentID, DepartmentName, Location)
• Customer(CustomerID, DepartmentID, CustomerName, Email)
• Order(OrderID, OrderDate, CustomerID, ProductID)

 Retrieve all customers who work in departments located in New


York.
 Retrieve products that are more expensive than any product in

the Electronics category.


 Retrieve products that are more expensive than every product in

the Furniture category.


 Retrieve customers who have placed at least one order.
21
 Retrieve customers who have not placed any orders.
EXAMPLE
• Product(ProductID, ProductName, Price, Category)
• Department(DepartmentID, DepartmentName, Location)
• Customer(CustomerID, CustomerName, Email)
• Order(OrderID, OrderDate, CustomerID, ProductID)

 Retrieve all employees who work in departments


located in New York.

SELECT CustomerID, Name


FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID
FROM Departments
WHERE Location = 'New York');

22
EXAMPLE
• Product(ProductID, ProductName, Price, Category)
• Department(DepartmentID, DepartmentName, Location)
• Customer(CustomerID, CustomerName, Email)
• Order(OrderID, OrderDate, CustomerID, ProductID)

 Retrieve products that are more expensive than any


product in the Electronics category.

SELECT ProductName
FROM Products
WHERE Price > ANY (SELECT Price
FROM Products
WHERE Category = 'Electronics');

23
EXAMPLE
• Product(ProductID, ProductName, Price, Category)
• Department(DepartmentID, DepartmentName, Location)
• Customer(CustomerID, CustomerName, Email)
• Order(OrderID, OrderDate, CustomerID, ProductID)

 Retrieve products that are more expensive than every


product in the Furniture category.

SELECT ProductName
FROM Products
WHERE Price > ALL (SELECT Price
FROM Products
WHERE Category = 'Furniture');

24
EXAMPLE
• Product(ProductID, ProductName, Price, Category)
• Department(DepartmentID, DepartmentName, Location)
• Customer(CustomerID, CustomerName, Email)
• Order(OrderID, OrderDate, CustomerID, ProductID)

 Retrieve customers who have placed at least one order.

SELECT CustomerID, CustomerName


FROM Customers
WHERE EXISTS (SELECT *
FROM Orders
WHERE Orders.CustomerID = Customers.CustomerID);

25
EXAMPLE
• Product(ProductID, ProductName, Price, Category)
• Department(DepartmentID, DepartmentName, Location)
• Customer(CustomerID, CustomerName, Email)
• Order(OrderID, OrderDate, CustomerID, ProductID)

 Retrieve customers who have not placed any orders.

SELECT CustomerID, CustomerName


FROM Customers
WHERE NOT EXISTS (SELECT *
FROM Orders
WHERE Orders.CustomerID = Customers.CustomerID);

26
ANY AND ALL RULES
<ANY means less than the maximum.
>ANY means more than the minimum.
=ANY is equivalent to IN.

>ALL means more than the maximum,


<ALL means less than the minimum.

27
ANY AND ALL RULES
Find employees who are not IT programmers and whose salary is
less than that of any IT programmer.

28
ANY AND ALL RULES
Find employees who are not IT programmers and whose salary is
less than all of the IT programmers.

29
ANY OPERATOR WITH SUBQUERY

30
ALL OPERATOR WITH SUBQUERY

31
EXISTS OPERATOR WITH SUBQUERY

32
NULL WITH SUBQUERY
NULL IN SUBQUERY

34
NOT EXISTS

Avoid using NOT IN


if there is a chance
of having NULL in
the column. Use
NOT EXISTS
instead.
35
MORE ON SUBQUERY
Revisit!

37
Revisit!

38
Revisit!

39
Example-1
WHERE clause-IN
Operator

40
Example-2
WHERE clause-
NOT IN Operator

41
Example-3
WHERE clause
-Multiple Column

42
Example-4
HAVING clause

43
Example-5
FROM clause

44
SUBQUERY FOR UPDATING DATA
• Product(ProductID, ProductName, Price, Category)
• Department(DepartmentID, DepartmentName, Location)
• Customer(CustomerID, CustomerName, Email)
• Order(OrderID, OrderDate, CustomerID, ProductID)

 Increase the price of all products that are more


expensive than the average price.

 UPDATE Product
 SET Price = Price * 1.10

 WHERE Price > (SELECT AVG(Price) FROM Product);


45
SUBQUERY FOR DELETING DATA
 Delete products that were never ordered.

 DELETE FROM Product


 WHERE ProductID NOT IN (

 SELECT DISTINCT ProductID FROM Order);

46
SUBQUERY FOR CREATING TABLES
 Create a new table for high-value customers who placed
orders for products over $1000.

CREATE TABLE HighValueCustomers AS


SELECT DISTINCT c.CustomerID, c.CustomerName, c.Email
FROM Customer c
JOIN Order o ON c.CustomerID = o.CustomerID
JOIN Product p ON o.ProductID = p.ProductID
WHERE p.Price > 1000;
In SQL, parentheses are not required around a subquery when it's part of 47
a CREATE TABLE AS statement or a SELECT ... INTO clause (in some RDBMS).
SUBQUERY FOR CREATING TABLES
 CREATE TABLE NewTable AS
 SELECT ...

 FROM ...

 WHERE ...;

 It’s a standalone SELECT that directly is used to create


the structure and feed the data.

In SQL, parentheses are not required around a subquery when it's part of 48
a CREATE TABLE AS statement or a SELECT ... INTO clause (in some RDBMS).
CORRELATED SUBQUERIES
Students
Id Name Class Marks
1 Ali 10 85
2 Sara 10 78
3 Ahmed 9 92
4 Zoya 9 70
5 Bilal 10 90

Q-Find the top scorer(s) in each class.

For every class, find the student(s) who have the


49
highest marks in that class.
CORRELATED SUBQUERIES
SELECT name, class, marks
FROM students s1
WHERE marks = (
SELECT MAX(marks)
FROM students s2
WHERE s1.class = s2.class
); Id Name Class Marks
1 Ali 10 85
2 Sara 10 78
3 Ahmed 9 92
4 Zoya 9 70
50
5 Bilal 10 90
CORRELATED SUBQUERIES
Id Name Class Marks
1 Ali 10 85
2 Sara 10 78
3 Ahmed 9 92
4 Zoya 9 70
5 Bilal 10 90

Step 1: Start with the outer query.


Step 2: For each row, run the inner subquery (correlated).

For each student, the subquery is executed, where s1.class


comes from the current row in the outer query.

Step 3: Comparison of marks with the max of class marks 51


Step 4: Select rows for output if the condition matches
CORRELATED SUBQUERIES
Id Name Category Price
1 iPhone Mobile 1200
2 Galaxy Mobile 950
3 MacBook Laptop 2000
4 Dell XPS Laptop 1800
5 AirPods Accessories 200
6 Apply Watch Accessories 400

Q- Find products that are the most expensive in their


category.

52
CORRELATED SUBQUERIES

For each product in the outer query, we calculate


the maximum price in its category using the
subquery.

53
CORRELATED SUBQUERIES

SELECT name, category, price


FROM products p1
WHERE price = (
SELECT MAX(price)
FROM products p2
WHERE p1.category = p2.category
);

For each product in the outer query, we calculate


the maximum price in its category using the
subquery.
54
CORRELATED SUBQUERIES

Find products that belong to categories where the


average price is greater than $1000.

SELECT name, category, price


FROM products
WHERE category IN (
SELECT category
FROM products
GROUP BY category
HAVING AVG(price) > 1000
); 55
CORRELATED SUBQUERIES

Find products that are more expensive than the


average price of their own category.

56
CORRELATED SUBQUERIES

Find products that are more expensive than the


average price of their own category.

SELECT name, category, price


FROM products p1
WHERE price > (
SELECT AVG(price)
FROM products p2
WHERE p1.category = p2.category
);

57
CORRELATED SUBQUERIES

Find all products that belong to a category which


has more than one product.

58
CORRELATED SUBQUERIES

Find all products that belong to a category which


has more than one product.

SELECT name, category, price


FROM products
WHERE category IN (
SELECT category
FROM products
GROUP BY category
HAVING COUNT(*) > 1
);
59
SUBQUERIES
 Non-Correlated subqueries
 A non-correlated subquery is independent of the outer
query.
It runs once, and the result is used by the outer query.
 Can run on its own.
 Does not reference any column of the outer query.

 Correlated subqueries
 A correlated subquery depends on the outer query.
It runs once for each row processed by the outer query.
 References a column from the outer query.

 Cannot run independently 60


THANK YOU

You might also like