Full answer
sql
CREATE TABLE tickets (
id INTEGER PRIMARY KEY,
status TEXT DEFAULT 'pending',
created TEXT DEFAULT CURRENT_TIMESTAMP,
note TEXT
);
INSERT INTO tickets (id) VALUES (1);
INSERT INTO tickets (id, status) VALUES (2, NULL);
SELECT id, status, created IS NOT NULL AS has_created, note FROM tickets ORDER BY id;| id | status | has_created | note |
|---|---|---|---|
| 1 | pending | 1 | NULL |
| 2 | NULL | 1 | NULL |
Row 1 omitted status and created, so both defaults applied. note has no default and became NULL. Row 2 passed NULL for status explicitly, and the default did not apply.
If the column is NOT NULL, the explicit NULL is an error instead:
sql
CREATE TABLE t2 (id INTEGER PRIMARY KEY, status TEXT NOT NULL DEFAULT 'pending');
INSERT INTO t2 (id, status) VALUES (1, NULL);
-- error on purposetext
Error: NOT NULL constraint failed: t2.statusCURRENT_TIMESTAMP in SQLite is UTC text. PostgreSQL's now() returns the transaction start time as timestamptz.
sql
CREATE TABLE tickets (
id INTEGER PRIMARY KEY,
status TEXT DEFAULT 'pending',
created TEXT DEFAULT CURRENT_TIMESTAMP,
note TEXT
);
INSERT INTO tickets (id) VALUES (1);
INSERT INTO tickets (id, status) VALUES (2, NULL);
SELECT id, status, created IS NOT NULL AS has_created, note FROM tickets ORDER BY id;
-- error on purpose
CREATE TABLE t2 (id INTEGER PRIMARY KEY, status TEXT NOT NULL DEFAULT 'pending');
INSERT INTO t2 (id, status) VALUES (1, NULL);Checked on SQLite 3.46.1, run twice with identical output.
Key points
- DEFAULT applies only when the column is omitted
- An explicit NULL overrides the default
- No default means NULL, or an error if NOT NULL
- CURRENT_TIMESTAMP gives a creation time
Common mistakes
- Sending NULL from an ORM and expecting the default
- Assuming a default is applied on UPDATE
Follow-ups
- How would you keep an updated_at column current?
- What does INSERT ... DEFAULT VALUES do?
Tips
- Show omitted versus explicit NULL