Learn SQL/Advanced/CTEs/SQL CTEs and WITH Clause

SQL CTEs and WITH Clause

A named, temporary result set that makes a query readable top to bottom instead of inside out.

What & Why

A Common Table Expression (CTE) is a named query you define with WITH, then reference later in the same statement as if it were a real table. It exists only for the duration of that one query.

The problem it solves: nested subqueries force you to read from the inside out. A CTE lets you name each step and read the whole query top to bottom, like a short paragraph.

See How It Works

BUSINESS QUESTION

Build monthly feedback counts first, then present them in calendar order.

iduser_idfeature_idratingnps_scorecommentcreated_at
1101159Clear and useful2024-01-25 12:15:00+00
210224NULLExport worked well2024-02-20 15:40:00+00
3103147Helpful setup flow2024-03-18 09:05:00+00
410433NULLNeeds clearer timing2024-04-08 17:30:00+00
EXAMPLE QUERY
WITH monthly_feedback AS (
  SELECT
    DATE_TRUNC('month', created_at)::date AS month_start,
    COUNT(*) AS feedback_count
  FROM product.feedback
  GROUP BY 1
)
SELECT
  month_start,
  feedback_count
FROM monthly_feedback
ORDER BY month_start;
RESULT — monthly feedback counts
month_startfeedback_count
2024-01-011
2024-02-011
2024-03-011
2024-04-011

The CTE groups the four representative feedback rows before the final ordered SELECT.

Advanced business practice

Sign up free to try it on a real business scenario