Tutorials References Menu

MySQL Tutorial

MySQL HOME MySQL Intro MySQL RDBMS

MySQL SQL

MySQL SQL MySQL SELECT MySQL WHERE MySQL AND, OR, NOT MySQL ORDER BY MySQL INSERT INTO MySQL NULL Values MySQL UPDATE MySQL DELETE MySQL LIMIT MySQL MIN and MAX MySQL COUNT, AVG, SUM MySQL LIKE MySQL Wildcards MySQL IN MySQL BETWEEN MySQL Aliases MySQL Joins MySQL INNER JOIN MySQL LEFT JOIN MySQL RIGHT JOIN MySQL CROSS JOIN MySQL Self Join MySQL UNION MySQL GROUP BY MySQL HAVING MySQL EXISTS MySQL ANY, ALL MySQL INSERT SELECT MySQL CASE MySQL Null Functions MySQL Comments MySQL Operators

MySQL Database

MySQL Create DB MySQL Drop DB MySQL Create Table MySQL Drop Table MySQL Alter Table MySQL Constraints MySQL Not Null MySQL Unique MySQL Primary Key MySQL Foreign Key MySQL Check MySQL Default MySQL Create Index MySQL Auto Increment MySQL Dates MySQL Views

MySQL References

MySQL Data Types MySQL Functions

MySQL Examples

MySQL Examples

MySQL DEFAULT Constraint


MySQL DEFAULT Constraint

The DEFAULT constraint is used to set a default value for a column.

The default value will be added to all new records, if no other value is specified.


DEFAULT on CREATE TABLE

The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created:

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 be used to insert system values, by 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 create a DEFAULT constraint on the "City" column when the table is already created, use the following SQL:

ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';

DROP a DEFAULT Constraint

To drop a DEFAULT constraint, use the following SQL:

ALTER TABLE Persons
ALTER City DROP DEFAULT;