HAVING and week 3 review
Imagine you want to know which customers have placed at least two orders. Your first instinct would be to write WHERE COUNT(*) >= 2, but PostgreSQL will answer with an error: aggregate functions are not allowed in WHERE. The reason is the logical order: WHERE applies to individual rows before grouping, when no count exists yet. To filter groups that are already computed there is HAVING, which is written after GROUP BY.
-- Customers with 2 or more orders
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 2
ORDER BY orders DESC, customer_id;
-- Categories with more than 2 products
SELECT category, COUNT(*) AS products
FROM products
GROUP BY category
HAVING COUNT(*) > 2;WHERE versus HAVING
The practical rule: WHERE filters rows of the table (before grouping) and HAVING filters groups (after grouping). If the condition talks about a plain column, such as status or category, it goes in WHERE, and it is also more efficient, because the engine discards rows before doing the work of grouping. If it talks about the result of an aggregate function, such as COUNT or SUM, it goes in HAVING. Many queries use both at once, each in its place.
-- Order lines: total per order, only for orders worth more than 500
SELECT order_id, SUM(quantity * unit_price) AS order_total
FROM order_items
GROUP BY order_id
HAVING SUM(quantity * unit_price) > 500
ORDER BY order_total DESC;
-- WHERE and HAVING together: ignore cancelled orders first, then keep customers with 2+
SELECT customer_id, COUNT(*) AS valid_orders
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING COUNT(*) >= 2;Look at the second example: by excluding the cancelled order, Bruno (customer 2) goes from 2 orders to 1 and disappears from the result. This shows how WHERE changes the groups that HAVING later evaluates. A style detail: in HAVING you repeat the full expression instead of using the alias, because in PostgreSQL the SELECT alias does not exist yet at that point (MySQL allows it, but it is not standard). In ORDER BY, on the other hand, you can use the alias.
Counting conditionally with FILTER
Sometimes you want several counts in the same query, each with its own condition. PostgreSQL offers the FILTER clause, placed after an aggregate, which restricts which rows enter it. It is a very handy way to build summary reports in a single row. In MySQL the same is achieved with SUM(CASE WHEN ... THEN 1 ELSE 0 END), a technique we will study in week 5.
SELECT COUNT(*) AS all_orders,
COUNT(*) FILTER (WHERE status = 'delivered') AS delivered,
COUNT(*) FILTER (WHERE status = 'pending') AS pending,
COUNT(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM orders;To close the week, put everything together in a single report and read it in logical order: which table the rows come from (FROM), which are discarded (WHERE), how they are grouped (GROUP BY), which groups are kept (HAVING), which columns are shown (SELECT) and how they are sorted and trimmed (ORDER BY and LIMIT). If you master that sequence, you can reason about any query with aggregations without memorizing loose rules. Practice explaining aloud each step of your own queries; if you can explain it, you have truly understood it.
Teste dein Wissen
Frage 1 von 6What does COUNT(email) return if a customer has a NULL email?
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen