Subqueries & CTEs

Queries inside queries: scalar and correlated subqueries, IN and EXISTS, derived tables, WITH clauses, and recursive CTEs for trees and graphs.

Overview

A subquery is a SELECT written inside another statement. It lets you compute something first, such as an average or a list of ids, and then use it in the outer query. A CTE (common table expression) is the same idea with a name: WITH name AS (SELECT ...) defines a result you can read like a table in the query that follows.

Interviewers use these to test two things: whether you can break a question into steps, and whether you know the traps, above all NOT IN with a NULL and recursion that never ends.

The sample table

The table has six employees in two departments. manager_id points to another row, so the table also holds a small org chart. All the SQL on this page runs on PostgreSQL.

Drawn as a tree, the rows look like this. Keep the picture in mind: the recursive queries near the end of the page walk it.

Interview questions

  • What is the difference between a correlated and an uncorrelated subquery?
  • When would you use a CTE instead of a subquery?
  • How do you query a hierarchy of unknown depth?

Sign up free to read the full topic

More Databases & SQL topics

Start free on Cariara · Coding problems · System design studio