Consider a table sales with columns region, product, and amount. Which query correctly returns regions with total sales greater than 1000?
SELECT region, SUM(amount) AS total_sales FROM sales WHERE amount > 100 GROUP BY region HAVING SUM(amount) > 1000;
Remember that WHERE filters rows before grouping, and HAVING filters groups after aggregation.
The WHERE amount > 100 filters out sales less than or equal to 100 before grouping. Then HAVING total_sales > 1000 filters groups where the sum is greater than 1000. So only regions with individual sales over 100 and total sales over 1000 are returned.
Why does the order of filtering conditions matter in SQL queries involving aggregation?
Think about when rows are filtered versus when groups are filtered.
WHERE filters rows before aggregation, so it affects which rows are included in groups. HAVING filters groups after aggregation. Changing the order changes which data is aggregated and which groups remain.
Which option contains a syntax error in filtering aggregated data?
SELECT department, COUNT(*) AS emp_count FROM employees GROUP BY department WHERE emp_count > 10;
Check the order of clauses in SQL and which clause filters aggregated results.
WHERE filters rows before grouping and cannot filter aggregated results. To filter groups based on aggregate functions like COUNT, use HAVING after GROUP BY.
Given a large orders table, which filtering approach is more efficient to find customers with more than 5 orders?
SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id HAVING COUNT(*) > 5;
Think about how indexes affect query performance on large tables.
Indexes on columns used in GROUP BY and filtering can speed up query execution by reducing data scanned. Filtering with WHERE on aggregate functions is not possible. Using HAVING is correct but adding an index improves performance.
A query returns no rows but you expect some. The query is:
SELECT category, AVG(price) AS avg_price FROM products WHERE price < 200 GROUP BY category HAVING AVG(price) > 150;
What is the most likely reason for no results?
Consider how WHERE affects which rows are included before aggregation.
The WHERE clause removes all products priced 200 or more before grouping. This reduces the number of rows per category, which can lower the average price below 150, causing HAVING to filter out all groups.