PREP WITH PROOF
Menu
SQL & DATA QUALITY / PRACTICAL GUIDE

SQL Latest Row Per Group: ROW_NUMBER, Ties and NULL Policies

Select the latest row per group with deterministic ROW_NUMBER ordering. Compare MAX joins, timestamp ties, NULL fallback and filters before or after ranking.

THE QUICK ANSWER

Use ROW_NUMBER() over a group partition with a complete ordering key, then filter rn = 1 in an outer query. Define timestamp ties and NULL handling explicitly. Filtering eligible rows before ranking means something different from filtering the selected winner afterward. A MAX(timestamp) join can return ties and omit all-NULL groups.

Latest is a selection rule, not just an aggregate

A report needs the latest status for each account. GROUP BY account with MAX(observed_at) finds a time, but the report also needs the identifier and status belonging to a chosen event. Joining that maximum back to the events can return two rows when timestamps tie. A group with only unknown times introduces another decision: should it disappear or receive a fallback row?

Begin with the output contract. This guide selects one eligible row per represented account, preferring a known observation time, then the greatest time, then the greatest unique event ID. An account whose eligible times are all NULL receives the greatest-ID eligible row as an explicit fallback. That fallback is deterministic, but it is not evidence that an unknown event actually occurred later.

The example uses SQLite with integer observation times, plus Python only as a runnable test harness and independent oracle. The published fixture ran on SQLite 3.53.1. It does not use wall-clock strings, delete duplicate data or benchmark an index. Its purpose is to make cardinality, tie handling and filter placement testable before a query becomes part of a report.

Rank candidates, then select row number one

Partitioning by account gives each account its own competition. The window ordering first places NULL times behind known times, then orders known times descending, then uses event_id descending to settle remaining ties. Because event_id is the primary key, no two candidate rows share the entire ordering key. The final ORDER BY account controls presentation separately from choosing each winner.

The window expression appears inside a common table expression, with rn = 1 applied by the outer SELECT. SQLite permits window functions in result expressions and ORDER BY, rather than directly in the same SELECT’s WHERE clause. Keeping the ranking stage separate also gives the eligibility predicate a visible location.

The boolean expression observed_at IS NULL is evaluated as a SQLite ordering expression. With ascending order, known values precede NULL values under this contract. Port the idea deliberately: another SQL dialect may require CASE WHEN observed_at IS NULL THEN 1 ELSE 0 END or provide its own NULLS LAST syntax. Recheck the syntax and ordering behavior on the database you actually run.

WITH ranked AS (
  SELECT account, event_id, observed_at, state,
         ROW_NUMBER() OVER (
           PARTITION BY account
           ORDER BY observed_at IS NULL, observed_at DESC, event_id DESC
         ) AS rn
  FROM event
  WHERE state = 'active'
)
SELECT account, event_id, observed_at, state
FROM ranked
WHERE rn = 1
ORDER BY account;

Source: SQLite window functions: ROW_NUMBER, ranking and output ordering ↗

Choose one winner or retain every newest-time tie

For account A, two active rows have time 100 and IDs 1 and 2. Under the one-row contract, ID 2 wins. A timestamp-only maximum join returns both IDs. That result is not necessarily a faulty join: it answers the different question “which rows have the greatest known timestamp?” Decide which question the downstream consumer expects.

If all ties are wanted, a ranking function such as RANK can describe that contract. Rank by the time policy without the unique ID tie-breaker, then retain rank one. Adding event_id to that ordering removes the timestamp peer group and changes the meaning. A tie-breaker belongs in a one-winner rule; it should not silently erase ties that the report intended to show.

Do not replace the row selection with independent maxima for every column. The greatest time and greatest ID can belong to different source rows. Likewise, DISTINCT removes duplicate projected values; it does not define which event should represent an account. Include the identifier while validating the query so that the actual chosen source record remains visible.

Why the maximum-time join loses the all-NULL account

In the fixture, B has two active events with NULL times. MAX(observed_at) returns NULL for that group, and an equality join on e.observed_at = m.newest does not match NULL to NULL. B therefore contributes no rows to the maximum-time join, while the explicit ROW_NUMBER fallback returns ID 5.

