</>
Skip to content
PostgreSQL lessons (21/38)

PostgreSQL — CTE

Basic CTE

WITH active_users AS (
    SELECT * FROM users WHERE active = true
)
SELECT * FROM active_users;

Multiple CTEs

WITH 
active_users AS (
    SELECT * FROM users WHERE active = true
),
recent_orders AS (
    SELECT * FROM orders WHERE created_at > NOW() - INTERVAL '30 days'
)
SELECT u.name, o.total
FROM active_users u
JOIN recent_orders o ON u.id = o.user_id;

Recursive CTE

WITH RECURSIVE category_tree AS (
    -- Base case
    SELECT id, name, parent_id, 0 as depth
    FROM categories WHERE parent_id IS NULL
    
    UNION ALL
    
    -- Recursive case
    SELECT c.id, c.name, c.parent_id, ct.depth + 1
    FROM categories c
    JOIN category_tree ct ON c.parent_id = ct.id
)
SELECT * FROM category_tree;

CTE Benefits

BenefitDescription
ReadabilityNamed subqueries
ReusabilityUse multiple times
RecursionHierarchical data
PerformanceOptimized execution

Mini Practice

  1. Create a basic CTE
  2. Use multiple CTEs
  3. Create recursive CTE
  4. Query CTE results

Up Next

Continue with Views — creating views.

Related Topics

Frequently Asked Questions about CTE

What is CTE in PostgreSQL?

CTE is a fundamental concept in PostgreSQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn CTE?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn CTE.

Why is CTE important in PostgreSQL?

CTE is essential for PostgreSQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.