LESSON 06 / 24·2 min readFoundation

Subquery vs EXISTS vs CTE?

01 Understand02 Recall03 Prepare

Understand the concept

A subquery supplies a result inside another query, EXISTS checks whether a matching result exists, and a CTE gives a named query expression that can be referenced later. These are ways to structure SQL and express relationships. The optimizer and data determine performance, so syntax alone does not tell you which is fastest.

Important ideas

  • A subquery is a query inside another query.

  • EXISTS checks whether at least one matching row exists.

  • A CTE names a query step; it improves readability but is not automatically faster.

  • Use EXISTS when only existence matters and you do not need columns from every matching child row.

PAUSE & RECALL

Can you explain it without the notes?

Subquery vs EXISTS vs CTE?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

A subquery supplies a result inside another query, EXISTS checks whether a matching result exists, and a CTE gives a named query expression that can be referenced later. These are ways to structure SQL and express relationships. The optimizer and data determine performance, so syntax alone does not tell you which is fastest.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Avoid claiming CTEs always cache results or always improve performance; inspect the database version and plan.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: When should I use a recursive CTE or set operation?

Adapted from 05_SQL_POSTGRESQL.md · “Subquery vs EXISTS vs CTE?”. Examples are study fragments; framework behavior can depend on your version.