Sub topic 2
NOT EXISTS, Aggregates, and Choosing EXISTS or IN
This chapter assumes you know basic SELECT, WHERE, INNER JOIN, LEFT JOIN, aggregate functions such as COUNT and AVG, table aliases, and that NULL means a missing value.
Finding rows with no match
NOT EXISTS is true when the correlated inner query returns no rows. A correlated subquery refers to a column of the outer query, so the database runs it once for each outer row.
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);This query returns customers who have no orders. The SELECT 1 list does not matter, because EXISTS checks only whether a matching row is found.
Comparing a row to an aggregate of its related rows
A correlated scalar subquery returns one value for each outer row. The following query returns orders whose total is above the average total of that customer's orders.
SELECT o.order_id, o.customer_id, o.total
FROM orders o
WHERE o.total > (
SELECT AVG(o2.total)
FROM orders o2
WHERE o2.customer_id = o.customer_id
);EXISTS or IN: when each reads better
Use EXISTS when the question is about related rows. Use IN when you compare one column against a set of values.
| Question | Better fit | Reason |
|---|---|---|
| Customers with at least one order | EXISTS | The correlated check reads as "has a related row" |
| Customers whose ID appears in a list | IN | One column, no correlation needed |
Exercise
Using products(productid, name) and orderitems(product_id), write a query that returns products that were never ordered.
Show answer
SELECT p.productid, p.name FROM products p WHERE NOT EXISTS ( SELECT 1 FROM orderitems oi WHERE oi.productid = p.productid );