开发者

How do I select an entire row which has the largest ID in the table?

开发者 https://www.devze.com 2023-04-09 18:15 出处:网络
How would I do something 开发者_开发技巧like this? SQL SELECT row FROM table WHERE id=max(id) You could use a subselect:

How would I do something 开发者_开发技巧like this?

SQL SELECT row FROM table WHERE id=max(id)


You could use a subselect:

SELECT row 
FROM table 
WHERE id=(
    SELECT max(id) FROM table
    )

Note that if the value of max(id) is not unique, multiple rows are returned.

If you only want one such row, use @MichaelMior's answer,

SELECT row from table ORDER BY id DESC LIMIT 1


You could also do

SELECT row FROM table ORDER BY id DESC LIMIT 1;

This will sort rows by their ID in descending order and return the first row. This is the same as returning the row with the maximum ID. This of course assumes that id is unique among all rows. Otherwise there could be multiple rows with the maximum value for id and you'll only get one.


SELECT * 
FROM table 
WHERE id = (SELECT MAX(id) FROM TABLE)


You can not give order by because order by does a "full scan" on a table.

The following query is better:

SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);


One can always go for analytical functions as well which will give you more control

select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1

If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.


Try with this

 SELECT top 1  id, Col2,  row_number() over (order by id desc)  FROM Table
0

精彩评论

暂无评论...
验证码 换一张
取 消