Chapter 03

Querying in depth

The features in this chapter replace a surprising amount of application code. Every one of them runs where the data already is, which is almost always faster than moving rows into Java to loop over them.

⏱ 18 min readLevel: intermediate

Filtered aggregates

one pass, several answers
SELECT c.full_name,
       count(*)                                        AS total_orders,
       count(*) FILTER (WHERE o.status = 'CANCELLED')   AS cancelled,
       count(*) FILTER (WHERE o.placed_at > now() - interval '30 days') AS recent,
       sum(o.total_amount) FILTER (WHERE o.status = 'PAID') AS paid_value,
       round(avg(o.total_amount), 2)                   AS avg_value
FROM   customer c
JOIN   customer_order o USING (customer_id)
GROUP  BY c.customer_id, c.full_name
HAVING count(*) > 5
ORDER  BY paid_value DESC NULLS LAST;

FILTER is cleaner than sum(CASE WHEN … THEN 1 ELSE 0 END) and lets the planner do a single scan instead of one subquery per metric.

Window functions

aggregate without collapsing rows
SELECT o.reference,
       o.customer_id,
       o.total_amount,
       o.placed_at,

       -- position within the customer's history
       row_number() OVER w                                AS nth_order,
       lag(o.total_amount)  OVER w                        AS previous_amount,
       o.total_amount - lag(o.total_amount) OVER w        AS delta,

       -- running total per customer
       sum(o.total_amount)  OVER (PARTITION BY o.customer_id
                                  ORDER BY o.placed_at
                                  ROWS UNBOUNDED PRECEDING) AS lifetime_value,

       -- ranking across the whole result
       rank()       OVER (ORDER BY o.total_amount DESC)   AS value_rank,
       percent_rank() OVER (ORDER BY o.total_amount)      AS percentile
FROM   customer_order o
WHERE  o.status = 'PAID'
WINDOW w AS (PARTITION BY o.customer_id ORDER BY o.placed_at);
"Top N per group" — the canonical use
SELECT * FROM (
  SELECT o.*,
         row_number() OVER (PARTITION BY customer_id
                            ORDER BY placed_at DESC) AS rn
  FROM customer_order o
) ranked
WHERE rn <= 3;   -- three most recent orders per customer

CTEs and recursion

readable pipelines
WITH monthly AS (
  SELECT date_trunc('month', placed_at) AS month,
         sum(total_amount)              AS revenue
  FROM   customer_order
  WHERE  status IN ('PAID','FULFILLED','DELIVERED')
  GROUP  BY 1
),
with_growth AS (
  SELECT month,
         revenue,
         lag(revenue) OVER (ORDER BY month) AS previous
  FROM   monthly
)
SELECT month,
       revenue,
       round(100.0 * (revenue - previous) / nullif(previous, 0), 1) AS growth_pct
FROM   with_growth
ORDER  BY month DESC;
CTEs are no longer optimisation fences — mostly

Before PostgreSQL 12 every CTE was materialised, which sometimes destroyed performance. Now they are inlined when safe. You can force either behaviour with WITH x AS MATERIALIZED (…) or AS NOT MATERIALIZED.

LATERAL joins

a correlated subquery that can return many columns
SELECT c.full_name,
       recent.reference,
       recent.total_amount,
       recent.placed_at
FROM   customer c
LEFT JOIN LATERAL (
  SELECT o.reference, o.total_amount, o.placed_at
  FROM   customer_order o
  WHERE  o.customer_id = c.customer_id      -- may reference c
  ORDER  BY o.placed_at DESC
  LIMIT  1
) recent ON true;

Upserts and RETURNING

ON CONFLICT
INSERT INTO stock (product_id, quantity, updated_at)
VALUES (42, 10, now())
ON CONFLICT (product_id) DO UPDATE
SET    quantity   = stock.quantity + EXCLUDED.quantity,
       updated_at = now()
RETURNING product_id, quantity;

-- idempotent insert: ignore duplicates
INSERT INTO outbox_event (idempotency_key, payload)
VALUES ($1, $2)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING event_id;      -- returns no row when it was a duplicate

-- RETURNING works on UPDATE and DELETE too, which removes a round trip
UPDATE customer_order
SET    status = 'CANCELLED', version = version + 1
WHERE  order_id = $1 AND version = $2 AND status IN ('DRAFT','PLACED')
RETURNING order_id, status, version;

That last statement is optimistic locking, a state-machine guard and the new state returned — in one round trip. Zero rows means the caller lost the race.

A work queue with SKIP LOCKED

no broker required
UPDATE outbox_event
SET    published_at = now()
WHERE  event_id IN (
         SELECT event_id
         FROM   outbox_event
         WHERE  published_at IS NULL
         ORDER  BY event_id
         FOR UPDATE SKIP LOCKED
         LIMIT  100
       )
RETURNING event_id, aggregate_id, type, payload;

SKIP LOCKED makes concurrent workers step over rows another worker already holds, so ten pollers claim ten disjoint batches with no contention and no duplicates.

Full-text and fuzzy search

two different problems
-- full text: stemming, stop words, ranking
SELECT name, ts_rank(search_vector, q) AS rank
FROM   product, plainto_tsquery('english', 'wireless headphone') q
WHERE  search_vector @@ q
ORDER  BY rank DESC
LIMIT  20;

-- fuzzy: typos and partial matches, via pg_trgm
CREATE INDEX idx_product_name_trgm ON product USING gin (name gin_trgm_ops);

SELECT name, similarity(name, 'hedphones') AS score
FROM   product
WHERE  name % 'hedphones'          -- % is the similarity operator
ORDER  BY score DESC
LIMIT  10;
This covers most "we need Elasticsearch" requirements

Full-text ranking plus trigram fuzziness handles product search, customer lookup and admin filters comfortably into the millions of rows. Reach for a dedicated search engine when you need faceting, custom analysers or relevance tuning as a product feature.

Pagination that stays fast

OFFSET vs keyset
-- OFFSET: the database walks and discards every skipped row
SELECT * FROM customer_order ORDER BY order_id LIMIT 20 OFFSET 100000;  -- slow

-- keyset: index seek straight to the position, constant time
SELECT * FROM customer_order
WHERE  (placed_at, order_id) < ($1, $2)     -- last row of the previous page
ORDER  BY placed_at DESC, order_id DESC
LIMIT  20;

Ten workers poll the same queue table. Which clause stops them fighting over the same rows?

NOWAIT raises an error instead of waiting; SERIALIZABLE causes retries; a table lock serialises everything. SKIP LOCKED simply skips rows another transaction holds, so each worker claims a disjoint batch immediately.