Module P-1·20 min read

CTEs, window functions, upserts, subqueries, UNION — the SQL that separates proficient engineers from beginners.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

P-1 — Advanced SQL: The Patterns You Will Use Every Week

Who this module is for: You completed Phase 1 and can write fundamental SQL. Phase 2 assumes you are building real applications and need the SQL patterns that separate engineers who can write queries from engineers who can write good queries. This module covers the constructs that appear in almost every production PostgreSQL codebase.


Common Table Expressions (CTEs) — WITH Clauses

A CTE creates a named, temporary result set within a query. It makes complex queries readable by breaking them into named steps.

sql

Chaining Multiple CTEs

sql

Since PostgreSQL 12, a non-recursive CTE referenced exactly once (with no side effects) is inlined by the planner — treated like a subquery, subject to predicate pushdown and join reordering, not run as a separate fenced step. Every CTE above is referenced once, so on PG12+ they're inlined. A CTE only materializes — executes once, result cached, opaque to the planner — when it's referenced more than once, or when you force it with AS MATERIALIZED. You can force inlining the other way with AS NOT MATERIALIZED, even on a multiply-referenced CTE.

Recursive CTEs — Traversing Hierarchies

Recursive CTEs can traverse tree structures (org charts, categories with subcategories, file systems):

sql

Window Functions — Computation Without Collapsing Rows

Aggregate functions collapse many rows into one. Window functions compute across a set of rows but keep every row in the output.

sql

The OVER() Clause

OVER() defines the "window" — the set of rows each calculation sees:

sql

Essential Window Functions

Ranking:

sql
DifferenceWhen there is a tie
ROW_NUMBER()Assigns unique numbers (arbitrary tie-breaking)
RANK()Tied rows get same rank; next rank skips numbers (1,1,3)
DENSE_RANK()Tied rows get same rank; next rank does not skip (1,1,2)

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.