Skip to content

Subquery

Medium — good to knowDatabase

ELI5 — The Vibe Check

A subquery is a query inside a query. The inner query runs first and its result is used by the outer query. It is like asking 'give me all users whose ID appears in (give me all user IDs who ordered something last week)'.

Real Talk

A subquery is a SELECT statement nested inside another SQL statement. It can appear in the WHERE clause (to filter based on another query's results), the FROM clause (as a derived table), or the SELECT clause (as a scalar subquery). Correlated subqueries reference the outer query and execute once per outer row.

Show Me The Code

-- Users who have placed at least one order
SELECT name FROM users
WHERE id IN (
  SELECT DISTINCT user_id FROM orders
);

When You'll Hear This

"Use a subquery to filter based on aggregate results." / "Subqueries can often be rewritten as JOINs for better performance."

Made with passive-aggressive love by manoga.digital. Powered by Claude.