// SQL snippet

Change a column to nullable

Relaxing a column to allow NULLs is the safe direction: no data can violate it. The work is in the application code that suddenly has to handle NULL.

Main statement
PostgreSQL
还支持
SQL Server MySQL SQLite

The task

A field that used to be mandatory now legitimately has no value for some rows, so the constraint must be relaxed without a data check or a long lock.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.

PostgreSQL
ALTER TABLE orders
  ALTER COLUMN discount_code DROP NOT NULL;

工作原理

DROP NOT NULL is catalog-only on PostgreSQL regardless of table size, because allowing NULLs needs no check of existing rows. The cost lands in the code that reads the column: arithmetic and || concatenation with a NULL return NULL, WHERE discount_code <> 'X' silently skips NULL rows, aggregates such as SUM and COUNT(col) ignore them, and ORM models need the field marked optional.

Variations

SQL Server

SQL Server
ALTER TABLE dbo.Orders
    ALTER COLUMN DiscountCode NVARCHAR(50) NULL;
-- restating the type is required on SQL Server

MySQL

MySQL
ALTER TABLE orders
  MODIFY COLUMN discount_code VARCHAR(50) NULL;
-- restate the default and comment too; InnoDB rebuilds the
-- table in place for this change

SQLite

SQLite
-- SQLite cannot alter nullability in place; rebuild the
-- table with the column declared nullable

Questions that come up

Can I roll this back later?

Yes, in the NOT NULL direction, but that needs the check-backfill-enforce sequence from the make-column-not-null recipe because NULLs may have appeared since. Relax first, tighten only after code guarantees a value.

Keep reading

// snippets are better with a schema brain

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.