SQL Tutorial - Default Constraint


'Default Constraint' is used to insert a default value in one or more columns in a table during insertion if no specific value has been given.

Default Constraint


The 'Default Constraint' is normally used to enter system generated values like current date, standard discount rate for your customers when not explicitly given etc.

SQL 'Default Constraint' Syntax


CREATE Table tablename
(
column1 datatype PRIMARY KEY,
column2 datatype,
column3 datatype DEFAULT GETDATE(),
column4 datatype,
.
.
.
columnn datatype
)

The above method of creating a table creates an 'Default' constraint on column is shown.

The Default Constraint Example


CREATE TABLE Employees
(
EmployeeID smallint PRIMARY KEY,
EmployeeName nvarchar(50) NOT NULL,
DateOfBirth smalldatetime NOT NULL,
DesignationID smallint NULL,
DeptID smallint NULL,
PhoneNo nvarchar(12) NULL,
City nvarchar(50) NOT NULL,
Salary decimal(5, 2) DEFAULT 450.00
)

Note: When creating the columns, the data type of the column must be given so that you know what datatype it holds. If it's a non integer, you need to specify the length of the column also. Here we are ensuring that when the salary column doesnt have a specific value while being inserted, it will default to $450.