There is no universally correct NULL policy. You may instead exclude unknown times from eligibility, retain an explicit “no known latest event” state, or return every unknown candidate for review. The important part is to specify the policy before treating one-row output as a data-quality guarantee. A deterministic query cannot manufacture missing chronology.

A compact SQLite aggregate with a bare status column also needs care. SQLite documents special behavior when a single built-in min or max aggregate is present, but equal maxima still leave the associated bare-column choice unspecified. Do not assume that a query accepted by SQLite provides your required tie rule or will be accepted unchanged by another SQL engine.

Source: SQLite SELECT: filtering and bare columns with min/max ↗

Latest active event and latest event that is active differ

Account A has a newer inactive event at time 200. Filtering state = active before ranking asks for the latest active event, so ID 2 remains the winner. Ranking every event first and then requiring the chosen row to be active asks whether the account’s latest selected event is active; A is excluded. C has the same distinction at different times.

The fixture calls these queries LATEST_ACTIVE and LATEST_THEN_ACTIVE. The first returns A, B, C and D; the second returns B and D under the stated NULL fallback. Both are valid selection contracts. Moving the predicate across the ranking boundary is a semantic change, even if an edit looks like a harmless query cleanup.

Use that distinction when reviewing date ranges as well. Restricting the candidate rows to a reporting month selects the latest event inside the month. Choosing the all-time latest event and then checking whether it falls in the month is another report. If you need a state as of a cutoff, define which events are eligible at that cutoff before ranking them.

Requested resultCandidate stageWinner stage
Latest active eventKeep active eventsChoose one using time and ID
Latest event, only if activeKeep all eventsChoose one, then check state
All newest known-time tiesChoose eligible known-time eventsRetain all peers at maximum time
Latest eligible row with unknown-time fallbackKeep eligible events, including NULL timeKnown time first; greatest ID settles ties

Run a complete fixture with an independent winner calculation

Save this as latest_per_group.py and run python latest_per_group.py with a Python environment that includes SQLite window-function support. No external package or database server is needed. The table uses a non-NULL account key, a unique integer event ID, a nullable integer time and a state. The labels and numbers are invented examples, not observations from a production system.

The three initial assertions check the exact rows returned by the two ranking contracts and the maximum-time join. The Python reference scans candidate rows and compares explicit tuple keys instead of executing another window query. The randomized section tests both ranking contracts against that reference, including empty input, tied times, negative times and groups with unknown observations.

The fixture completed 1,203 assertions across the fixed examples and 300 seeded datasets loaded in two insertion orders. Reversing insertion order is a useful regression check, but the determinism argument comes from the unique complete ordering key. Neither the checks nor the small in-memory table establish the best physical plan for a large warehouse.

import random
import sqlite3
from contextlib import closing

LATEST_ACTIVE = '''
WITH ranked AS (
  SELECT account, event_id, observed_at, state,
         ROW_NUMBER() OVER (
           PARTITION BY account
           ORDER BY observed_at IS NULL, observed_at DESC, event_id DESC
         ) AS rn
  FROM event
  WHERE state = 'active'
)
SELECT account, event_id, observed_at, state
FROM ranked WHERE rn = 1
ORDER BY account;
'''

LATEST_THEN_ACTIVE = '''
WITH ranked AS (
  SELECT account, event_id, observed_at, state,
         ROW_NUMBER() OVER (
           PARTITION BY account
           ORDER BY observed_at IS NULL, observed_at DESC, event_id DESC
         ) AS rn
  FROM event
)
SELECT account, event_id, observed_at, state
FROM ranked WHERE rn = 1 AND state = 'active'
ORDER BY account;
'''

MAX_JOIN = '''
WITH eligible AS (SELECT * FROM event WHERE state = 'active'),
latest AS (
  SELECT account, MAX(observed_at) AS newest
  FROM eligible GROUP BY account
)
SELECT e.account, e.event_id, e.observed_at, e.state
FROM eligible AS e JOIN latest AS m
  ON e.account = m.account AND e.observed_at = m.newest
ORDER BY e.account, e.event_id;
'''


def reference(rows, active_first):
    winners = {}
    for account, event_id, observed_at, state in rows:
        if active_first and state != 'active':
            continue
        key = (observed_at is not None,
               observed_at if observed_at is not None else 0, event_id)
        if account not in winners or key > winners[account][0]:
            winners[account] = (key, (account, event_id, observed_at, state))
    return [winners[a][1] for a in sorted(winners)
            if active_first or winners[a][1][3] == 'active']


