Challenge - 5 Problems
Subquery Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate2:00remaining
Understanding the purpose of subqueries
What is the main purpose of using a subquery in an SQL statement?
Attempts:
2 left
💡 Hint
Think about how one query can depend on the result of another.
✗ Incorrect
A subquery is a query nested inside another query. It helps to filter or calculate values based on the results of the inner query.
📋 Factual
intermediate2:00remaining
Identifying valid subquery placement
Which of the following SQL clauses can contain a subquery?
Attempts:
2 left
💡 Hint
Subqueries are often used to filter rows or generate data sets.
✗ Incorrect
Subqueries can be used in WHERE to filter rows, in FROM to create temporary tables, and in SELECT to compute values.
🚀 Application
advanced2:00remaining
Output of nested subquery with aggregation
What will be the output of this query?
SELECT employee_id FROM employees WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = 10);
Attempts:
2 left
💡 Hint
Look at the subquery filtering by department_id = 10 and calculating average salary.
✗ Incorrect
The subquery calculates the average salary for department 10. The outer query selects employees whose salary is greater than this average.
🔍 Analysis
advanced2:00remaining
Analyzing error in correlated subquery
Consider this query:
What error or issue will this query produce?
SELECT e1.employee_id FROM employees e1 WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e1.department_id = e2.department_id);
What error or issue will this query produce?
Attempts:
2 left
💡 Hint
Check if the subquery is correlated properly and returns a single value per outer row.
✗ Incorrect
This is a correlated subquery comparing each employee's salary to the average salary of their department. It runs correctly and returns expected results.
❓ Reasoning
expert2:00remaining
Determining the number of rows returned by nested queries
Given two tables:
What is the number of rows returned by this query?
- departments(department_id, department_name)
- employees(employee_id, department_id, salary)
What is the number of rows returned by this query?
SELECT department_id FROM departments WHERE department_id IN (SELECT department_id FROM employees WHERE salary > 50000);
Attempts:
2 left
💡 Hint
The subquery finds departments with employees earning more than 50000; the outer query filters departments accordingly.
✗ Incorrect
The subquery returns department IDs where employees earn more than 50000. The outer query returns those departments only, so the count equals departments with such employees.