How get last auto_increment id from table?

815 views
Skip to first unread message

korwru

unread,
Jun 15, 2011, 1:29:56 AM6/15/11
to H2 Database
How can I get the current number of ID (auto_increment) for a specific
table in the database?

I'm looking for a query identical IDENT_CURRENT in database MS SQL.

In JDBC a method getGeneratedKeys () returns the ID value, but only
after INSERT-query.



Evan

unread,
Jun 15, 2011, 9:37:57 AM6/15/11
to H2 Database
Hi,

auto_increment is saved as sequences.

If you are like me, who create tables with auto_increment,
H2 will change it with
int not null default (next value for <schema.sequence_name>) not null
null_to_default sequence <sequence name>

you can confirm it using
select "SQL" from information_schema.tables where table_schema =
'YOUR_SCHEMA_NAME_IN_ALL_CAPS' and table_name =
'YOUR_TABLE_NAME_IN_ALL_CAPS'

now that you know the <schema.sequence_name> ,next run
select * from information_schema.sequences where sequence_schema =
'<schema>' and sequence_name = '<sequence_name>'

i think current_value is what you are looking for.

Hope that helps.
evan

Evan

unread,
Jun 15, 2011, 10:10:18 AM6/15/11
to H2 Database
wups, should've searched for that IDENT_CURRENT before..
Sorry, the method above gives you the NEXT value, not the CURRENT one.

I can only suggest select max..

On Jun 15, 2:29 pm, korwru <kor...@gmail.com> wrote:

korwru

unread,
Jun 15, 2011, 10:16:34 AM6/15/11
to H2 Database
Thank you. I have used this method.
Reply all
Reply to author
Forward
0 new messages