DEFAULT constraint in SQL Server

This is the *simplest* constraint of all other constraints to explain, DEFAULT constraint will set a default value for a column if a value is not specified for the column.

How do we declare a default constraint?

  • While declaring a table
CREATE TABLE People (
    ID int NOT NULL,
    FirstName varchar(255),
    City varchar(255) DEFAULT 'Chennai'
);
--The below insert operation is not specified any value for City, but SQL Server uses default value 'Chennai'
Insert into People(ID,FirstName) Values(1,'Latheesh NK')

--The below insert specified a value for City
Insert into People(ID,FirstName,City) Values(2,'NK Latheesh','Cochin')

Select * from People

Drop Table People
  • Altering an existing table

ALTER TABLE SomeTable
        ADD SomeCol Bit NULL --Or NOT NULL.
 CONSTRAINT D_SomeTable_SomeCol --When Omitted a Default-Constraint Name is autogenerated.
    DEFAULT (0)--Optional Default-Constraint.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records.

Notes:

Optional Constraint Name:
If you leave out CONSTRAINT D_SomeTable_SomeCol then SQL Server will autogenerate
    a Default-Contraint with a funny Name like: DF__SomeTa__SomeC__4FB7FEF6

Optional With-Values Statement:
The WITH VALUES is only needed when your Column is Nullable and you want the Default Value used for Existing records.
If your Column is NOT NULL, then it will automatically use the Default Value for all Existing Records, whether you specify WITH VALUES or not.

How Inserts work with a Default-Constraint:
If you insert a Record into SomeTable and do not Specify SomeCol‘s value, then it will Default to 0.
If you insert a Record and Specify SomeCol‘s value as NULL (and your column allows nulls), then the Default-Constraint will not be used and NULL will be inserted as the Value.

If you want to add multiple columns you can do it this way for example:

ALTER TABLE YourTable
    ADD Column1 INT NOT NULL DEFAULT 0,
        Column2 INT NOT NULL DEFAULT 1,
        Column3 VARCHAR(50) DEFAULT 'Hello'

Can we drop a DEFAULT constraint?

Yes, we can very well DROP a default constraint.

Can we disable/enable DEFAULT constraint?

No, we cannot disable/enable default constraint, we can only drop and recreate default constraint in SQL Server.

If you enjoyed this blog post, feel free to share it with your friends!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s