SQL: Structured Query LanguageAggregation
What is the difference between WHERE and HAVING in SQL?
Question 1 of 1 · Updated
Both filter data, but at different stages of a query:
- WHERE filters individual rows before they are grouped.
- HAVING filters groups after
GROUP BYand aggregation, so it can use aggregates such asCOUNT(*)orSUM(...).
SQL-- Customers with more than 5 paid orders in 2026 SELECT customer_id, COUNT(*) AS paid_orders FROM orders WHERE status = 'paid' -- row filter: runs first AND created_at >= DATE '2026-01-01' GROUP BY customer_id HAVING COUNT(*) > 5; -- group filter: runs after aggregation
Logical order of a query: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
Tip: put every condition that doesn't need an aggregate in WHERE. Filtering rows early means less data to group, which is usually faster.
Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning