Skip to content
Learn Netverks

Lesson

Step 22/36 61% through track

ctes-postgresql

Common Table Expressions (CTEs)

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~2 min
Level
intermediate

This lesson

This lesson teaches Common Table Expressions (CTEs): the SQL patterns, schema habits, and query reasoning you need before advancing in PostgreSQL.

Teams query Common Table Expressions (CTEs) on every PostgreSQL codebase—skipping it leaves gaps in debugging and data reviews.

You will apply Common Table Expressions (CTEs) in contexts like: Modern startups, geospatial apps, and analytics-friendly OLTP systems.

Copy Postgres SQL into psql, local PostgreSQL, or DB Fiddle (PostgreSQL dialect)—use \d and EXPLAIN ANALYZE where lessons show them. The in-browser lab ships later; psql is the practice path now.

When you can explain the previous lesson's ideas without copying example queries verbatim.

WITH clauses name intermediate result sets—readable multi-step SQL and recursive trees/graphs.

Non-recursive CTE

WITH big_orders AS (
  SELECT * FROM orders WHERE total > 500
)
SELECT c.name, b.total
FROM big_orders b
JOIN customers c ON c.id = b.customer_id;

Practice: Seed customers/orders tables from earlier lessons, then run queries in psql or DB Fiddle (PostgreSQL).

Recursive CTE

WITH RECURSIVE subordinates AS (
  SELECT id, name, manager_id FROM employees WHERE id = 1
  UNION ALL
  SELECT e.id, e.name, e.manager_id
  FROM employees e
  JOIN subordinates s ON e.manager_id = s.id
)
SELECT * FROM subordinates;

Always include a termination condition—runaway recursion exhausts resources.

CTE materialization note

Postgres may inline or materialize CTEs depending on version and settings—use EXPLAIN to verify performance on hot paths.

Important interview questions and answers

  1. Q: CTE vs subquery?
    A: CTEs improve readability; optimizer may treat similarly—profile hot queries.
  2. Q: Recursive CTE parts?
    A: Anchor member UNION ALL recursive member referencing the CTE name.

Self-check

  1. What keyword starts a recursive CTE?
  2. Why name intermediate steps with WITH?

Tip: Name steps in WITH clauses—readability wins in interviews and code review.

Interview prep

Recursive CTE?

Anchor UNION ALL recursive member for trees/graphs.

WITH benefit?

Readable named intermediate results.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • MATERIALIZED CTE?
  • Recursive limit?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump