HAVING — Complete Guide
HAVING — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 14 of 100
HAVING
SQL → Advanced
SQL · 1 — Queries · ~6 min · PostgreSQL — SQL & Queries
What is this?
HAVING filters groups after aggregation, unlike WHERE which filters raw rows. Use it when the condition involves COUNT, SUM, or other aggregate results.
Why should you care?
Marketing wants Swiggy restaurants with more than 500 orders this week — HAVING COUNT(*) > 500 after GROUP BY restaurant_id.
See it live — copy this example
Run in pgAdmin or psql.
SELECT restaurant_id, COUNT(*) AS orders_this_week
FROM orders
WHERE created_at >= date_trunc('week', now())
GROUP BY restaurant_id
HAVING COUNT(*) >= 100
ORDER BY orders_this_week DESC;
What happened?
- WHERE trims rows to this week first.
- GROUP BY buckets by restaurant.
- HAVING drops restaurants under 100 orders.
- The result is high-volume partners only.
Practice next
- Ensure orders has restaurant_id and created_at columns.
- Run the query and note fewer rows than GROUP BY without HAVING.
- Change threshold to 10 and compare counts.
- HAVING SUM(total_amount) > 50000 for high-GMV restaurants.
- Combine HAVING COUNT(*) >= 100 AND AVG(total_amount) > 300.
Remember
HAVING filters summarized groups. WHERE filters individual rows before grouping. Both can appear in one query with different jobs.
PostgresVerse partner tiering
Ops promotes restaurants with HAVING COUNT >= 100 to gold tier for faster payouts.
Outcome: SQL encodes tier rules instead of exporting CSVs to Excel.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!