← Вернуться к курсу: SQL and databases from scratch

Subqueries: queries inside queries

Видео скоро появится

Sometimes a question is solved in two steps: first you compute something, then you use that result to filter. For example: which products cost more than the average price? You need the average price before you can compare. A subquery is a SELECT written in parentheses inside another query, and the engine resolves it first. It is one of the most versatile tools in SQL, and in this lesson you will see its four usual places.

Scalar subquery

A scalar subquery returns exactly one value (one row and one column) and can be used wherever a number or a text would go: in a WHERE, in the SELECT or in a HAVING. If it returns more than one row, PostgreSQL gives the error more than one row returned by a subquery used as an expression. If it returns none, the value is NULL.

sql
-- Products priced above the average price
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;

-- The most expensive product(s)
SELECT name, price FROM products WHERE price = (SELECT MAX(price) FROM products);

Subquery with IN and with EXISTS

When the subquery returns a list of values, it is compared with IN. When you only need to know whether any row exists, EXISTS is used, which returns true as soon as it finds a match (usually more efficient). The negative versions, NOT IN and NOT EXISTS, answer questions of the who does not have kind. Here there is a serious trap: if the NOT IN list contains any NULL, the condition is never true and returns nothing. NOT EXISTS does not have that problem, so it is the safest option.

sql
-- Customers who bought product 1 (Laptop 14), with nested IN
SELECT name FROM customers
WHERE customer_id IN (
  SELECT customer_id FROM orders
  WHERE order_id IN (SELECT order_id FROM order_items WHERE product_id = 1)
);

-- Customers without orders, using NOT EXISTS
SELECT c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);

-- Products that appear in at least one cancelled order
SELECT p.name
FROM products p
WHERE EXISTS (
  SELECT 1 FROM order_items oi JOIN orders o ON o.order_id = oi.order_id
  WHERE oi.product_id = p.product_id AND o.status = 'cancelled'
);

Correlated subqueries and in FROM

In the EXISTS examples the subquery refers to a column of the outer query (c.customer_id, p.product_id): it is a correlated subquery, and conceptually it runs once per outer row. It works very well with small and medium volumes, and the PostgreSQL optimizer usually rewrites it efficiently. You can also put a subquery in the FROM clause, as if it were a temporary table; in PostgreSQL it requires a mandatory alias (derived table). It is useful for aggregating at two levels, for example computing the average of already aggregated totals.

sql
-- Products priced above the average of THEIR OWN category (correlated)
SELECT p.name, p.category, p.price
FROM products p
WHERE p.price > (SELECT AVG(p2.price) FROM products p2 WHERE p2.category = p.category);

-- Orders worth more than the average order (subquery in FROM, alias is mandatory)
SELECT t.order_id, t.order_total
FROM (
  SELECT order_id, SUM(quantity * unit_price) AS order_total
  FROM order_items
  GROUP BY order_id
) AS t
WHERE t.order_total > (SELECT AVG(order_total) FROM (
  SELECT SUM(quantity * unit_price) AS order_total FROM order_items GROUP BY order_id
) AS x)
ORDER BY t.order_total DESC;

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →