Challenge - 5 Problems
Master of GROUP BY multiple columns
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of GROUP BY on two columns
Given the table Sales with columns
region, product, and amount, what is the output of this query?SELECT region, product, SUM(amount) AS total_sales
FROM Sales
GROUP BY region, product
ORDER BY region, product;
SQL
CREATE TABLE Sales (region VARCHAR(10), product VARCHAR(10), amount INT); INSERT INTO Sales VALUES ('East', 'Pen', 10), ('East', 'Pen', 15), ('East', 'Pencil', 5), ('West', 'Pen', 20), ('West', 'Pencil', 10);
Attempts:
2 left
💡 Hint
GROUP BY groups rows that have the same values in all listed columns.
✗ Incorrect
The query groups rows by both region and product. For example, 'East' and 'Pen' rows are summed together (10 + 15 = 25). Other groups are summed similarly.
🧠 Conceptual
intermediate1:30remaining
Understanding GROUP BY multiple columns
Why do we use multiple columns in a GROUP BY clause in SQL?
Attempts:
2 left
💡 Hint
Think about how grouping works with one column, then extend to multiple columns.
✗ Incorrect
Using multiple columns in GROUP BY groups rows that share the same values in all those columns, creating finer groups.
📝 Syntax
advanced1:30remaining
Identify the correct GROUP BY syntax with multiple columns
Which of the following SQL queries correctly groups by two columns
category and year?Attempts:
2 left
💡 Hint
Check the syntax for separating columns in GROUP BY.
✗ Incorrect
Columns in GROUP BY must be separated by commas without parentheses or semicolons.
❓ optimization
advanced2:00remaining
Optimizing GROUP BY with multiple columns
You have a large table with columns
country, city, and sales. Which index would best improve performance of this query?SELECT country, city, SUM(sales) FROM sales_data GROUP BY country, city;
Attempts:
2 left
💡 Hint
Think about how the database groups rows efficiently.
✗ Incorrect
A composite index on the grouped columns helps the database quickly find and group rows by those columns.
🔧 Debug
expert2:30remaining
Why does this GROUP BY query cause an error?
Consider this query:
Why does it cause an error?
SELECT department, employee, COUNT(*) FROM employees GROUP BY department;
Why does it cause an error?
Attempts:
2 left
💡 Hint
Check which columns must appear in GROUP BY or be aggregated.
✗ Incorrect
Columns in SELECT that are not aggregated must appear in GROUP BY. Here, employee is missing from GROUP BY and not aggregated.