Challenge - 5 Problems
HAVING Clause Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of HAVING with GROUP BY and aggregate
Given the 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 total_sales > 1000;
MySQL
SELECT region, SUM(amount) AS total_sales FROM sales GROUP BY region HAVING total_sales > 1000;
Attempts:
2 left
💡 Hint
HAVING filters groups after aggregation, using the alias defined in SELECT.
✗ Incorrect
The HAVING clause filters groups created by GROUP BY. Here, it filters regions whose total sales exceed 1000. The alias total_sales can be used in HAVING in MySQL.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in HAVING clause
Which option shows a syntax error in using HAVING clause in MySQL?
Attempts:
2 left
💡 Hint
WHERE cannot filter on aggregate functions.
✗ Incorrect
WHERE filters rows before grouping and cannot use aggregate functions like COUNT(). HAVING filters groups after aggregation.
🧠 Conceptual
advanced2:00remaining
Difference between WHERE and HAVING clauses
Which statement correctly explains the difference between WHERE and HAVING clauses in SQL?
Attempts:
2 left
💡 Hint
Think about when filtering happens in the query process.
✗ Incorrect
WHERE filters individual rows before grouping. HAVING filters groups after aggregation is done.
❓ query_result
advanced2:00remaining
Output of HAVING with multiple conditions
Consider the table orders with columns
customer_id, order_date, and total. What rows will this query return?SELECT customer_id, COUNT(*) AS order_count, SUM(total) AS total_spent
FROM orders
GROUP BY customer_id
HAVING order_count >= 3 AND total_spent < 500;
MySQL
SELECT customer_id, COUNT(*) AS order_count, SUM(total) AS total_spent FROM orders GROUP BY customer_id HAVING order_count >= 3 AND total_spent < 500;
Attempts:
2 left
💡 Hint
HAVING can combine multiple conditions with AND/OR.
✗ Incorrect
The HAVING clause filters groups where order_count is 3 or more AND total_spent is less than 500.
🔧 Debug
expert2:00remaining
Why does this HAVING query return no rows?
Given the table products with columns
category and price, why does this query return no rows?SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category
HAVING avg_price < 0;
MySQL
SELECT category, AVG(price) AS avg_price FROM products GROUP BY category HAVING avg_price < 0;
Attempts:
2 left
💡 Hint
Think about the possible values of average price.
✗ Incorrect
Prices are usually non-negative, so average price less than zero is impossible, resulting in no rows.