PostgreSQL, SELECT from max id

断了今生、忘了曾经 提交于 2019-12-01 15:21:20

If your goal is to get the row with the highest my_id value, then the following query should achieve the same goal.

SELECT my_id, col2, col3 
FROM mytable 
ORDER BY my_id DESC 
LIMIT 1

Just order by my_id and take only the first record with limit 1

SELECT my_id, col2, col3
FROM mytable 
order by my_id desc
limit 1

Another but less performant way would be

SELECT my_id, col2, col3
FROM mytable 
where my_id = (select max(my_id) from mytable)

Sub query may help you

SELECT my_id, col2, col3 FROM mytable WHERE my_id = (select MAX(my_id) FROM mytable)
PSR
SELECT my_id, col2, col3 FROM mytable WHERE my_id = (select MAX(my_id) FROM mytab)

or use

SELECT my_id, col2, col3 FROM mytable ORDER BY my_id DESC LIMIT 1

when you have an index on my_id the ones with the subquery should be faster. when you dont have an index take the "order by". (obv. depends on database size if relevant)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!