Skip to content
Advertisement

How to get the id from next inserted element before that is created?

I need to get the id from the future element insert in my table. I have an autoincrement id.

await db.execute('CREATE TABLE Product(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT)');

Imagine this is my table with the values:

Id   Name
1    something
2    something2

If I delete all the items and insert another element it goes like this:

Id   Name
3    something3

If I delete again that row it’s possible know the value of the future id? I need to get the future value of id before create a new product.

Advertisement

Answer

I don’t know what you want to do, but here’s how you can get the current ID.

select * from sqlite_sequence;

It will return all columns, which has an auto incremented ID. sqlite_sequence is a table which saves the name of the column and the current id. So you have to filter for you needed column and increment the id by one on your own.

If you have only your Product table and the last object added was with id 3:

select * from sqlite_sequence where name="Product"

Returns the following:

name     seq
Product  3
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement