Set a column default
New defaults change what future INSERTs write without touching existing rows. Each engine applies them a little differently; SQL Server is the odd one with named constraints.
The task
From now on, INSERTs that omit the column should fall back to a sensible value rather than NULL or an error.
The snippet
Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.
ALTER TABLE users
ALTER COLUMN is_active SET DEFAULT true;
它的運作方式
The default applies to rows inserted after this statement; existing rows keep their values, and the change is catalog-only on PostgreSQL even for big tables. Re-running SET DEFAULT just overwrites the default with the same value. The default can be a literal or an expression, including volatile ones such as now() or gen_random_uuid(), which are evaluated separately for each inserted row.
Variations
SQL Server
SQL Server-- a default is a named constraint; a column can have only
-- one, so drop an existing one first (see remove-column-default)
IF NOT EXISTS (SELECT 1 FROM sys.default_constraints
WHERE name = 'DF_Users_IsActive')
ALTER TABLE dbo.Users
ADD CONSTRAINT DF_Users_IsActive DEFAULT 1 FOR IsActive;
MySQL
MySQLALTER TABLE users
ALTER COLUMN is_active SET DEFAULT 1;
-- expression defaults need parentheses (MySQL 8.0.13+):
-- ALTER TABLE users ALTER COLUMN token SET DEFAULT (UUID());
SQLite
SQLite-- defaults live in the column definition and SQLite has no
-- ALTER COLUMN, so rebuild the table: run
-- PRAGMA foreign_keys = OFF first (it is ignored inside a
-- transaction), then BEGIN and:
-- 1) CREATE TABLE users_new with the default in the column
-- 2) INSERT INTO users_new SELECT * FROM users
-- 3) DROP TABLE users; ALTER TABLE users_new RENAME TO users
-- 4) recreate indexes and triggers, COMMIT, then
-- PRAGMA foreign_keys = ON
Questions that come up
Why didn't my default appear on existing rows?
A default only fills in for INSERTs that omit the column; an INSERT that passes NULL explicitly still stores NULL. To backfill, run an UPDATE setting the column where it IS NULL, which is also the first step of the make-column-not-null recipe.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.