GimmeJob
Sign in
Databases, SQL & BI · SQL · Chapter 08 / 17

SQL learning path

CTEs & query decomposition

A Common Table Expression (CTE) gives a name to an intermediate query result for the duration of one statement. CTEs are not automatically “faster”; their primary benefit is clearer structure, and optimizer behavior differs by engine/version.

Basic WITH query

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

Multiple CTEs as a pipeline

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

Each step should have a meaningful name and a clear grain.

CTE versus subquery

A CTE and an inline subquery can express the same relational logic. Prefer the form that makes the query easier to verify. For a multi-stage QA reconciliation, named stages such as normalized_expected, normalized_actual, and differences can dramatically improve reviewability.

Recursive CTE concept

Recursive CTEs repeatedly apply a query until no new rows are produced. They are used for trees, graphs, hierarchical paths, sequence generation, and dependency traversal. They need an anchor term, a recursive term, and a termination condition.

A recursive query is powerful enough to create runaway work if the termination rule is wrong, so test it on bounded data first.

CTE performance caution

Do not assume that extracting logic into a CTE improves execution speed. PostgreSQL can inline or materialize CTEs depending on the query and version; other engines have different rules. Read the execution plan when performance matters.

Practice: build a CTE containing only QA employees, then query it for the highest score and average salary.

Source registry

2 chapter references · Under review
PostgreSQL 18 — Queries

Detailed reference for FROM/WHERE/GROUP BY/HAVING, set operations, sorting, LIMIT/OFFSET, CTEs, recursive queries, and query processing.

PostgreSQL Global Development Group · official documentation
Source ↗
SQLite — SELECT

Runtime-aligned reference for SELECT grammar and behavior in the in-browser SQLite practice environment.

SQLite · official documentation
Source ↗