Yi Zeng
Yi Zeng

Reputation: 32895

Select the latest records (i.e. ORDER by) when IDs IN multiple values

For example, a devices table like this

id user_id last_used_at
1 111 2000-01-01 00:00:00
2 111 2003-01-01 00:00:00
3 222 2000-01-01 00:00:00
4 222 2003-01-01 00:00:00

The question is - how to select the last used devices of user_id IN (111, 222)?

Upvotes: 0

Views: 59

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272406

You can use PostgreSQL specific DISTINCT ON for this:

SELECT DISTINCT ON (user_id) *
FROM devices
ORDER BY user_id, last_used_at DESC

Upvotes: 2

Ankit Bajpai
Ankit Bajpai

Reputation: 13527

There are multiple ways to do this. Using WINDOW function is 1 of them -

SELECT *
  FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY last_used_at DESC) RN
          FROM devices)
 WHERE user_id IN (111, 222)
   AND RN = 1;

Upvotes: 1

Related Questions