Default Constraint in SQL Server

With the help of default constraint in SQL Server, you can set the default value to the column. so whenever you are inserting some records to the table and you want some column to take default value ever after you are not inserting the value to that column then use default constraint.

Below is the example of Default constraint in SQL.

CREATE TABLE [dbo].[Employee](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [Address] [varchar](200) NOT NULL,    
    [Country] [varchar](50) NOT NULL,
 CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)
WITH 
(PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, 
ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

alter table Employee add constraint dt_Country default 'USA' for Country

INSERT INTO Employee(Name,Address) values('John','10th Main Street')
INSERT INTO Employee(Name,Address) values('Sonny','New York')
INSERT INTO Employee(Name,Address) values('Erric','Alabama')
INSERT INTO Employee(Name,Address,Country) values('Erric','Mumbai','India')

select * from Employee

visit below sqlfiddle for above example :

http://sqlfiddle.com/#!3/4ad81/1

Leave a Reply