Skip to content

SQL DEFAULT Constraint

DEFAULT gives a column a value to use whenever an insert leaves it out. A value the insert does give always wins.

Most of the company’s productions are made in the UK, so that can be the default country:

CREATE TABLE Productions (
ProductionID int PRIMARY KEY,
Title varchar(200) NOT NULL,
Format varchar(50) NOT NULL,
Country varchar(50) DEFAULT 'UK'
);
INSERT INTO Productions (ProductionID, Title, Format)
VALUES (2, 'Quarry Lane', 'Feature film');
ProductionID Title Format Country
2 Quarry Lane Feature film UK

Without the default, Country would have been NULL.

A default can be worked out at the moment of the insert. To stamp each invoice with the day it was entered, unless a date is given:

InvoiceDate date NOT NULL DEFAULT CURRENT_DATE

CURRENT_DATE is the standard spelling, used by PostgreSQL and SQLite. Other databases differ:

Database Default of today’s date
PostgreSQL, SQLite DEFAULT CURRENT_DATE
MySQL 8.0.13 and later DEFAULT (CURRENT_DATE), with the brackets
SQL Server DEFAULT CAST(GETDATE() AS date)
Oracle DEFAULT TRUNC(SYSDATE)

Adding or changing a default is written differently in each database. To make 'UK' the default country:

Database Statement
PostgreSQL, MySQL ALTER TABLE Productions ALTER COLUMN Country SET DEFAULT 'UK';
SQL Server ALTER TABLE Productions ADD CONSTRAINT DF_Country DEFAULT 'UK' FOR Country;
Oracle ALTER TABLE Productions MODIFY Country DEFAULT 'UK';

A new default applies to rows inserted from then on. Existing rows keep whatever value they already have.