Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use one sequence for all table in sqlite

When I'm creating tables in an SQLite database, separate sequences are automatically created for each table.

However I want to use one sequence for all tables in my SQLite database and also need to set min and max values (e.g. min=10000 and max=999999) of that sequence (min and max means start value of sequence and maximum value that sequence can increment).

I know this can be done in an Oracle database, but don't know how to do it in SQLite.

Is there any way to do this?

like image 254
Bishan Avatar asked Feb 27 '13 05:02

Bishan


People also ask

Can we use same sequence for multiple tables?

Show activity on this post. I found the answer: "Sequence numbers are generated independently of tables, so the same sequence can be used for one or for multiple tables."

Does SQLite support sequences?

It lacks built-in sequence support. It doesn't provide ways to store data outside a running transaction.

Does SQLite have auto increment?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment. The keyword AUTOINCREMENT can be used with INTEGER field only.


1 Answers

Unfortunately, you cannot do this: SQLite automatically creates sequences for each table in special sqlite_sequence service table.

And even if you somehow forced it to take single sequence as source for all your tables, it would not work the way you expect. For example, in PostgreSQL or Oracle, if you set sequence to value say 1 but table already has filled rows with values 1,2,..., any attempt to insert new rows using that sequence as a source would fail with unique constraint violation.

In SQLite, however, if you manually reset sequence using something like:

UPDATE sqlite_sequence SET seq = 1 WHERE name = 'mytable'

and you already have rows 1,2,3,..., new attempts to insert will NOT fail, but automatically assign this sequence maximum existing value for appropriate auto-increment column, so it can keep going up.

Note that you can use this hack to assign starting value for the sequence, however you cannot make it stop incrementing at some value (unless you watch it using other means).

like image 146
mvp Avatar answered Sep 21 '22 12:09

mvp