Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into sqlite table that contains only one column with auto-incremental primary key?

I would like to have in sqlite a "counter" table that always give me a new unique ID. I have managed what I need in the following way. First, I create the following table:

cursor.execute('''create table second (id integer primary key autoincrement, age integer)''')

Then I perform the following sequence of commands:

cursor.execute('''insert into second (age) values (1)''')
cursor.lastrowid

Each time when I execute the above two columns I get a new integer. It is exactly what I need. However, the above solution is not elegant since I use a column ("age") that I do not really need. The reason I used is following. I can create a table that contains only one column with the IDs:

cursor.execute('''create table first (id integer primary key autoincrement)''')

However, the problem is that I cannot manage to insert into this table. The following does not work:

cursor.execute('''insert into first () values ()''')

I get the following error message:

sqlite3.OperationalError: near ")": syntax error

Does anybody knows how to solve the described problem?

like image 346
Roman Avatar asked Nov 02 '25 15:11

Roman


2 Answers

This should work:

sqlite> CREATE TABLE first (id integer primary key autoincrement);
sqlite> INSERT INTO first (id) VALUES (null);
sqlite> SELECT * FROM first;
1
sqlite> INSERT INTO first (id) VALUES (null);
sqlite> SELECT * FROM first;
1
2
like image 87
Gabi Purcaru Avatar answered Nov 04 '25 06:11

Gabi Purcaru


The documentation says:

If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically.

So you can either explicitly specify NULL:

INSERT INTO first(id) VALUES(NULL)

or specify no value at all:

INSERT INTO first DEFAULT VALUES
like image 25
CL. Avatar answered Nov 04 '25 06:11

CL.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!