On this page
  1. WITH
  2. Syntax & Overview
  3. Notes & Best Practices
  4. Example

WITH

Prev: `LIMIT` | Up: clauses | Next: `INSERT`
Rel: clauses, SQL Query Execution Lifecycle
Ref: PostgreSQL — SQL Commands
Tags: #public #databases #sql #clauses #tier/core


Syntax & Overview

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

Defines named Common Table Expressions (WITH RECURSIVE for trees/graphs).

Notes & Best Practices

Example

WITH active_orders AS (
  SELECT user_id, total FROM orders WHERE status = 'paid'
)
SELECT user_id, SUM(total) AS lifetime_spend
FROM active_orders
GROUP BY user_id;

Linked from

Related notes