On this page
  1. Aggregations, CTEs & Window Functions
  2. Contents
  3. GROUP BY, HAVING & Conditional FILTER
  4. Common Table Expressions (WITH & WITH RECURSIVE)
  5. Window Functions (OVER (PARTITION BY ... ORDER BY ...))

Aggregations, CTEs & Window Functions

Prev: Joins & Set Operations | Up: sql | Next: SQL Query Execution Lifecycle
Rel: SQL Query Execution Lifecycle, PostgreSQL Indexes & EXPLAIN ANALYZE
Ref: PostgreSQL — Window Functions
Tags: #public #databases #sql #cte #window-functions


Contents


GROUP BY, HAVING & Conditional FILTER

WHERE filters rows before grouping; HAVING filters groups after aggregation. Use FILTER (WHERE ...) for clean conditional counts in one pass:

SELECT
  user_id,
  COUNT(*) AS total_orders,
  COUNT(*) FILTER (WHERE total_cents >= 10000) AS large_orders,
  SUM(total_cents) AS spend_cents
FROM orders
GROUP BY user_id
HAVING COUNT(*) >= 2;

Common Table Expressions (WITH & WITH RECURSIVE)

CTEs break complex queries into named readable steps. WITH RECURSIVE traverses trees and graphs (org charts, category hierarchies):

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

Window Functions (OVER (PARTITION BY ... ORDER BY ...))

Unlike GROUP BY, window functions compute running totals, rankings, and neighbor comparisons without collapsing rows:

SELECT
  user_id,
  created_at,
  total_cents,
  ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn,
  SUM(total_cents) OVER (PARTITION BY user_id ORDER BY created_at) AS running_total,
  LAG(total_cents) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_order
FROM orders;

Linked from

Related notes