简体   繁体   中英

Select last value in a specific column? (PostgreSQL)

Running into some issues when trying to retrieve the last value in a specific column, from a table and assign it into a variable.

Looking for the last int in a column "id" that is a primary key basically.

So I have a variable like "lastValue" in a select statement like :

select last(id) into lastValue from test_table

Not sure on an exact, or best way to accomplish this.

(on mobile, please forgive formatting)

A typical way to solve this is with order by and limit :

select id
from test_table
order by id desc
limit 1;

Of course, in this case, you could simply use:

select max(id)
from test_table;

But the first method allows you to choose whichever variables you want from the row with the maximum value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM