TExcelTAD
Home › PostgreSQL › PostgreSQL HAVING

PostgreSQL HAVING

WHERE filters rows before they are grouped. HAVING filters groups after the aggregates have been computed. Use it when the condition involves an aggregate such as count(*) or sum(…).

Filtering groups

Customers who placed more than one order:

pgsql · try it yourself
SELECT customer_id, count(*) AS orders
FROM orders
GROUP BY customer_id
HAVING count(*) > 1
ORDER BY orders DESC, customer_id;
 customer_id | orders
-------------+--------
           1 |      3
           2 |      3
           4 |      2
           5 |      2
           9 |      2
          10 |      2
(6 rows)

Trying the same with WHERE fails, because aggregates don't exist yet when WHERE runs:

pgsql · try it yourself
SELECT customer_id, count(*) AS orders
FROM orders
WHERE count(*) > 1
GROUP BY customer_id;
ERROR:  aggregate functions are not allowed in WHERE
LINE 3: WHERE count(*) > 1
              ^

WHERE and HAVING together

They often appear in the same query. The order of evaluation is:

  1. FROM / JOIN builds the rows
  2. WHERE removes rows
  3. GROUP BY forms groups
  4. HAVING removes groups
  5. SELECT computes the output, then ORDER BY and LIMIT

Categories whose in-stock books are worth more than 400 in total:

pgsql · try it yourself
SELECT cat.name, count(*) AS titles_in_stock, sum(b.price * b.stock) AS value
FROM books b
JOIN categories cat ON cat.id = b.category_id
WHERE b.stock > 0
GROUP BY cat.name
HAVING sum(b.price * b.stock) > 400
ORDER BY value DESC;
      name       | titles_in_stock |  value
-----------------+-----------------+---------
 Programming     |               4 | 1175.10
 Science Fiction |               3 |  491.25
 Mystery         |               3 |  489.11
 Children        |               2 |  457.20
 Fiction         |               4 |  456.78
(5 rows)

Tip: If a condition does not need an aggregate, put it in WHERE. Filtering rows early means less work for the grouping step.

Conditions on several aggregates

HAVING can combine conditions with AND/OR, and can use aggregates that are not in the select list:

pgsql · try it yourself
SELECT b.title,
       sum(oi.quantity) AS copies,
       count(*) AS order_lines
FROM order_items oi
JOIN books b ON b.id = oi.book_id
GROUP BY b.id
HAVING count(*) >= 2 AND sum(oi.quantity) >= 3
ORDER BY copies DESC, b.title;
        title         | copies | order_lines
----------------------+--------+-------------
 Ten Tiny Dragons     |      7 |           3
 Moon Socks           |      5 |           2
 Signal from Kepler   |      4 |           3
 The Salt Road        |      4 |           3
 Clockwork Garden     |      3 |           2
 Postgres in Practice |      3 |           3
 The Map Thief        |      3 |           2
(7 rows)

HAVING with FILTER

Combine HAVING with FILTER to ask questions such as "which customers have at least one delivered and at least one open order?":

pgsql · try it yourself
SELECT customer_id,
       count(*) FILTER (WHERE status = 'delivered')              AS delivered,
       count(*) FILTER (WHERE status IN ('pending', 'shipped')) AS open
FROM orders
GROUP BY customer_id
HAVING count(*) FILTER (WHERE status = 'delivered') > 0
   AND count(*) FILTER (WHERE status IN ('pending', 'shipped')) > 0
ORDER BY customer_id;
 customer_id | delivered | open
-------------+-----------+------
           2 |         2 |    1
           5 |         1 |    1
           9 |         1 |    1
(3 rows)

HAVING without GROUP BY

Without GROUP BY, the whole table is one group, so HAVING decides whether the single result row appears at all:

pgsql · try it yourself
SELECT count(*) AS cancelled FROM orders WHERE status = 'cancelled' HAVING count(*) > 5;
SELECT count(*) AS cancelled FROM orders WHERE status = 'cancelled' HAVING count(*) > 0;
 cancelled
-----------
(0 rows)

 cancelled
-----------
         2
(1 row)

Test yourself

What is the difference between WHERE and HAVING?

  1. None, they are synonyms
  2. WHERE filters rows before grouping, HAVING filters groups after aggregation
  3. HAVING filters rows, WHERE filters groups
  4. HAVING only works with joins

Why does WHERE count(*) > 1 fail?

  1. count needs a column
  2. Aggregate functions are not allowed in WHERE
  3. 1 must be quoted
  4. WHERE must come after GROUP BY

You want only books with price > 10, grouped by category, keeping categories with 3+ such books. Where does price > 10 go?

  1. HAVING
  2. WHERE
  3. GROUP BY
  4. ORDER BY