Challenge - 5 Problems
GROUP BY Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of GROUP BY with aggregate function
Given the table Sales with columns
product and quantity, what is the output of this query?SELECT product, SUM(quantity) FROM Sales GROUP BY product;
MySQL
CREATE TABLE Sales (product VARCHAR(20), quantity INT); INSERT INTO Sales VALUES ('apple', 10), ('banana', 5), ('apple', 15), ('banana', 10), ('orange', 7);
Attempts:
2 left
💡 Hint
GROUP BY groups rows by product and SUM adds quantities per group.
✗ Incorrect
The query groups rows by product and sums the quantity for each product. Apple has 10+15=25, banana 5+10=15, orange 7.
🧠 Conceptual
intermediate1:30remaining
Understanding GROUP BY with multiple columns
Consider a table Orders with columns
customer_id, product, and quantity. What does this query do?SELECT customer_id, product, COUNT(*) FROM Orders GROUP BY customer_id, product;
Attempts:
2 left
💡 Hint
GROUP BY with two columns groups rows by unique pairs of those columns.
✗ Incorrect
The query groups rows by both customer_id and product, so it counts how many orders each customer made for each product separately.
📝 Syntax
advanced1:30remaining
Identify the syntax error in GROUP BY usage
Which option contains a syntax error in the GROUP BY clause?
SELECT department, AVG(salary) FROM Employees GROUP BY;
Attempts:
2 left
💡 Hint
GROUP BY must specify at least one column to group by.
✗ Incorrect
Option B has GROUP BY with no columns, which is a syntax error. GROUP BY requires at least one column name.
❓ optimization
advanced2:00remaining
Optimizing GROUP BY with indexes
Which index will best improve performance of this query?
SELECT city, COUNT(*) FROM Customers GROUP BY city;
Attempts:
2 left
💡 Hint
Indexes on columns used in GROUP BY help speed grouping.
✗ Incorrect
An index on city helps the database quickly group rows by city. Indexes on other columns do not help this query.
🔧 Debug
expert2:30remaining
Why does this GROUP BY query fail?
Given the table Employees with columns
id, department, and salary, why does this query cause an error?SELECT id, department, AVG(salary) FROM Employees GROUP BY department;
Attempts:
2 left
💡 Hint
Columns in SELECT must be in GROUP BY or aggregated.
✗ Incorrect
The query selects id which is neither aggregated nor in GROUP BY, causing an error in MySQL strict mode.