Curriculum
Course: SQL
Login

Curriculum

SQL

SQL References

0/80

MySQL Functions

0/139

SQL Server Functions

0/84

SQL Quick Ref

0/1
Text lesson

SQL DEFAULT

SQL DEFAULT Constraint

The DEFAULT constraint sets a predefined value for a column.

This value will be assigned to all new records in the absence of any other specified value.

SQL DEFAULT on CREATE TABLE

This SQL statement assigns a DEFAULT value to the “City” column during the creation of the “Persons” table.

My SQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Age int,
    City varchar(255) DEFAULT ‘Sandnes’
); 

The DEFAULT constraint can also insert system values, achieved by utilizing functions such as GETDATE().

CREATE TABLE Orders (
    ID int NOT NULL,
    OrderNumber int NOT NULL,
    OrderDate date DEFAULT GETDATE()
); 

SQL DEFAULT on ALTER TABLE

If you need to establish a DEFAULT constraint on the “City” column after the table has already been created, utilize the following SQL statement:

MySQL:

ALTER TABLE Persons
ALTER City SET DEFAULT ‘Sandnes’

SQL Server:

ALTER TABLE Persons
ADD CONSTRAINT df_City
DEFAULT ‘Sandnes’ FOR City; 

MS Access:

ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT ‘Sandnes’

Oracle:

ALTER TABLE Persons
MODIFY City DEFAULT ‘Sandnes’

DROP a DEFAULT Constraint

To remove a DEFAULT constraint, utilize the following SQL statement:

MySQL:

ALTER TABLE Persons
ALTER City DROP DEFAULT

SQL Server / Oracle / MS Access:

ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT

SQL Server:

ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT