Happy Mittal
Happy Mittal

Reputation: 3747

max function in sql

I have a table :

ID | time
1 | 124124244
2 | 211313112
3 | 131334334  

I want to get row of max(time).
I tried like this:

select ID,max(time) from T;  

Although it gave correct max(time), but ID given was always 1. I can't get that whole row.
How can I do it ?

Upvotes: 1

Views: 101

Answers (4)

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115590

If there are no two rows with same time or if you want one of them and don't care for the others, you can use this:

SELECT    id, time
FROM      T
ORDER BY  time DESC
    LIMIT 1 ;

If there are more than one rows with same time, @Raphael's answer will return all of them.

Upvotes: 2

xdazz
xdazz

Reputation: 160873

SELECT * FROM T WHERE `time` = (SELECT MAX(`time`) FROM T)

Upvotes: 2

Meherzad
Meherzad

Reputation: 8553

select id from tbl where time = (select max(time) from tbl)

check this fiddle http://sqlfiddle.com/#!2/77acd/3

Upvotes: 1

Raphaël Althaus
Raphaël Althaus

Reputation: 60503

select t.ID, t.time from T
inner join (select MAX(time) maxTime FROM T) a
 ON a.maxTime = t.time;

SqlFiddle, with xdazz's answer also (both are working)

Upvotes: 2

Related Questions