Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the row with max timestamp in postgres?

I need to get a row of information with max timestamp in postgresql. Below is a demo for this question:

drop table Mytable cascade
create table MyTable (usr char(1), event_dt timestamp without time zone);
insert into mytable values ('A','01-JAN-2009 11:10:11');
insert into mytable values ('A','02-JAN-2009 11:10:22');
insert into mytable values ('B','02-JAN-2009 01:01:59' );
insert into mytable values ('C', '31-DEC-2008 02:02:02');
insert into mytable values ('D', '31-DEC-2008 03:03:03');

If I do

select max(event_dt) from (
select usr,event_dt from mytable where usr= 'A') as foo 

It is sort of what I need but it only returns the event_dt "2009-01-02 11:10:22"

Where I want the usr as well sa event_dt from that row. How do I do it?

like image 884
RoundPi Avatar asked Feb 01 '13 19:02

RoundPi


1 Answers

I would simply go for...

SELECT usr, event_dt FROM mytable ORDER BY event_dt DESC LIMIT 1
like image 83
Najzero Avatar answered Oct 11 '22 18:10

Najzero