Curriculum
Course: MYSQL
Login

Curriculum

MYSQL

MySQL References

0/140
Text lesson

MySQL DEFAULT

MySQL DEFAULT Constraint

The DEFAULT constraint sets a default value for a column.

This default value is assigned to new records if no other value is specified during insertion.

DEFAULT on CREATE TABLE

The following SQL statement assigns a DEFAULT value to the “City” column during the creation of the “Persons” table:

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

The DEFAULT constraint can also be utilized to insert system values, such as using functions like CURRENT_DATE().

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

DEFAULT on ALTER TABLE

To add a DEFAULT constraint to the “City” column in an existing table, use the following SQL:

ALTER TABLE Persons
ALTER City SET DEFAULT ‘Sandnes’;

DROP a DEFAULT Constraint

To remove a DEFAULT constraint, use the following SQL:

ALTER TABLE Persons
ALTER City DROP DEFAULT;