Free courses in AI, Data Science & Machine Learning Written lessons · Quizzes · Final exams
Future Data Academy
Log inGet started ↗
← SQL learning path
Intermediate · SQLITE

Subqueries and CTEs

Break reasoning into named steps.

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

  1. Above average pay — Return name for employees paid above the overall average known salary, ordered by id.
  2. Has a paid order — Return name for customers with a paid order, ordered by id. Try EXISTS.
  3. No paid orders — Return name for customers with no paid orders, ordered by id. Try NOT EXISTS.
  4. Highest paid per department — Return department and name for highest-paid employees in each department, retaining ties. Order by department,name.
  5. Revenue CTE — Return customer_id and revenue for paid totals >=180, ordered by customer_id. Try a CTE.
  6. Above department average — Return name for employees paid above their own department average, ordered by id.
  7. Largest stock category — Return category and units for highest total stock; alphabetical category breaks ties.
  8. Second distinct salary — Return second_salary as the second highest distinct non-NULL salary.
  9. Selected countries — Use UNION to return UK or Pakistan country values, alphabetically without duplicates.
  10. 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.