+1 (726) 227-3497

Window Functions on Amazon Redshift: QUALIFY, Sessionization and Gaps-and-Islands

Window functions are where Redshift SQL gets most expressive, and where many slow queries come from. This tutorial covers four patterns we use constantly on client warehouses: deduplication, sessionization, gaps-and-islands, and top-N per group. It ends with the performance rules that matter on an MPP engine.

How a window function executes on Redshift

A window function with PARTITION BY forces rows with the same partition key onto the same slice, then sorts them by the ORDER BY inside the window. If the table is already distributed on the partition key and sorted on the order key, the redistribution and sort are cheap or avoidable. If not, you will see a DS_DIST step or a large sort in EXPLAIN. Keep that in mind for every example below.

Example table used throughout:

CREATE TABLE events (
  user_id     BIGINT,
  event_ts    TIMESTAMP,
  event_type  VARCHAR(50),
  page        VARCHAR(500)
)
DISTKEY (user_id)
SORTKEY (event_ts);

1. Deduplicate with QUALIFY

The classic approach wraps ROW_NUMBER() in a subquery:

SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) AS rn
  FROM staging.orders
) WHERE rn = 1;

Redshift now supports the QUALIFY clause, which filters on window results directly:

SELECT *
FROM staging.orders
QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) = 1;

The plan is the same; the query is shorter and harder to get wrong. Check that your cluster or workgroup is on a current patch version before relying on it, and keep the subquery form in code that must run on older clusters. Use a deterministic tiebreaker in the ORDER BY (for example add , ingest_id DESC) or reruns may keep different rows.

2. Sessionization

Define a new session when the gap since the user's previous event exceeds 30 minutes. Two steps: flag session starts with LAG, then number sessions with a running SUM.

WITH flagged AS (
  SELECT user_id, event_ts, page,
    CASE WHEN DATEDIFF(minute,
               LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts),
               event_ts) > 30
           OR LAG(event_ts) OVER (PARTITION BY user_id ORDER BY event_ts) IS NULL
         THEN 1 ELSE 0 END AS is_new_session
  FROM events
)
SELECT user_id, event_ts, page,
  SUM(is_new_session) OVER (
    PARTITION BY user_id ORDER BY event_ts
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS session_id
FROM flagged;

Because events is distributed on user_id, both windows run locally with no redistribution. Persist the result into a table (or a materialized view) rather than recomputing sessions in every dashboard query.

Session-level rollups then become simple aggregates:

SELECT user_id, session_id,
       MIN(event_ts) AS session_start,
       MAX(event_ts) AS session_end,
       COUNT(*)      AS events_in_session
FROM sessionized
GROUP BY user_id, session_id;

3. Gaps and islands

To find consecutive runs, such as consecutive days a user was active, subtract a row number from the value. Rows in the same island produce the same difference.

WITH days AS (
  SELECT DISTINCT user_id, event_ts::date AS d FROM events
),
numbered AS (
  SELECT user_id, d,
    d - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d))::int AS grp
  FROM days
)
SELECT user_id, MIN(d) AS streak_start, MAX(d) AS streak_end, COUNT(*) AS streak_days
FROM numbered
GROUP BY user_id, grp
HAVING COUNT(*) >= 3;

The DISTINCT matters. Duplicate days would break the arithmetic. For gaps instead of islands, compare each row to LEAD(d) and keep rows where the difference exceeds one day.

4. Top-N per group

SELECT customer_id, order_id, order_total
FROM orders
QUALIFY DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY order_total DESC) <= 3;

Pick ROW_NUMBER for exactly N rows, RANK or DENSE_RANK if ties should be kept.

Frame clauses: the quiet performance trap

When you add ORDER BY to an aggregate window and omit the frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which treats ties as peers. Say what you mean:

  • Use ROWS BETWEEN ... for running totals. It is explicit and avoids tie surprises.
  • For moving averages use ROWS BETWEEN 6 PRECEDING AND CURRENT ROW.
  • LAST_VALUE with the default frame returns the current row, not the partition's last row. Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.

Performance rules for MPP

  1. Align DISTKEY with PARTITION BY. A mismatch adds a redistribution of the whole input. Confirm in EXPLAIN.
  2. Reuse identical windows. Several functions with the same PARTITION BY ... ORDER BY share one sort. Differing specs each add a sort, so standardize them.
  3. Filter before windowing. Push date and tenant predicates into a CTE ahead of the window, except when the filter depends on the window result (use QUALIFY there).
  4. Watch skew. One huge partition (a bot user, a NULL key) lands on a single slice. Check row counts per partition key and filter or salt outliers.
  5. Materialize expensive windows. If a sessionized table is read many times, build it incrementally rather than recomputing it.

Checklist

  • Is there a deterministic tiebreaker in every ORDER BY?
  • Are frames explicit on running aggregates and LAST_VALUE?
  • Does EXPLAIN show a redistribution that a better DISTKEY would remove?
  • Are NULL partition keys handled?

If your Redshift warehouse has analytic queries that run longer than they should, our team can review the plans and key design as part of a performance optimization engagement. Reach out through the Get In Touch page.