Challenge - 5 Problems
Derived Table Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of a derived table with aggregation
Given the table sales with columns
region, product, and amount, what is the output of this query?SELECT region, total_sales FROM (SELECT region, SUM(amount) AS total_sales FROM sales GROUP BY region) AS region_totals ORDER BY total_sales DESC;
SQL
CREATE TABLE sales (region VARCHAR(10), product VARCHAR(10), amount INT); INSERT INTO sales VALUES ('North', 'A', 100), ('South', 'B', 200), ('North', 'B', 150), ('East', 'A', 50), ('South', 'A', 100);
Attempts:
2 left
💡 Hint
Look at how the SUM aggregates amounts per region and then the outer query orders by total_sales descending.
✗ Incorrect
The inner query sums amounts grouped by region. South has 200+100=300, North has 100+150=250, East has 50. The outer query orders by total_sales descending, so South first, then North, then East.
📝 Syntax
intermediate1:30remaining
Identify the syntax error in derived table usage
Which option contains a syntax error in using a subquery in the FROM clause?
Attempts:
2 left
💡 Hint
Check the alias syntax after the subquery in the FROM clause.
✗ Incorrect
Option C has 'AS;' without an alias name, which is a syntax error. The alias must have a name after AS.
❓ optimization
advanced2:00remaining
Optimizing a query with a derived table
Consider this query:
Which option is the most efficient way to write this query without changing the output?
SELECT d.region, d.avg_amount FROM (SELECT region, AVG(amount) AS avg_amount FROM sales GROUP BY region) d WHERE d.avg_amount > 100;
Which option is the most efficient way to write this query without changing the output?
Attempts:
2 left
💡 Hint
Try to use aggregation filtering directly without a derived table.
✗ Incorrect
Option A uses HAVING to filter groups after aggregation, which is more efficient than filtering in an outer query on a derived table.
🔧 Debug
advanced1:30remaining
Debugging incorrect column reference in derived table
Given the query:
What error will this query produce?
SELECT dt.region, dt.total_sales FROM (SELECT region, SUM(amount) AS total FROM sales GROUP BY region) dt WHERE total_sales > 100;
What error will this query produce?
Attempts:
2 left
💡 Hint
Check the alias names used inside and outside the derived table.
✗ Incorrect
Inside the derived table, the sum is aliased as 'total', but the outer query references 'total_sales', which does not exist.
🧠 Conceptual
expert1:30remaining
Understanding scope and naming in derived tables
Why is it necessary to provide an alias name for a subquery used in the FROM clause?
Attempts:
2 left
💡 Hint
Think about how the outer query accesses the results of the subquery.
✗ Incorrect
The alias acts like a temporary table name so the outer query can refer to the columns of the derived table.