Skip to content
We areTOP 1%
DBMS & SQL · Intermediate · Topic 3 of 4

SQL: Subqueries & CTEs

5 questions.
Your progress0%
1st Visit
0/5
2nd Visit
0/5
Revise
0/5

Overview

A subquery is a query inside another query. It can return one value, used in a comparison such as salary > (SELECT AVG(salary) ...), a list of values, used with IN or EXISTS, or a whole table in the FROM clause. A common table expression (CTE), written with WITH name AS (...), gives an intermediate result a name so that a multi-step query reads from top to bottom. Use these tools when a question needs a value computed from the data itself, such as "above the average", "the second highest" or "customers who never ordered". CTEs are available in MySQL 8.0 and later, PostgreSQL and SQL Server.

WITH dept_avg AS (
  SELECT dept, AVG(salary) AS avg_sal
  FROM employees
  GROUP BY dept
)
SELECT e.name
FROM employees e
JOIN dept_avg d ON d.dept = e.dept
WHERE e.salary > d.avg_sal;

Questions

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account