LQ
SQL Reference
Practice →
SQL ReferenceAdvanced QueriesSubqueries

Subqueries

Use a query inside another query.

Questions this answers
  • How do I filter by the result of another query?
  • How do I find rows above the average?
  • How do I use a query as a derived table?
  • How do I check if a value exists in another table?

How it works

A subquery is a SELECT statement nested inside another. It can appear in WHERE (to filter), FROM (as a derived table), or SELECT (as a scalar value). Subqueries look complex but they're just queries inside queries — each one is solved independently.

Subquery in WHERE

-- Artists with above-average listeners
SELECT name, monthly_listeners
FROM artists
WHERE monthly_listeners > (
  SELECT AVG(monthly_listeners) FROM artists
);

Subquery with IN

-- Orders from customers in New York
SELECT * FROM orders
WHERE customer_id IN (
  SELECT id FROM customers WHERE city = 'New York'
);

Derived table in FROM

SELECT genre, avg_listeners
FROM (
  SELECT genre, AVG(monthly_listeners) AS avg_listeners
  FROM artists
  GROUP BY genre
) AS genre_stats
WHERE avg_listeners > 5000000;
💡 The subquery in FROM must be aliased (AS genre_stats here).

Ready to practise Subqueries?

Solve real exercises with AI feedback — free to start.

Try it free →