SQL

Get the Latest Entry for Each Group Using Window Functions

Discover how to retrieve the most recent record for each distinct group in your SQL database, perfect for 'latest activity' or 'last update' scenarios.

WITH RankedItems AS (
  SELECT
    item_id,
    group_id,
    value,
    created_at,
    ROW_NUMBER() OVER(PARTITION BY group_id ORDER BY created_at DESC) as rn
  FROM items
)
SELECT item_id, group_id, value, created_at
FROM RankedItems
WHERE rn = 1;
How it works: This snippet uses a Common Table Expression (CTE) and the `ROW_NUMBER()` window function to find the latest record within each group. `PARTITION BY group_id` divides the data into groups based on the `group_id`, and `ORDER BY created_at DESC` assigns a rank within each group, with the most recent item getting rank 1. The outer query then filters for `rn = 1` to select only the latest item from each group.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs