Memra

Derived tables, ANY & ALL

◈ 2 cards

Query a subquery as if it were a table; compare against a set.

A subquery as a table

A subquery in the FROM clause is a derived table — you query its result like any other table (it needs an alias):

SELECT genre, avg_price
FROM (
  SELECT genre, avg(price) AS avg_price FROM books GROUP BY genre
) g
WHERE avg_price > 15;

ANY and ALL compare a value against every value a subquery returns: - price > ALL (...) — greater than every one - price > ANY (...) — greater than at least one (= ANY is the same as IN)

formwrittenreusableCTEWITH g AS (…) SELECT … FROMgyes — by name, repeatedlyderived tableSELECT … FROM (…) gonce, where it sits
Both give the intermediate result a name; only the CTE puts that name somewhere the rest of the query can reach more than once.
comparisonmeansbooks keptprice > ALL (9.99, 11.00)above the maximum7price > ANY (9.99, 11.00)above the minimum8Poetry prices are 9.99 and 11.00.
ALL must beat every value, so it collapses to the largest; ANY need beat only one, so it collapses to the smallest. That is also why = ANY is exactly IN.
NORMAL ~/memra/learn/postgresql/derived-tables-any-all utf-8 LF