Skip to content
Advertisement

Select the row with the most recent modified date

I have this table:

user_id name email modified_date
1 John a@gmail.com 2022-01-01
1 John b@gmail.com 2022-01-02
1 Lucy c@gmail.com 2022-01-03
2 Joey d@gmail.com 2021-12-24
3 Mike e@gmail.com 2022-01-01
3 Mary f@gmail.com 2022-01-02

I’m trying to get unique user_id‘s email with the most recent modified_date. This is my expected output:

user_id email name
1 c@gmail.com Lucy
2 d@gmail.com Joey
3 f@gmail.com Mary

I used limit 1, but the output seems to be randomized.

Can somebody help me to sort this out ?

Advertisement

Answer

you can go for row_number() with partition by

Schema (PostgreSQL v10.0)


Query #1

user_id email name
1 b@gamil.com John

View on DB Fiddle

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