SQL subquery

A subquery is a query inside another query, wrapped in parentheses. It can return a single value (compare against it), a list (use with IN) or a whole table (use in FROM).

A correlated subquery refers to the outer query, so it runs once per outer row. It answers questions like "employees who earn more than their department's average".

Syntax

SELECT ... WHERE col > (SELECT AVG(col) FROM t);
SELECT ... FROM (SELECT ...) AS sub;

Try it yourself

Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.

subquery.sql · PostgreSQL
Loading editor…

Examples

1. Scalar subquery

SELECT name, price FROM products WHERE price > (SELECT AVG(price) FROM products);

Above-average products.

2. Derived table

SELECT ROUND(AVG(n), 2) FROM (SELECT order_id, COUNT(*) AS n FROM order_items GROUP BY order_id) t;

A subquery in FROM needs an alias.

3. Correlated

SELECT first_name, salary FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees x WHERE x.department_id = e.department_id);

Compares each row with its own group.

Common mistakes

  • A scalar subquery that returns more than one row ("more than one row returned by a subquery").
  • Forgetting the alias on a derived table.

Practice: test yourself

This challenge is from our interactive course. Write the query and press Check answer.

Challenge · 30 pts

Return first_name, last_name and salary of employees who earn more than the average salary of their own department.

challenge.sql · PostgreSQL
Loading editor…

FAQ

Subquery or JOIN?

Use whatever reads more clearly. For complex logic, a CTE (WITH) is often the clearest of all.

Learn SQL step by step

65 hands-on exercises, streaks, a leaderboard and a certificate.

Start free →