How to create a table in SQLite
Create a table in SQLite, with IF NOT EXISTS, primary keys, foreign keys and defaults, and when you need AUTOINCREMENT instead of INTEGER PRIMARY KEY.
Quick Answer
Use CREATE TABLE, and add IF NOT EXISTS so it doesn't fail when the table is already there. An INTEGER PRIMARY KEY column numbers new rows for you:
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO users (email, name) VALUES ('ada@example.com', 'Ada'); -- id = 1
You usually don't need AUTOINCREMENT. Add it only when an id must never be reused after its row is deleted.
INTEGER PRIMARY KEY, AUTOINCREMENT and rowid
Every ordinary SQLite table has a hidden 64-bit rowid. A column declared exactly INTEGER PRIMARY KEY becomes another name for it, so id, rowid, oid and _rowid_ all return the same number. Leave it out of an INSERT, or insert NULL, and SQLite uses the largest rowid in the table plus one.
That means a deleted id can come back. AUTOINCREMENT prevents it by recording the highest id ever used in the sqlite_sequence table. Here three rows were inserted, the last one deleted, and a fourth inserted:
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT);
CREATE TABLE logs (id INTEGER PRIMARY KEY AUTOINCREMENT, msg TEXT);
-- insert 3 rows into each, delete id 3, insert one more
INTEGER PRIMARY KEY | INTEGER PRIMARY KEY AUTOINCREMENT | |
|---|---|---|
| After deleting the newest row | Next id is 3 again | Next id is 4 |
| After deleting every row | Starts again at 1 | Carries on from the highest id (5 in our test) |
| When the id reaches 9223372036854775807 | Picks an unused id at random | Fails with database or disk is full |
| Extra cost | None | Updates sqlite_sequence on every insert |
Use AUTOINCREMENT when old ids might be stored somewhere else, such as in logs, URLs or another system, and a reused id would point at the wrong row. Otherwise plain INTEGER PRIMARY KEY is simpler and faster. AUTOINCREMENT only works on that exact column type:
sqlite> CREATE TABLE e (id INT PRIMARY KEY AUTOINCREMENT);
Parse error: AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY
In VisuaLeaf
Create a table in a form in VisuaLeaf
Open the .db file in VisuaLeaf, right-click the database in the sidebar and choose New Table. Add columns with SQLite's types, set defaults and nullability, choose the primary key, and add foreign keys and indexes in their own grids. The live preview shows the CREATE TABLE statement as you go, so you can check it reads INTEGER PRIMARY KEY rather than INT PRIMARY KEY, a difference explained in the findings below. To paste a statement you already have, switch to Script mode.
After you create it, the new table opens in the same tab and is highlighted in the sidebar. Show DDL gives you its full definition to copy into a migration. See Table Management.

