Skip to content
Advertisement

Postgres: getting latest rows for an array of keys

I have a simple table for the events log:

If I need the latest event for a given user, that’s obvious:

However, suppose I need the latest events for each user id in an array. For example, for the table above and users {1, 4} I’d expect events {3, 5}. Is that possible in plain SQL without resorting to a pgSQL loop?

Advertisement

Answer

A Postgres specific solution is to use distinct on which is usually faster than the solution using a window function:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement