Understanding DEFAULT Constraints in SQL: A Complete Guide
Table of Content:
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not provide a specific value.
Syntax: Altering an existing column to add a default constraint:
ALTER TABLE { TABLE_NAME } ADD CONSTRAINT { CONSTRAINT_NAME } DEFAULT { DEFAULT_VALUE } FOR { EXISTING_COLUMN_NAME }
Syntax: Adding a new column, with default value, to an existing table:
ALTER TABLE { TABLE_NAME } ADD { COLUMN_NAME } { DATA_TYPE } { NULL | NOT NULL } CONSTRAINT { CONSTRAINT_NAME } DEFAULT { DEFAULT_VALUE }
Example
For example, the following SQL creates a new table called "Customers" and adds five columns. Here, the SALARY column is set to 10000.00 by default, so in case the INSERT INTO statement does not provide a value for this column, then by default this column would be set to 10000.00.
CREATE TABLE Customers( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25) , SALARY DECIMAL (18, 2) DEFAULT 10000.00, PRIMARY KEY (ID) );
If the CUSTOMERS table has already been created, then to add a DEFAULT constraint to the SALARY column, you would write a query like the one which is shown in the code block below.
ALTER TABLE Customers
MODIFY SALARY DECIMAL (18, 2) DEFAULT 10000.00;
Drop Default Constraint
To drop a DEFAULT constraint, use the following SQL query.
ALTER TABLE Customers ALTER COLUMN SALARY DROP DEFAULT;
The DEFAULT constraint is used to provide a default value for a column. The default value will be added to all new records IF no other value is specified.
Example for Default Constraints
Get the TablePerson from this tutorial
Code: The following command will add a default constraint, DF_TablePerson_GenderID.
ALTER TABLE TablePerson ADD CONSTRAINT DF_TablePerson_GenderID DEFAULT 1 FOR GenderID
The insert statement below does not provide a value for GenderId column, so the default of 1 will be inserted for this record.
Code:
Insert into TablePerson(ID,Name,Email) values(5,'Sam','s@s.com')
On the other hand, the following insert statement will insert NULL, instead of using the default.
Code: SQL Server
Insert into TablePerson(ID,Name,Email,GenderID) values (6,'Dan','d@d.com',NULL)
To drop a constraint
Code: SQL Server
ALTER TABLE { TABLE_NAME } DROP CONSTRAINT { CONSTRAINT_NAME }