Home / Learn Secure SQL / Subqueries

Subqueries

A query inside a query.

Quick summaryA query inside a query.

How to think about this

Nestingouter queryruns inner queryfirst (usually)uses its result
Nesting

What it is

A subquery is a complete SELECT nested inside another query, used in WHERE, FROM, or as a computed column.

Why it matters

Subqueries let you express "users who did X" without a separate round trip from your application code.

Mechanically speaking

Write the inner query first and test it alone, then wrap it inside the outer query.

Shows up in

  • Web application code review
  • Backend development
  • Database administration
Users who have paid ordersSQL: edit and run

The inner SELECT finds the relevant user_ids; the outer SELECT looks them up by name.

Check yourself

1. A subquery is...