Newbie101
Newbie101

Reputation: 501

How to auto increment the primary key?

I have this sql query to create my Penguin table

CREATE TABLE Penguin (
PenguinID INTEGER PRIMARY KEY,
Name VARCHAR(10),
Height FLOAT,
Weight FLOAT)

But then when I do INSERT INTO Penguin (Name, Height, Weight) VALUES (?,?,?) only the name, height and weight are added, and the PenguinID column is NULL

Upvotes: 0

Views: 41

Answers (2)

Barbaros Özhan
Barbaros Özhan

Reputation: 65158

just add AUTOINCREMENT besides the definition of the column within the CREATE TABLE statement as

PenguinID INTEGER PRIMARY KEY AUTOINCREMENT

Demo

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269503

Because of some strange defaults in SQLite, it does this automatically. You can see here.

What is happening is that all tables have a rowid column that is auto-incremented. An integer primary key is automatically a synonym for rowid, so it gets incremented. This is explained in the documentation.

Don't get used to this behavior, because it is peculiar to SQLite. You can define the column as autoincrement, although that adds a tad of overhead.

Upvotes: 2

Related Questions