def load(con, rows):
    con.execute('DELETE FROM event')
    con.executemany('INSERT INTO event VALUES (?, ?, ?, ?)', rows)


def main():
    with closing(sqlite3.connect(':memory:')) as con:
        con.execute('''CREATE TABLE event(
          account TEXT NOT NULL, event_id INTEGER PRIMARY KEY,
          observed_at INTEGER, state TEXT NOT NULL
        )''')
        rows = [('A', 1, 100, 'active'), ('A', 2, 100, 'active'),
                ('A', 3, 200, 'inactive'), ('B', 4, None, 'active'),
                ('B', 5, None, 'active'), ('C', 6, 50, 'active'),
                ('C', 7, 100, 'inactive'), ('D', 8, 80, 'active')]
        load(con, rows)
        assert con.execute(LATEST_ACTIVE).fetchall() == [
            ('A', 2, 100, 'active'), ('B', 5, None, 'active'),
            ('C', 6, 50, 'active'), ('D', 8, 80, 'active')]
        assert con.execute(LATEST_THEN_ACTIVE).fetchall() == [
            ('B', 5, None, 'active'), ('D', 8, 80, 'active')]
        assert con.execute(MAX_JOIN).fetchall() == [
            ('A', 1, 100, 'active'), ('A', 2, 100, 'active'),
            ('C', 6, 50, 'active'), ('D', 8, 80, 'active')]
        rng = random.Random(108)
        checks = 3
        for _ in range(300):
            rows = [(rng.choice('ABCDE'), i,
                     rng.choice([None, -2, 0, 1, 2, 2]),
                     rng.choice(['active', 'inactive']))
                    for i in range(1, rng.randrange(1, 45))]
            for data in (rows, list(reversed(rows))):
                load(con, data)
                for sql, active_first in ((LATEST_ACTIVE, True),
                                          (LATEST_THEN_ACTIVE, False)):
                    assert con.execute(sql).fetchall() == reference(rows, active_first)
                    checks += 1
        print(f'PASS: {checks} assertions; 300 seeded datasets, two insertion orders')
        print('SQLite', sqlite3.sqlite_version)


if __name__ == '__main__':
    main()

Keep timestamp meaning and query cost separate

The integer times are deliberately comparable without parsing a timestamp string. In a real schema, establish whether the order means event time, ingestion time or a source sequence. A late-arriving event may have a larger ingestion ID and an older event time. The ID tie-breaker in this guide resolves equal times; it does not replace the primary time ordering.

If timestamps are stored as text, mixed offsets, missing precision and inconsistent formats can defeat a naive lexical ordering. Normalize according to the application’s time contract before relying on a descending comparison. The related pagination guide explains why continuing through a composite sort key also requires keeping the full order precise.

After correctness is settled, inspect the real database’s execution plan and representative data. Partitioning, filtering and expression-based ordering can affect which indexes are useful. A conventional index on account and time may help some workloads, but this guide makes no claim that it eliminates sorting for the full NULL-policy expression. Measure rather than treating a suggested index as a performance result.

This SELECT does not remove duplicate source events or prevent future competing writes. If the requirement is durable uniqueness, investigate keys, ingestion rules and transaction boundaries separately. A report that displays one row per account can hide duplicate input without repairing it. Keep a diagnostic count or exception report when those duplicates matter operationally.

Make every winner explainable

For a reliable latest-row-per-group query, define eligibility, NULL handling and a complete tie-breaker before writing the window function. Keep candidate filtering separate from post-selection filtering, and retain a final ORDER BY for predictable presentation.

Test at least one timestamp tie, one all-NULL group, one account with a newer ineligible event and one empty input. Preserve the returned source ID in the assertions. Those cases establish what the query means and make later tuning easier to review without accidentally changing which row represents each group.

KEEP THESE THREE THINGS

Your next steps

  1. Choose a one-winner or all-ties contract explicitly.
  2. Use a unique tie-breaker after the primary time ordering.
  3. Decide what an unknown timestamp means for selection.
  4. Place eligibility filters before ranking only when that is the intended question.

Sources & official resources

Linked resources checked on 2026-11-05. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →