Postgres latest row: filter before or after selection?
Show a correct deterministic query that still lies about current health when status is filtered before choosing the latest event.
Quick answer
To find the latest Postgres row per group, first define which rows are eligible, then choose a deterministic ordering inside each group. Filtering before that choice answers a different question from filtering afterward. `DISTINCT ON` can express either contract, but neither a tie-breaker nor an index can repair the wrong eligibility rule.
On this page
To find the latest Postgres row per group, first define which rows are eligible, then choose a deterministic ordering inside each group. Filtering before that choice answers a different question from filtering afterward. DISTINCT ON can express either contract, but neither a tie-breaker nor an index can repair the wrong eligibility rule. [1][2]
Which “latest” does the report actually mean?#
Scenario: a fictional fleet dashboard lists devices whose latest reported health is healthy. The event table contains healthy and unhealthy reports, a timestamp and an event identifier. A developer adds WHERE status = 'healthy' to an existing latest-row query. The dashboard looks reassuring, but it can now display an old healthy report for a device whose newer report says it is unhealthy.
The placement of the word “latest” changes which events may compete. “Latest event, if healthy” means choose from the full eligible event history and then inspect the selected event. “Latest healthy event” means discard unhealthy events and choose from what remains. Both are legitimate reports. They become dangerous when a query written for the latter is labelled as the former.
Write the contract as a sentence before touching SQL. In this case: for each tenant-device pair, select the event with the greatest non-missing occurrence time, break equal timestamps by the event identifier, then include it only if its status is healthy. A timestamp with no value is ineligible. The identifier rule is a deterministic product convention, not evidence of real-world arrival order.
That last distinction matters when events arrive late. A device's occurrence time, server ingestion time and processing sequence describe different orders. If the dashboard promises “most recently received,” the query needs a trustworthy received-time or sequence contract instead. Giving the wrong clock a descending sort makes the query deterministic while preserving the wrong meaning.
Build a fixture that can disprove the obvious query#
Use a small relation that contains the failure rather than many ordinary rows. The example below is illustrative data, not production measurements. It includes a newer unhealthy event, equal-time reports, an unknown timestamp and another tenant with a device identifier that happens to match. The SQL targets documented PostgreSQL 18 behavior. [1][2][3]
CREATE TEMP TABLE health_event (
event_id bigint PRIMARY KEY,
tenant_id text NOT NULL,
device_id text NOT NULL,
occurred_at timestamptz,
status text NOT NULL
);
INSERT INTO health_event VALUES
(101, 'acme', 'pump', '2026-10-01 09:00+00', 'healthy'),
(102, 'acme', 'pump', '2026-10-01 10:00+00', 'unhealthy'),
(103, 'acme', 'fan', '2026-10-01 10:00+00', 'healthy'),
(104, 'acme', 'fan', '2026-10-01 10:00+00', 'unhealthy'),
(105, 'acme', 'valve', NULL, 'healthy'),
(106, 'beta', 'pump', '2026-10-01 10:00+00', 'healthy');Scenario: the accepted “currently healthy” result contains only the other tenant's pump. The first pump has a newer unhealthy report; the fan's higher identifier wins the agreed tie; the valve has no eligible timestamp. These outcomes are business expectations derived from the stated contract, not sample database output.
The tempting query places the status filter inside the selection:
-- Answers: latest healthy event for each tenant-device pair.
SELECT DISTINCT ON (tenant_id, device_id)
tenant_id, device_id, event_id, occurred_at, status
FROM health_event
WHERE occurred_at IS NOT NULL AND status = 'healthy'
ORDER BY tenant_id, device_id, occurred_at DESC, event_id DESC;This query has a complete ordering. It still answers the wrong question for a current-health dashboard, because the unhealthy rows no longer participate. Postgres's documented processing places WHERE before distinct-row selection. Improving the syntax or adding another sort expression cannot restore the excluded candidates. [1]
How do you keep selection and display filters separate?#
Put the latest-row choice in a subquery and the selected-status test outside it. The inner condition contains eligibility rules that really apply to the history: in this example, a known timestamp. The outer condition contains a condition on the chosen winner. Explicit columns make the contract easier to inspect than a wide SELECT *. [1]
SELECT tenant_id, device_id, event_id, occurred_at, status
FROM (
SELECT DISTINCT ON (tenant_id, device_id)
tenant_id, device_id, event_id, occurred_at, status
FROM health_event
WHERE occurred_at IS NOT NULL
ORDER BY tenant_id, device_id, occurred_at DESC, event_id DESC
) AS latest
WHERE status = 'healthy'
ORDER BY tenant_id, device_id;The grouping expressions must match the leftmost ordering expressions for DISTINCT ON. The remaining ordering expressions choose the winning row. An outer ORDER BY controls presentation after that choice, so changing the dashboard display order does not accidentally change which event represents a device. [1][2]
Tenant identity belongs in both the grouping and the ordering. Filtering to a single tenant before selection is reasonable when that is the query's explicit scope, but grouping only by a device name in a cross-tenant report can merge unrelated histories. A globally unique device key could change that requirement; verify the schema's guarantee rather than assuming names are unique.
Now make the missing-time rule explicit. Excluding missing timestamps says those reports cannot establish recency. Using DESC NULLS LAST instead keeps them as fallback candidates when a device has no dated report. Those are different contracts. Postgres puts nulls first for a descending sort by default, so a bare descending timestamp can promote an undated row unexpectedly. [2]
If undated reports need their own dashboard, expose that state directly. Calling an unknown-time report “latest” gives a precision the data does not contain. Likewise, the highest event identifier resolves a tie only because this example adopts that rule. An opaque UUID can make a deterministic tie-breaker without establishing which of the tied events actually happened later.
Would a window function change the answer?#
A window function gives another way to express the same winner. It also makes it convenient to retain several ranked events for explanation. It does not erase the importance of filter placement: a window function sees the relation after its query's filtering, so an early status predicate creates the same semantic error. [3]
WITH ranked AS (
SELECT tenant_id, device_id, event_id, occurred_at, status,
row_number() OVER (
PARTITION BY tenant_id, device_id
ORDER BY occurred_at DESC, event_id DESC
) AS position
FROM health_event
WHERE occurred_at IS NOT NULL
)
SELECT tenant_id, device_id, event_id, occurred_at, status
FROM ranked
WHERE position = 1 AND status = 'healthy'
ORDER BY tenant_id, device_id;Choose the form your team can review reliably. DISTINCT ON is concise for selecting a single Postgres row per group. Ranking is useful when the report needs multiple positions or an explanation of the losing candidates. Switching syntax must keep the same selected event identifiers on the adversarial fixture. Postgres documents DISTINCT ON as an extension, which matters when portability is a requirement. [1][3]
An aggregate with max(occurred_at) answers a narrower question: it finds the maximum timestamp. Joining that timestamp back to the event table can return several tied rows. You still need a policy for selecting a row and retaining its other fields. Avoid independently taking maxima of status or payload fields; the resulting values need not describe any single event.
Why can a healthy-only index encourage the wrong rewrite?#
A partial index includes only rows satisfying its predicate. An index restricted to healthy events might suit the “latest healthy event” report, but it cannot, by itself, represent the unhealthy event that should disqualify a device from the current-health report. Keep the semantic query fixed while evaluating an index. Do not push the status predicate inward just to make an attractive plan available. [4]
For the stated contract, an index candidate begins with the tenant and device keys and continues with the recency order. Since undated events are explicitly ineligible, a partial predicate on known timestamps can match that eligibility rule. This is a candidate to measure, not a claim that every workload should add the index. Multicolumn indexes have storage and write costs, and their usefulness depends on the query and data distribution. [4][5]
CREATE INDEX health_event_latest_known
ON health_event
(tenant_id, device_id, occurred_at DESC, event_id DESC)
WHERE occurred_at IS NOT NULL;
-- Run against a representative disposable or approved environment.
EXPLAIN (ANALYZE, BUFFERS)
SELECT tenant_id, device_id, event_id, occurred_at, status
FROM (
SELECT DISTINCT ON (tenant_id, device_id)
tenant_id, device_id, event_id, occurred_at, status
FROM health_event
WHERE occurred_at IS NOT NULL
ORDER BY tenant_id, device_id, occurred_at DESC, event_id DESC
) AS latest
WHERE status = 'healthy';Read the actual plan rather than assuming the index allows the engine to touch only a single row per device. EXPLAIN ANALYZE executes the query, so use an environment and workload for which that execution is authorized. Look at scanned rows, buffers, sorting and filtering, then compare with a baseline on the same fixture and representative data. This article makes no speedup claim. [5][6]
What acceptance record prevents the bug returning?#
Put the tenant scope, eligible timestamps, grouping key, recency clock, tie rule and final status test in the query review. Pair that record with adversarial fixture results. A screenshot showing a plausible healthy device is weak evidence; the newer unhealthy event must be present in the fixture and must disqualify its older healthy predecessor.
| Fixture branch | Latest-event contract | Latest-healthy-event contract |
|---|---|---|
| Healthy followed by unhealthy | Device omitted | Older healthy event retained |
| Equal timestamps | Agreed identifier decides | Same rule among eligible healthy rows |
| Only unknown timestamps | Omitted under this eligibility rule | Also omitted unless the rule changes |
| Same device name across tenants | Separate groups | Separate groups |
Add a regression that compares the DISTINCT ON and ranked versions as sets, including selected event identifiers. Comparing only the number of rows can miss a wrong winner. Keep a separate test for final ordering if an API depends on stable presentation. If the data changes during a multi-query report, define the snapshot boundary too; deterministic selection does not freeze a changing database.
The publication checks use a local relational fixture for the ranked formulation and expected-set comparison. The Postgres-specific DISTINCT ON and index plans require a Postgres integration check in your environment; they were documentation-reviewed here, not benchmarked. Keep that limitation beside the code rather than treating a successful alternate-engine fixture as a Postgres execution result. [1][3][6]
How does an “as of” report change eligibility?#
Scenario: support asks what the dashboard would have shown at a historical cutoff. Put the cutoff in the relation from which the latest event is selected. An event after the cutoff must not win and then be removed afterward, because that can hide the earlier event that should represent the device at the requested time. The position of this time predicate serves a different purpose from the selected-status predicate. [1]
Write the historical contract in full: consider events known to the report under the chosen cutoff rule, choose each device's latest eligible event, then test its status. If the cutoff refers to occurrence time, a late-arriving event can alter a historical answer when the query is rerun. If the report promises what the system actually knew then, the dataset also needs an ingestion or knowledge boundary. Sorting cannot reconstruct information that the schema never recorded.
Keep the historical cutoff parameter typed and timezone-aware at the application boundary. Do not compare localized display strings or truncate precision to make a tie disappear. Record whether the boundary includes an event exactly at the cutoff, and put that equality case in the fixture. The query reviewer should be able to explain why the event competes without reading a UI date label.
Now consider several widgets on a report page. Each query can implement its own winner correctly while observing a different set of committed events. If the page requires a coherent historical snapshot, establish that through the report's database transaction and isolation contract. If it tolerates independently refreshed widgets, display their observation boundaries. A deterministic ordering controls ties within the visible relation; it does not synchronize independent reads.
For the fixture, add an event just after the cutoff and verify that the earlier eligible event still competes. Add a tied event exactly at the boundary and confirm the agreed identifier rule. Then change only the outer status filter and verify that the inner set of selected event identifiers stays fixed. This gives the test distinct jobs: eligibility decides who can compete, ordering chooses a winner, and the final predicate decides whether to display that winner. [1][2]
Keep the index review subordinate to that sequence. A fast historical query with a changed cutoff interpretation is a report defect, not a performance improvement. Measure only after the fixture establishes the intended historical answer, and retain the expected identifiers alongside the plan so a future optimization has the same semantic target. [4][6]
The same habit helps when LEFT JOIN reports lose rows: decide what each relation represents before repairing syntax. Here the crucial relation is the set from which the winner may be chosen.
- Is DISTINCT ON enough to select the latest row?
- It selects the first row in each group according to the query's ordering. Define eligibility, put grouping expressions first in the ordering, and provide a complete tie rule. The keyword alone does not define recency. [1]
- Should status filtering happen inside or outside?
- Filter inside when status defines eligible history, as in “latest successful attempt.” Filter outside when status is a test on the overall latest event. Name the report accordingly and include a fixture where the answers differ. [1]
- Can NULLS LAST replace an explicit missing-time policy?
- No. It controls ordering, while excluding missing timestamps controls eligibility. Keeping nulls last still permits an undated winner when the group contains only undated rows. Decide whether that fallback has a useful business meaning. [2]