KITFORMA · EDITORIAL GUIDE
How can I select the newest row per customer without mismatching its columns?
KitForma editorial guide. Selecting MAX(timestamp) beside unrelated nonaggregated columns does not reliably select the complete row that owns that timestamp.
Step-by-step guidance
row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) and select rank one in an outer query. PostgreSQL DISTINCT ON is another option with a matching ORDER BY. Test tied timestamps and a customer with one record. The extra unique tie-breaker defines deterministic choice. If all tied newest rows should be returned, use an appropriate rank rather than row_number and document that multiple rows are possible.
Minimal example:
-- Standard window pattern; verified with SQLite.
WITH events(customer_id, created_at, id) AS
(VALUES (1, '2026-01-01', 10), (1, '2026-01-01', 11)),
ranked AS (
SELECT *, ROW_NUMBER() OVER (
PARTITION BY customer_id ORDER BY created_at DESC, id DESC
) AS position FROM events
)
SELECT id FROM ranked WHERE position = 1;
-- Expected: 11Sources and verification
Sources checked:
Scope: This editorial guide is based on the cited sources and tool behavior. A forum question or a query observed for our site does not establish market search volume, low competition, guaranteed rankings or inadequate answers elsewhere.
This starter guide was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.