Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageMiddleCommonTheory

When would you use a subquery or common table expression instead of another join?

Answer

A subquery can express existence, scalar lookup or set membership, while a common table expression gives a named intermediate result that can make a complex query easier to read and test. A join is often clearer when combining related row sets, but equivalent syntax does not guarantee an identical plan on every database. Verify empty and multi-row cases, NULL behaviour in IN or NOT IN, duplicate amplification, recursive termination and the actual execution plan for performance-sensitive queries.

Strong answer includes

  • chooses syntax for semantics and clarity
  • recognizes NULL and cardinality traps
  • does not assume equivalent syntax has identical performance

Practical example

CTE for a named intermediate result
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
Result
Run the query to see the result.

The CTE isolates the aggregation and gives it a name before it is joined to customer data. This often makes complex logic easier to reason about and test independently than deeply nested subqueries.

Expected result: Customers in the sample database whose paid-order total exceeds 150.

#sql#cte#subquery#joins

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery