Challenge - 5 Problems
CTE Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of CTE vs Subquery for Average Salary
Given the table employees with columns
id, department, and salary, what is the output of the following query using a CTE that calculates the average salary per department and then selects departments with average salary above 5000?SQL
WITH dept_avg AS ( SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department ) SELECT department FROM dept_avg WHERE avg_salary > 5000 ORDER BY department;
Attempts:
2 left
💡 Hint
Think about what the CTE calculates first and what the main query filters.
✗ Incorrect
The CTE calculates the average salary per department. The main query selects departments where this average is greater than 5000. The result is a list of department names sorted alphabetically.
📝 Syntax
intermediate2:00remaining
Identify the Syntax Error in CTE Usage
Which option contains a syntax error in the use of a CTE?
SQL
WITH dept_count AS ( SELECT department, COUNT(*) AS emp_count FROM employees GROUP BY department ) SELECT * FROM dept_count WHERE emp_count > 10;
Attempts:
2 left
💡 Hint
Check the parentheses around the CTE definition.
✗ Incorrect
Option C is missing parentheses around the CTE query, which is required syntax for CTEs.
❓ optimization
advanced2:00remaining
Optimizing Query with CTE vs Subquery
Consider a query that calculates total sales per region and then filters regions with sales above 10000. Which option shows the best use of a CTE to improve readability and avoid repeating the aggregation?
Attempts:
2 left
💡 Hint
Look for correct CTE syntax and clear separation of steps.
✗ Incorrect
Option D uses a CTE to calculate total sales per region once, then filters on that result, improving readability and avoiding repetition.
🔧 Debug
advanced2:00remaining
Debugging Incorrect CTE Result
A developer wrote this query to find departments with more than 5 employees, but it returns no rows. What is the likely cause?
SQL
WITH dept_emps AS ( SELECT department, COUNT(employee_id) AS emp_count FROM employees ) SELECT department FROM dept_emps WHERE emp_count > 5;
Attempts:
2 left
💡 Hint
Check if aggregation is grouped properly.
✗ Incorrect
Without GROUP BY, COUNT(employee_id) returns total count for all rows, so emp_count is a single value and filtering by >5 returns no rows per department.
🧠 Conceptual
expert2:00remaining
Why Use CTE Instead of Subquery?
Which of the following is the best explanation for why using a CTE can be better than a subquery in complex SQL queries?
Attempts:
2 left
💡 Hint
Think about how CTEs help organize complex queries.
✗ Incorrect
CTEs make queries easier to read and maintain by breaking them into named parts and can be reused multiple times in the main query. They do not guarantee performance improvements or allow data modification.