What we found testing this
INT PRIMARY KEYis notINTEGER PRIMARY KEY. Only the exact wordINTEGERmakes the column an alias for the rowid. Withid INT PRIMARY KEY, two inserts that left outidboth storedNULL, whilerowidwas 1 and 2.BIGINT PRIMARY KEYdid the same, and SQLite added a separatesqlite_autoindexfor each. Both happened in better-sqlite3 (3.49.2) as well.- A TEXT primary key accepts NULL, more than once.
code TEXT PRIMARY KEYstored two rows with a NULL code and no error. SQLite keeps this old behaviour for compatibility. AddNOT NULL, or useWITHOUT ROWID, which refused the NULL withNOT NULL constraint failed: w.code. INTEGER PRIMARY KEY DESCisn't an alias either. The insert gaverowid1 and leftidNULL.VACUUMrenumbers tables without an INTEGER PRIMARY KEY. A table with only abodycolumn had rowids 3 and 4 after two deletes. AfterVACUUMthey were 1 and 2. The same rows in a table withid INTEGER PRIMARY KEYkept 3 and 4. Never store a bare rowid as a reference.- IF NOT EXISTS doesn't compare the definition.
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, totally_different TEXT)succeeded silently and left the old table as it was. Use migrations, not IF NOT EXISTS, to change a schema. - CREATE TABLE ... AS SELECT drops every constraint. Copying a table with a primary key, NOT NULL, UNIQUE and a default produced
CREATE TABLE users_copy(id INT, email TEXT, created_at NUM, active NUM): no keys, no defaults, andid INT, which isn't a rowid alias. - Foreign keys are on in better-sqlite3 and off elsewhere.
PRAGMA foreign_keysreturned 0 in the sqlite3 shell and Python, and 1 in better-sqlite3. With it off, an order for a user that didn't exist was inserted without complaint. - AUTOINCREMENT costs a little. 200,000 inserts in one transaction, in memory from Python, took 0.136 s with
INTEGER PRIMARY KEYand 0.176 s withAUTOINCREMENT, best of three runs.
Foreign keys, CHECK and defaults
PRAGMA foreign_keys = ON; -- once per connection
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
total INTEGER NOT NULL CHECK (total >= 0), -- cents
status TEXT NOT NULL DEFAULT 'new'
);
CREATE INDEX IF NOT EXISTS orders_user_id ON orders(user_id);
With foreign keys on, an order for a user that doesn't exist fails with FOREIGN KEY constraint failed. SQLite doesn't index foreign key columns for you, so add the index yourself, or every delete from users scans orders. For the error itself, see FOREIGN KEY constraint failed.
A default that calls a function needs parentheses, such as DEFAULT (unixepoch()). CURRENT_TIMESTAMP is the exception. Declared types are mostly advice in SQLite; to have them enforced, end the statement with STRICT, as explained in SQLite data types.
Composite primary keys and WITHOUT ROWID
For a key made of two columns, list them in a table-level PRIMARY KEY. A join table like this is a good fit for WITHOUT ROWID, which stores rows by the primary key instead of a hidden rowid:
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders(id),
product_id INTEGER NOT NULL,
qty INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (order_id, product_id)
) WITHOUT ROWID;
Inserting the same pair twice failed with UNIQUE constraint failed: order_items.order_id, order_items.product_id. A WITHOUT ROWID table must have a primary key, can't use AUTOINCREMENT, and has no rowid column: selecting it gave no such column: rowid.
Check the table you created
sqlite> .schema orders
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
total INTEGER NOT NULL CHECK (total >= 0),
status TEXT NOT NULL DEFAULT 'new'
);
CREATE INDEX orders_user_id ON orders(user_id);
SQLite saves the statement as you wrote it, without the IF NOT EXISTS. For column details as rows, use PRAGMA table_info('orders'), covered in describing a table.
From Python and Node
import sqlite3
conn = sqlite3.connect("app.db")
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT
)""")
cur = conn.execute("INSERT INTO users (email, name) VALUES (?, ?)", ("ada@example.com", "Ada"))
print(cur.lastrowid) # 1
# SQLite 3.35+: get the new id back from the INSERT itself
row = conn.execute("INSERT INTO users (email) VALUES (?) RETURNING id", ("bob@example.com",)).fetchone()
conn.commit()
const Database = require('better-sqlite3')
const db = new Database('app.db')
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT
)
`)
const info = db.prepare('INSERT INTO users (email, name) VALUES (?, ?)').run('ada@example.com', 'Ada')
// { changes: 1, lastInsertRowid: 1 }
lastrowid and lastInsertRowid return the rowid. That's your id only when the id column is INTEGER PRIMARY KEY. With INT PRIMARY KEY the rowid was 1 and the id column was NULL.
Frequently Asked Questions
How do I create a table only if it does not exist in SQLite?
CREATE TABLE IF NOT EXISTS users (...); does nothing when a table with that name exists. It does not check that the existing table has the same columns.
How do I make an auto increment id in SQLite?
Declare the column id INTEGER PRIMARY KEY and leave it out of your INSERT statements. SQLite assigns the next number. Add AUTOINCREMENT only if deleted ids must never be reused.
What is the difference between INTEGER PRIMARY KEY and AUTOINCREMENT in SQLite?
Both number rows automatically. Without AUTOINCREMENT, SQLite uses the largest current id plus one, so the id of a deleted last row can be reused. AUTOINCREMENT tracks the highest id ever used in sqlite_sequence and never reuses one.
What is rowid in SQLite?
A hidden 64-bit integer key on every table that is not WITHOUT ROWID. A column declared INTEGER PRIMARY KEY becomes an alias for it. Without that alias, VACUUM can renumber the rowids.