+1 (415) 943-1448

BigQuery Window Functions and QUALIFY: Six Patterns That Replace Self-Joins

Window (analytic) functions are the most useful SQL feature in BigQuery that teams under-use. They let you rank, compare to the previous row, compute running totals, and sessionize events, all without self-joins. Self-joins are expensive in a warehouse that bills by data processed. This guide covers the patterns we use most on client projects. The examples use a hypothetical shop.orders table with order_id, customer_id, order_ts, amount, and country.

The anatomy of a window

SELECT
  order_id,
  customer_id,
  amount,
  SUM(amount) OVER (
    PARTITION BY customer_id
    ORDER BY order_ts
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  ) AS customer_running_total
FROM shop.orders;
  • PARTITION BY splits rows into independent groups. Leave it out and the whole table is one group.
  • ORDER BY sets the row order inside each partition.
  • The frame (ROWS BETWEEN ...) says which rows around the current one the function sees.

Be explicit about the frame for running aggregates. If you give ORDER BY and no frame, BigQuery defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Rows with equal ordering values are treated as peers and get the same result, which surprises people when timestamps tie.

Pattern 1: Top-N per group with QUALIFY

QUALIFY filters on window function results directly. You don't need a subquery.

SELECT customer_id, order_id, amount
FROM shop.orders
QUALIFY ROW_NUMBER() OVER (
  PARTITION BY customer_id
  ORDER BY amount DESC, order_id
) <= 3;

Add a tiebreaker column to the ORDER BY, such as order_id here. Otherwise ROW_NUMBER is not deterministic when values tie. Use RANK or DENSE_RANK when ties should share a position.

Note that BigQuery requires QUALIFY queries to also contain a WHERE, GROUP BY, or HAVING clause in some forms. If you hit that error, add WHERE TRUE.

Pattern 2: Deduplicate to the latest record

SELECT *
FROM shop.customers_raw
WHERE TRUE
QUALIFY ROW_NUMBER() OVER (
  PARTITION BY customer_id
  ORDER BY updated_at DESC
) = 1;

This is the standard way to collapse CDC or append-only landing tables into current state. Filter on the partition column in the WHERE clause when you can, so the query scans only the recent partitions.

Pattern 3: Compare to the previous row with LAG

SELECT
  customer_id,
  order_ts,
  TIMESTAMP_DIFF(
    order_ts,
    LAG(order_ts) OVER (PARTITION BY customer_id ORDER BY order_ts),
    DAY
  ) AS days_since_previous_order
FROM shop.orders;

The first row in each partition gets NULL. LAG(col, 2, default) looks back two rows and supplies a default. LEAD looks forward.

Pattern 4: Moving averages

SELECT
  order_date,
  revenue,
  AVG(revenue) OVER (
    ORDER BY order_date
    ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
  ) AS revenue_7_row_avg
FROM daily_revenue;

ROWS counts physical rows. If your daily table has missing dates, a "7-row" average does not cover seven days. Fill the gaps first with GENERATE_DATE_ARRAY, or use a RANGE frame over a numeric ordering key, for example UNIX_DATE(order_date):

AVG(revenue) OVER (
  ORDER BY UNIX_DATE(order_date)
  RANGE BETWEEN 6 PRECEDING AND CURRENT ROW
)

Pattern 5: Sessionization

Sessionizing events is the classic use of window functions. Start a new session after 30 minutes of inactivity:

WITH flagged AS (
  SELECT
    user_id,
    event_ts,
    IF(
      TIMESTAMP_DIFF(
        event_ts,
        LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts),
        MINUTE
      ) > 30
      OR LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts) IS NULL,
      1, 0
    ) AS is_new_session
  FROM analytics.events
)
SELECT
  user_id,
  event_ts,
  SUM(is_new_session) OVER (
    PARTITION BY user_id
    ORDER BY event_ts
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  ) AS session_number
FROM flagged;

Flag each boundary, then take a running sum of the flags. The same technique finds "islands" in any ordered data, such as consecutive login days or contiguous outage periods.

Pattern 6: Share of total without a join

SELECT
  country,
  SUM(amount) AS revenue,
  SAFE_DIVIDE(SUM(amount), SUM(SUM(amount)) OVER ()) AS share_of_total
FROM shop.orders
GROUP BY country;

Window functions run after GROUP BY, so you can wrap an aggregate in a window aggregate, as in SUM(SUM(amount)) OVER ().

Named windows

If several expressions share a window, define it once:

SELECT
  customer_id,
  order_ts,
  ROW_NUMBER() OVER w AS order_seq,
  SUM(amount)  OVER w AS running_total
FROM shop.orders
WINDOW w AS (PARTITION BY customer_id ORDER BY order_ts);

Performance notes

  • Partition skew. All rows of one PARTITION BY key are processed together on one slot. A hot key, such as a NULL customer ID or one huge tenant, can cause slow stages or spilling to disk. Check the execution graph for a single worker taking far longer than the others, and filter or split out hot keys.
  • No PARTITION BY. A window with no partitioning pushes all rows through a single worker. That is fine for small result sets and slow for large ones.
  • Filter early. Window functions run after WHERE, so cut rows and prune table partitions before the window is computed.
  • Only select what you need. Wide SELECT * combined with a sort-heavy window increases shuffle size.
  • Prefer QUALIFY over self-joins for top-N and dedup. The query is shorter, and it usually avoids reading the table twice.

Quick reference

NeedFunction
Unique row numberROW_NUMBER()
Ranking with tiesRANK(), DENSE_RANK()
Previous or next rowLAG(), LEAD()
First or last in frameFIRST_VALUE(), LAST_VALUE() (set the frame explicitly)
BucketsNTILE(n)
PercentilePERCENT_RANK(), PERCENTILE_CONT()
Running totalsSUM() OVER (... ROWS ...)

LAST_VALUE with the default frame returns the current row, because the frame ends at CURRENT ROW. Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING if you want the true last value in the partition.

Need help?

If your analytics SQL is slow, expensive, or hard to maintain, BQBrains engineers can review your queries and model the fix. Get in touch with a description of the problem.