Direct answer: When two rows tie on every column in your ORDER BY, including the timestamp, ROW_NUMBER() = 1 no longer has a single correct answer: which of the tied rows gets rank 1 depends on the engine's internal row order, which can differ across runs, across a re-execution after a vacuum/reorganize, or across a query plan change, none of which are things you control. The fix is to keep adding ORDER BY keys until no two rows in any partition can tie on all of them simultaneously, ending with a column that is guaranteed unique (a primary key or surrogate id) as the final, unconditional tiebreaker.
Structured elaboration
Why it breaks determinism. ROW_NUMBER() assigns 1, 2, 3, ... to rows within a partition based on the ORDER BY clause. SQL only guarantees a well-defined order among rows that the ORDER BY clause can actually distinguish; rows that tie on every listed key are, per the standard, in an implementation-defined order relative to each other. Two runs of the identical query, or the same query before and after a table reorganization, can legally return a different row as rank 1 even though nothing about the data changed. For a dedup pipeline, that means the 'surviving' row for a given key can flap between runs, which breaks any downstream process relying on a stable choice (a slowly changing dimension load, an incremental pipeline keyed on the surviving row's id, or just a report that should be reproducible).
A concrete multi-criteria tie-break. A common real fix, not just 'add the id': when deduplicating events that arrived from multiple devices for the same user at the identical timestamp, rank by business priority first, THEN by recency, THEN by id: prefer a desktop-sourced event over mobile, and mobile over tablet, before falling back to timestamp, and only fall back to the row id if literally everything else ties.
sql
WITH ranked AS (
SELECT id, user_id, score, event_ts, device,
ROW_NUMBER() OVER (
PARTITION BY user_id
ORDER BY score DESC, event_ts DESC,
CASE device WHEN 'desktop' THEN 1 WHEN 'mobile' THEN 2 WHEN 'tablet' THEN 3 ELSE 4 END,
id
) AS rn
FROM events2
)
SELECT * FROM ranked WHERE rn = 1;
Worked example (executed in DuckDB). Two rows for user 1 tie exactly on score (90) and event_ts (09:00:00): one from mobile (id 2... shown as id in output), one from desktop. A third row for the same user has a lower score.
text
-- ORDER BY score DESC, event_ts DESC only (no further tiebreak):
id | score | event_ts | device | rn
1 | 90 | 09:00:00 | mobile | 1 <- arbitrary: this engine happened to rank id=1 first
2 | 90 | 09:00:00 | desktop | 2
3 | 80 | 08:00:00 | tablet | 3
-- with device-priority + id added as final tiebreak:
id | score | event_ts | device | rn
2 | 90 | 09:00:00 | desktop | 1 <- deterministic: desktop always wins this tie now
Adding the device-priority CASE and the id column changes which row wins the tie from 'whatever the engine happens to return first' to a fixed, explainable, always-reproducible answer: desktop over mobile over tablet, with the surrogate id as the final fallback if even device somehow ties.
DISTINCT ON as an alternative (Postgres and DuckDB). DISTINCT ON expresses the identical intent more compactly on engines that support it: pick one row per key, ordered by the same tiebreak chain, without a separate ROW_NUMBER/filter step.
sql
SELECT DISTINCT ON (user_id) id, user_id, score, event_ts, device
FROM events2
ORDER BY user_id, score DESC, event_ts DESC,
CASE device WHEN 'desktop' THEN 1 WHEN 'mobile' THEN 2 WHEN 'tablet' THEN 3 ELSE 4 END, id;
Run against the same data, this returns the identical winning row (desktop, id matching the ROW_NUMBER = 1 result), confirming the two formulations agree once the ORDER BY chain is fully deterministic. DISTINCT ON is not portable (Postgres and DuckDB support it; SQL Server, Snowflake, and BigQuery do not), so ROW_NUMBER() = 1 remains the more broadly applicable pattern.
A related but distinct angle: time-window duplicates instead of exact-key duplicates. Not every 'duplicate' shares an identical key. If two events for the same user within, say, 5 seconds of each other should be treated as one duplicate click even though their timestamps differ slightly, exact-key PARTITION BY doesn't apply at all; that's the gaps-and-islands technique instead (bucket by a rounded/truncated timestamp, or flag a new group whenever the gap from the previous event exceeds the tolerance), not a tie-break question. Worth naming explicitly: 'duplicate' meaning exact-key collision and 'duplicate' meaning near-in-time collision are two different problems that happen to both get called deduplication.
Trade-offs & pitfalls
- A hash of the full row's content is another valid final tiebreaker when there's no natural priority order, but it must be computed over stable, deterministic functions only; never include
random(), now(), or any non-deterministic expression in a tiebreak chain, or you reintroduce the exact nondeterminism you were trying to remove.
- Document the tiebreak precedence somewhere visible (a comment in the query or a data-quality doc); a reviewer six months later has no way to infer 'why does desktop always win' from the
CASE expression alone.
- Adding more
ORDER BY keys costs a marginally more expensive sort, not more scans; it's essentially free compared to the cost of nondeterministic output in a pipeline anyone depends on.