← All notes

PostgreSQL CTEs (WITH queries)

Short answer

WITH names a subquery you can reuse in one larger statement. Think of it as a temporary table that lives for that query only. [S1]

Sketch

WITH recent AS (
  SELECT * FROM orders WHERE created_at > now() - interval '7 days'
)
SELECT customer_id, count(*) FROM recent GROUP BY 1;

Points

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).

Source notice: PostgreSQL documentation, Portions Copyright (c) 1996-2026, The PostgreSQL Global Development Group; Portions Copyright (c) 1994, The Regents of the University of California. Used under the PostgreSQL License (https://www.postgresql.org/about/licence/).

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: PostgreSQL Global Development Group, PostgreSQL docs 7.8: WITH Queries (Common Table Expressions), PostgreSQL License; PostgreSQL Global Development Group, SELECT, PostgreSQL License.

Cite this

Permanent ID: iil:note:pk94xdd6

iinventedlight. 2026. "PostgreSQL WITH queries (CTEs) and recursive queries." iinventedlight Library, iil:note:pk94xdd6, version of 2026-11-04. https://iinventedlight.com/library/notes/postgres-ctes-with-queries/. License: CC-BY-4.0.

@misc{iil_note_pk94xdd6,
  author = {{iinventedlight}},
  title = {{PostgreSQL WITH queries (CTEs) and recursive queries}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-04},
  url = {https://iinventedlight.com/library/notes/postgres-ctes-with-queries/},
  note = {Permanent ID iil:note:pk94xdd6. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.

For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/postgres-ctes-with-queries.md.