DEFAULT gives a column a value to use whenever an insert leaves it out. A value the insert does give always wins.
A fixed default
Section titled “A fixed default”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.
Today’s date
Section titled “Today’s date”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_DATECURRENT_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) |
On an existing table
Section titled “On an existing table”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.