Understand the concept
A scalar subquery returns one value, such as an average. EXISTS checks for a match without multiplying the outer row. NOT EXISTS is useful for absence; NOT IN can surprise you when its list contains NULL.
Apply the method
WITH names an intermediate query. Use names describing the grain, such as customer_totals. CTEs improve readability; they do not promise faster execution. The database chooses an execution plan.
Avoid a common mistake
For second highest salary, clarify second row versus second distinct value. Ties change the answer. A correlated maximum can retain ties; LIMIT 1 chooses a single record. State your tie policy.
Worked query
Return name for employees paid above the overall average known salary, ordered by id.
SELECT name FROM employees WHERE salary>(SELECT AVG(salary) FROM employees) ORDER BY id;Run and explore this example →Check your understanding
Before running your query, predict the output columns and approximate row count. After running it, inspect a missing value, a tie and a record with no match when available. Explain why the result answers the question.
Practice this topic
- Above average pay — Return name for employees paid above the overall average known salary, ordered by id.
- Has a paid order — Return name for customers with a paid order, ordered by id. Try EXISTS.
- No paid orders — Return name for customers with no paid orders, ordered by id. Try NOT EXISTS.
- Highest paid per department — Return department and name for highest-paid employees in each department, retaining ties. Order by department,name.
- Revenue CTE — Return customer_id and revenue for paid totals >=180, ordered by customer_id. Try a CTE.
- Above department average — Return name for employees paid above their own department average, ordered by id.
- Largest stock category — Return category and units for highest total stock; alphabetical category breaks ties.
- Second distinct salary — Return second_salary as the second highest distinct non-NULL salary.
- Selected countries — Use UNION to return UK or Pakistan country values, alphabetically without duplicates.
- First order date — Return customer_id and first_order (earliest ordered_at), ordered by customer_id.
SQLite reference: SQL language documentation. Written by Future Data Academy with AI assistance; query examples checked against the supplied teaching dataset.
