← Graph

Prefer LATERAL over CTE for filtered top-N per group

takeaway 2 connections

In Postgres, a LATERAL join can be drastically faster than a CTE for top-N-per-group queries when additional filtering is applied, because the CTE materializes averages for every row in the table first. In the lightning talk's example this difference was ~5 ms (LATERAL) vs ~47 ms (classic) vs unchanged ~99 ms (CTE).

type
insight
takeaway Prefer LATERAL over CTE for filtered top-N per group
about
LATERAL join concept
Recommends LATERAL for filtered top-N-per-group queries.
takeaway Prefer LATERAL over CTE for filtered top-N per group
from_talk
Key insight derived from the benchmarking in the talk.

Provenance

Read by
4 extractions