100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Database

Common Table Expressions

Learn how PostgreSQL's WITH clause structures complex queries into named, readable building blocks, including recursive CTEs for hierarchical data.

Query PlanningIntermediate8 min readJul 10, 2026
Analogies

What a CTE Is and Why It Helps Readability

A Common Table Expression, introduced with the WITH keyword, lets you name an intermediate result set and reference it later in the same statement as if it were a table, letting you break a deeply nested subquery into a sequence of clearly named steps. Since PostgreSQL 12, non-recursive CTEs are inlined into the outer query by default (the planner can 'flatten' them like a subquery) unless they are referenced multiple times, marked MATERIALIZED, or are recursive, so modern CTEs generally do not carry the fixed optimization-fence penalty older PostgreSQL versions had.

🏏

Cricket analogy: Naming a specific fielding formation 'attacking cordon' and referring back to it in team talks throughout the match, rather than re-describing all five slip positions every time, is what a CTE does for a repeated subquery expression.

MATERIALIZED and NOT MATERIALIZED

Since PostgreSQL 12, you can override the default inlining behavior explicitly: WITH cte AS MATERIALIZED (...) forces the CTE to be computed once and stored, acting as an optimization fence just like pre-12 CTEs always did, which is useful when the CTE is expensive and referenced multiple times, or when it deliberately isolates a side-effecting data-modifying statement (INSERT/UPDATE/DELETE ... RETURNING) inside the WITH clause. WITH cte AS NOT MATERIALIZED forces inlining even in cases the planner might otherwise choose to materialize, useful when you know the CTE is cheap and want the outer query's WHERE clauses pushed down into it for a better plan.

🏏

Cricket analogy: Deciding to pre-record a specific fielding drill on video (MATERIALIZED) because the whole squad will rewatch it many times, versus just calling out instructions live each time (NOT MATERIALIZED) because it's a one-off tweak, mirrors the CTE materialization choice.

Recursive CTEs for Hierarchical Data

WITH RECURSIVE defines a CTE with two parts unioned together: a non-recursive base case that seeds the initial rows, and a recursive term that references the CTE's own name and is repeatedly evaluated against the previous iteration's output until it returns no new rows, making it the standard PostgreSQL tool for traversing trees such as an employee-manager hierarchy, a bill-of-materials, or a category tree. Because the recursive term must terminate, cyclic data (e.g. a manager accidentally reporting to their own subordinate) can cause an infinite loop, which is why production recursive CTEs typically track a visited-nodes array and add a WHERE NOT (id = ANY(path)) guard or a UNION (not UNION ALL) to deduplicate and break cycles.

🏏

Cricket analogy: Tracing a bowling lineage, a fast bowler who was mentored by a former pacer who was in turn mentored by another, iteration by iteration until you hit the founding mentor with no predecessor, mirrors how a recursive CTE walks up an employee-manager hierarchy.

sql
-- Simple readability CTE, inlined by the planner (PG 12+) since referenced once
WITH recent_orders AS (
  SELECT customer_id, total_amount
  FROM orders
  WHERE order_date >= CURRENT_DATE - INTERVAL '30 days'
)
SELECT customer_id, SUM(total_amount) AS total_spent
FROM recent_orders
GROUP BY customer_id
ORDER BY total_spent DESC;

-- Recursive CTE walking an employee-manager hierarchy, with a cycle guard
WITH RECURSIVE org_chain AS (
  SELECT employee_id, manager_id, full_name, 1 AS depth,
         ARRAY[employee_id] AS path
  FROM employees
  WHERE employee_id = 42  -- start from a specific employee

  UNION ALL

  SELECT e.employee_id, e.manager_id, e.full_name, oc.depth + 1,
         oc.path || e.employee_id
  FROM employees e
  JOIN org_chain oc ON e.employee_id = oc.manager_id
  WHERE NOT (e.employee_id = ANY(oc.path))  -- guard against cycles
)
SELECT depth, full_name FROM org_chain ORDER BY depth;

-- Isolating a data-modifying statement inside a CTE
WITH archived AS MATERIALIZED (
  DELETE FROM sessions WHERE expires_at < now()
  RETURNING session_id, user_id
)
INSERT INTO session_audit_log (session_id, user_id, archived_at)
SELECT session_id, user_id, now() FROM archived;

You can force a CTE to break the automatic inlining optimization by writing WITH cte AS MATERIALIZED (...). This is still commonly needed when a data-modifying CTE (INSERT/UPDATE/DELETE ... RETURNING) must run exactly once regardless of how the outer query references it.

CTEs vs. Subqueries vs. Views

A CTE, a subquery, and a view can all express the same logical computation, but they differ in scope and reusability: a subquery is inline and single-use within one statement, a CTE is named and can be referenced multiple times within one statement (and, since PG 12, is planned essentially like a smart subquery), and a view is a stored, named query reusable across many statements and sessions but with no per-statement materialization control. The main reasons to reach for a CTE over a plain subquery are readability for a multi-step pipeline and the ability to define recursive logic, which subqueries cannot express at all.

🏏

Cricket analogy: A one-off improvised field placement called out for a single ball is like a subquery; a named formation referenced repeatedly through one innings is like a CTE; and a standard fielding template written into the team's permanent playbook for every match is like a view.

A recursive CTE without a cycle guard on genuinely cyclic data (self-referencing foreign keys that form a loop) will run forever, consuming memory until it errors out or exhausts disk for its work files. Always add a visited-path array and a WHERE NOT (id = ANY(path)) style guard, or use the SQL standard CYCLE clause available since PostgreSQL 14, when the source data cannot guarantee acyclicity.

  • A CTE, introduced with WITH, names an intermediate result for readability and optional reuse within one statement.
  • Since PostgreSQL 12, non-recursive CTEs are inlined by default rather than always acting as an optimization fence.
  • WITH ... AS MATERIALIZED forces single computation and storage; NOT MATERIALIZED forces inlining even when the planner might otherwise materialize.
  • WITH RECURSIVE combines a base case and a recursive term, repeatedly evaluated until no new rows appear, for hierarchical traversal.
  • Recursive CTEs on cyclic data need an explicit guard (visited-path array or the PG14+ CYCLE clause) to avoid infinite loops.
  • CTEs uniquely support recursion and multi-step readability that plain subqueries cannot express.
  • Data-modifying statements (INSERT/UPDATE/DELETE RETURNING) can be embedded in a CTE, typically as MATERIALIZED, to guarantee single execution.

Practice what you learned

Was this page helpful?

Topics covered

#Database#PostgreSQLAdvancedStudyNotes#CommonTableExpressions#Common#Table#Expressions#CTE#SQL#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse