Databases sql Beginner

Common Table Expression Patterns

Practical CTE examples: recursive hierarchy, deduplication, and windowed aggregates.

sql
-- Deduplication
WITH ranked AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY created_at DESC) AS rn
  FROM users
)
SELECT * FROM ranked WHERE rn = 1;

-- Recursive tree
WITH RECURSIVE tree AS (
  SELECT id, name, 0 AS depth FROM categories WHERE parent_id IS NULL
  UNION ALL
  SELECT c.id, c.name, t.depth+1 FROM categories c JOIN tree t ON c.parent_id = t.id
)
SELECT * FROM tree ORDER BY depth;

Prerequisites

  • PostgreSQL >= 12 or MySQL >= 8

Pro Tips

  • → Add MATERIALIZED hint in Postgres for large CTEs.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
sql
Level
Beginner
Read time
4 min
Published
Mar 2025
License
Commercial License

Newsletter

New modules every week, directly to your inbox.