Skip to content
Learn Netverks

Lesson

Step 22/36 61% through track

subqueries

Subqueries

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~2 min
Level
intermediate

This lesson

This lesson teaches Subqueries: the SQL patterns, schema habits, and query reasoning you need before advancing in SQL.

Subqueries vs JOINs trade readability for performance—correlated subqueries can be expensive at scale.

You will apply Subqueries in contexts like: Postgres, MySQL, SQLite, warehouses, and ORMs that still expose SQL.

Copy SQL from each lesson into SQLite (sqlite3), DB Fiddle, or local Postgres—read result grids and row counts. The in-browser SQL lab (sql_sandbox) will run queries when the runner ships; until then, local clients are the practice path.

When you can explain the previous lesson's ideas without copying example queries verbatim.

A subquery nests SELECT inside another statement—in WHERE, FROM, or SELECT list. They express multi-step logic; CTEs (next module) often improve readability of the same logic.

Subquery in WHERE

SELECT name, email
FROM customers
WHERE id IN (
  SELECT customer_id
  FROM orders
  WHERE total > 100
);

Practice: Seed customers and orders sample data, then run each query. Verify row counts manually.

Scalar subquery

SELECT c.name,
       (SELECT COUNT(*)
        FROM orders o
        WHERE o.customer_id = c.id) AS order_count
FROM customers c;

Correlated subqueries reference outer rows—powerful but can be slow; JOIN + GROUP BY is often faster.

EXISTS

SELECT c.name
FROM customers c
WHERE EXISTS (
  SELECT 1
  FROM orders o
  WHERE o.customer_id = c.id
);

EXISTS stops at first match—efficient for “has related rows” checks.

Important interview questions and answers

  1. Q: IN vs EXISTS?
    A: Semantically similar for many cases; EXISTS often better when subquery is large and you only need presence.
  2. Q: Subquery in FROM?
    A: Derived table / inline view—must have alias in most engines.

Self-check

  1. Which operator tests for related rows without returning data?
  2. When might JOIN beat correlated subquery?

Tip: If a correlated subquery feels slow, try JOIN + GROUP BY or a CTE.

Interview prep

EXISTS vs IN?

EXISTS stops at first match; often efficient for presence checks.

Correlated subquery?

Inner query references outer row—can be expensive.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Correlated cost?
  • EXISTS vs IN?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump