← Back to SQL, page 9

sql-0180 · Easy fresher

What does a DEFAULT clause do, and what value does a column get when an INSERT omits it without a default?

DEFAULT supplies a value when the INSERT does not mention the column, such as DEFAULT 'pending' or DEFAULT CURRENT_TIMESTAMP. Without a default, the column gets NULL, and if it is NOT NULL the insert fails. An explicit NULL in the INSERT overrides the default.

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;
idstatushas_creatednote
1pending1NULL
2NULL1NULL

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 purpose
text
Error: NOT NULL constraint failed: t2.status

CURRENT_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