Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options to retrieve the current (on a moment of running query) sequence value

How is it possible to get the current sequence value in postgresql 8.4?

Note: I need the value for the some sort of statistics, just retrieve and store. Nothing related to the concurrency and race conditions in case of manually incrementing it isn't relevant to the question.

Note 2: The sequence is shared across several tables

Note 3: currval won't work because of:

  • Return the value most recently obtained by nextval for this sequence in the current session
  • ERROR: currval of sequence "<sequence name>" is not yet defined in this session

My current idea: is to parse DDL, which is weird

like image 935
zerkms Avatar asked Feb 14 '13 23:02

zerkms


People also ask

How do you change the current value of a sequence in Oracle?

Best AnswerMake the sequence INCREMENT BY that amount. Issue one new number. Change the INCREMENT BY back to the original amount. The next number genereate after that will be the desired value.

How do you get the next value of a sequence in SQL?

If you want to select the next value from sequence object, you can use this SQL statement. If you want to select multiple next values from SQL Sequence, you have to loop calling the above SQL statement and save the "next value" got in a storage. You can loop using (while loop) or by (cursor).

How do I use Currval in PostgreSQL?

currval(' sequence_name ') Returns the most recently returned value from nextval(' sequence_name '). This value is associated with a PostgreSQL session, and if the nextval() function has not yet been called in the connected session on the specified sequence sequence_name , there will be no "current" value returned.

What is Currval and Nextval in Oracle?

CURRVAL. returns the current value of a sequence. NEXTVAL. increments the sequence and returns the next value.


2 Answers

You may use:

SELECT last_value FROM sequence_name; 

Update: this is documented in the CREATE SEQUENCE statement:

Although you cannot update a sequence directly, you can use a query like:

SELECT * FROM name;

to examine the parameters and current state of a sequence. In particular, the last_value field of the sequence shows the last value allocated by any session. (Of course, this value might be obsolete by the time it's printed, if other sessions are actively doing nextval calls.)

like image 163
Daniel Vérité Avatar answered Sep 18 '22 18:09

Daniel Vérité


If the sequence is being used for unique ids in a table, you can simply do this:

select max(id) from mytable;

The most efficient way, although postgres specific, is:

select currval('mysequence');

although technically this returns the last value generated by the call to nextval('mysequence'), which may not necessarily be used by the caller (and if unused would leave gaps in an auto increments id column).

like image 34
Bohemian Avatar answered Sep 19 '22 18:09

Bohemian