TExcelTAD
Home › PostgreSQL › PostgreSQL EXISTS, ANY & ALL

PostgreSQL EXISTS, ANY & ALL

These three operators connect an outer query with a subquery (a query inside a query):

Operator True when …
EXISTS (subquery) the subquery returns at least one row
x = ANY (subquery or array) the comparison is true for at least one value
x > ALL (subquery or array) the comparison is true for every value

EXISTS

Customers who have at least one pending order. The subquery refers to the outer row's c.id, so it is re-evaluated for each customer (a correlated subquery):

pgsql · try it yourself
SELECT c.id, c.first_name
FROM customers c
WHERE EXISTS (
    SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.status = 'pending'
)
ORDER BY c.id;
 id | first_name
----+------------
  2 | Ben
  9 | Isla
(2 rows)

EXISTS only cares whether a row comes back, not what is in it, which is why SELECT 1 is a common convention.

NOT EXISTS

NOT EXISTS finds rows with no match. Authors with no books in the shop:

pgsql · try it yourself
SELECT a.name
FROM authors a
WHERE NOT EXISTS (SELECT 1 FROM books b WHERE b.author_id = a.id);
   name
-----------
 Grace Liu
(1 row)

Unlike NOT IN, NOT EXISTS is not confused by NULLs, which makes it the safest way to write an anti-join.

ANY (also called SOME)

x op ANY (…) compares x with each value from the subquery and is true if any comparison is true. = ANY is the same as IN:

pgsql · try it yourself
-- Books that appear in an order of customer 2
SELECT title FROM books
WHERE id = ANY (SELECT oi.book_id
                FROM order_items oi JOIN orders o ON o.id = oi.order_id
                WHERE o.customer_id = 2)
ORDER BY title;
           title
---------------------------
 Algorithms on a Napkin
 Learning SQL the Calm Way
 Postgres in Practice
 Rust for Curious Minds
 Signal from Kepler
(5 rows)

In PostgreSQL, ANY also works with arrays, which is very useful when an application passes a list of ids as one parameter:

pgsql · try it yourself
SELECT id, title FROM books WHERE id = ANY (ARRAY[3, 5, 13]);

SELECT title FROM books WHERE title ILIKE ANY (ARRAY['%tea%', '%moon%']);
 id |       title
----+--------------------
  3 | Signal from Kepler
  5 | Clockwork Garden
 13 | Ten Tiny Dragons
(3 rows)

         title
------------------------
 Moon Socks
 A Short History of Tea
(2 rows)

ALL

x op ALL (…) is true only if the comparison holds for every value. Books more expensive than every Science Fiction book:

pgsql · try it yourself
SELECT title, price
FROM books
WHERE price > ALL (SELECT price FROM books WHERE category_id = 2)
ORDER BY price;
           title           | price
---------------------------+-------
 The Age of Canals         | 24.95
 Empires of Sand           | 27.00
 Algorithms on a Napkin    | 35.00
 Learning SQL the Calm Way | 39.90
 Rust for Curious Minds    | 42.50
 Postgres in Practice      | 44.00
(6 rows)

Two edge cases to remember:

pgsql · try it yourself
-- ALL over an empty set is true (there is no value that fails)
SELECT 1 > ALL (SELECT price FROM books WHERE category_id = 7) AS empty_all;

-- ANY over an empty set is false
SELECT 1 > ANY (SELECT price FROM books WHERE category_id = 7) AS empty_any;

-- <> ALL is the same as NOT IN
SELECT count(*) FROM books WHERE category_id <> ALL (ARRAY[1, 2, 3]);
 empty_all
-----------
 t
(1 row)

 empty_any
-----------
 f
(1 row)

 count
-------
     9
(1 row)

Which one to use?

Question Typical form
Is there any related row? EXISTS (SELECT 1 FROM … WHERE …)
Is there no related row? NOT EXISTS (…)
Is the value in a list or array? IN (…) or = ANY (array)
Is it bigger than all of them? > ALL (…) (or > (SELECT max(…)))

Tip: > ALL (SELECT x …) and > (SELECT max(x) …) behave differently when the subquery returns NULLs or no rows. The max form returns NULL for an empty set, so no row matches.

Test yourself

When is EXISTS (subquery) true?

  1. When the subquery returns a non-NULL value
  2. When the subquery returns at least one row
  3. When every row matches
  4. When the subquery returns exactly one row

Which is equivalent to id IN (1, 2, 3)?

  1. id = ALL (ARRAY[1,2,3])
  2. id = ANY (ARRAY[1,2,3])
  3. id > ANY (ARRAY[1,2,3])
  4. EXISTS (1, 2, 3)

What is 5 > ALL (empty subquery)?

  1. true
  2. false
  3. NULL
  4. An error