SiriusBits
SiriusBits

Reputation: 790

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)

Upvotes: 0

Views: 1667

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269443

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.

Upvotes: 1

Related Questions