Sub topic 2
Comparing Against a Set with ANY and ALL
This chapter assumes you know SELECT, WHERE, GROUP BY, joins, and how NULL behaves in comparisons.
Comparing with ANY and ALL
A multi-row subquery returns a list of values. ANY and ALL compare one value against every item in that list.
> ANYis true if the value is greater than at least one item.> ALLis true only if the value is greater than every item.
SELECT name
FROM employees
WHERE salary > ALL (SELECT salary FROM employees WHERE department_id = 10);This query returns employees paid more than everyone in department 10. If the subquery returns no rows, ALL is true and ANY is false.
Correlated Subqueries
A correlated subquery refers to a column of the outer query. The database evaluates it once for each outer row.
SELECT e.name, e.department_id, e.salary
FROM employees e
WHERE e.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e.department_id
);The alias e belongs to the outer query. Each employee is compared with the average salary of that employee's own department.
EXISTS and NOT EXISTS
EXISTS returns true if the subquery returns at least one row. It only checks for a match, so the select list is usually SELECT 1.
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);Unlike NOT IN, NOT EXISTS is not affected by NULL values in orders.customer_id.
Subqueries in the SELECT List
A scalar subquery in the SELECT list produces one value for each outer row.
SELECT c.name,
(SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.id) AS order_count
FROM customers c;Customers with no orders show 0. The subquery must return exactly one value per row, or the query fails.
Exercise
Exercise
Write a query that returns the names of customers who have placed at least one order, using EXISTS.
Show answer
SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);