Challenge - 5 Problems
HAVING Clause Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Filtering groups with HAVING clause
Given a table
sales with columns region and amount, what is the output of this query?SELECT region, SUM(amount) AS total_sales FROM sales GROUP BY region HAVING SUM(amount) > 1000;
PostgreSQL
CREATE TABLE sales (region TEXT, amount INT); INSERT INTO sales VALUES ('North', 500), ('North', 600), ('South', 400), ('South', 300), ('East', 1200), ('West', 800);
Attempts:
2 left
💡 Hint
Remember HAVING filters groups after aggregation, unlike WHERE which filters rows before grouping.
✗ Incorrect
The query groups sales by region and sums the amounts. HAVING filters groups where the sum is greater than 1000. 'North' sums to 1100, 'East' sums to 1200, both included. 'South' and 'West' sums are less than or equal to 1000, so excluded.
🧠 Conceptual
intermediate1:30remaining
Understanding HAVING vs WHERE
Which statement correctly explains the difference between WHERE and HAVING clauses in SQL?
Attempts:
2 left
💡 Hint
Think about when aggregation happens in the query process.
✗ Incorrect
WHERE filters individual rows before any grouping or aggregation happens. HAVING filters the groups after aggregation functions like SUM or COUNT are applied.
📝 Syntax
advanced2:00remaining
Identify the syntax error in HAVING clause
Which option contains a syntax error in the HAVING clause?
PostgreSQL
SELECT department, COUNT(*) AS emp_count FROM employees GROUP BY department HAVING emp_count > 5;
Attempts:
2 left
💡 Hint
Can you use column aliases directly in HAVING in PostgreSQL?
✗ Incorrect
In PostgreSQL, you cannot use column aliases defined in SELECT inside HAVING. You must repeat the aggregate function. Option A uses the alias 'emp_count' which causes a syntax error.
❓ optimization
advanced2:00remaining
Optimizing HAVING with WHERE
Consider this query:
What is the main benefit of using the WHERE clause here?
SELECT category, SUM(price) AS total_price FROM products WHERE price > 10 GROUP BY category HAVING SUM(price) > 100;
What is the main benefit of using the WHERE clause here?
Attempts:
2 left
💡 Hint
Think about when WHERE filters data compared to HAVING.
✗ Incorrect
WHERE filters rows before grouping and aggregation, so fewer rows are processed in aggregation, improving performance. HAVING filters after aggregation and cannot reduce rows before grouping.
🔧 Debug
expert2:30remaining
Debugging unexpected HAVING results
A developer runs this query:
But it returns a syntax error. What is the cause?
SELECT customer_id, COUNT(order_id) AS order_count FROM orders GROUP BY customer_id HAVING order_count > 3;
But it returns a syntax error. What is the cause?
Attempts:
2 left
💡 Hint
Check if column aliases can be used in HAVING in PostgreSQL.
✗ Incorrect
PostgreSQL does not allow using SELECT column aliases in HAVING. The aggregate function must be repeated in HAVING clause.