// SQL snippet

Remove a column default

Removing a default is the reverse of setting one: future inserts must supply the value explicitly or get NULL. The mechanics differ most on SQL Server, where the default is a named constraint you must find first.

Main statement
PostgreSQL
다음도 지원
SQL Server MySQL SQLite

The task

Application code now always supplies the value, so the lingering default only hides bugs by filling in omitted inserts. SQL Server makes this a two-step job because its defaults are named objects.

The snippet

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

PostgreSQL
ALTER TABLE users
  ALTER COLUMN is_active DROP DEFAULT;

작동 방식

DROP DEFAULT removes the value used for omitted inserts but changes no existing rows, and the statement is catalog-only. On PostgreSQL an omitted column then gets NULL, so inserts that skip a NOT NULL column start failing. Check for INSERT paths that omit the column before removing the default. Re-running is harmless: dropping an absent default is a no-op.

Variations

SQL Server

SQL Server
-- look up the (often system-generated) constraint name first
DECLARE @df sysname, @sql nvarchar(400);
SELECT @df = dc.name
FROM sys.default_constraints dc
JOIN sys.columns c ON c.object_id = dc.parent_object_id
                  AND c.column_id = dc.parent_column_id
WHERE dc.parent_object_id = OBJECT_ID('dbo.Users')
  AND c.name = 'IsActive';
IF @df IS NOT NULL
BEGIN
    SET @sql = N'ALTER TABLE dbo.Users DROP CONSTRAINT ' + QUOTENAME(@df);
    EXEC sp_executesql @sql;
END;

MySQL

MySQL
ALTER TABLE users
  ALTER COLUMN is_active DROP DEFAULT;
-- in strict mode this makes even a nullable column mandatory
-- in INSERTs; to keep omitted inserts storing NULL, use
-- ALTER TABLE users ALTER COLUMN is_active SET DEFAULT NULL;

SQLite

SQLite
-- defaults are part of the column definition; rebuild the
-- table with the new definition (see set-column-default)

Questions that come up

What is the difference between DROP DEFAULT and setting NULL?

On PostgreSQL there is none: a column without a default behaves as DEFAULT NULL. On MySQL they differ. After DROP DEFAULT the column has no default at all, and in strict mode an INSERT that omits it fails with error 1364 even if the column is nullable; SET DEFAULT NULL keeps those inserts working and stores NULL. MySQL rejects SET DEFAULT NULL on a NOT NULL column.

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.