In this tutorial, we will learn how to use DEFAULT constraint using SQL.
SQL DEFAULT constraint is used to provide a default value for a column if no specific value is provided in the INSERT INTO statement.
CREATE TABLE Employee(
ID int NOT NULL,
EmpName varchar(255) NOT NULL,
City varchar(255) DEFAULT 'Not Specified',
Country int,
Salary Decimal(18,2) DEFAULT '0.00'
);
To add a DEFAULT constraint on the column "City" when the table is already created, the statement is as follow:
ALTER TABLE Employee
ADD CONSTRAINT df_City
DEFAULT 'Not Specified' FOR City;
ALTER TABLE Employee
ALTER City SET DEFAULT 'Not Specified';
ALTER TABLE Employee
MODIFY City DEFAULT 'Not Specified';
To DROP a DEFAULT constraint, a query is as follow:
To drop a constraint when you know the name of DEFAULT constraint, a query is as follow:
ALTER TABLE tableName
DROP CONSTRAINT constraintName;
ALTER TABLE Employee
DROP CONSTRAINT df_City;
ALTER TABLE Employee
ALTER COLUMN City DROP DEFAULT;
ALTER TABLE Employee
ALTER City DROP DEFAULT;