How to set default value in a column in Database tableIntroduction
Sometimes we need to set some default value in a column in a table when a row is created and we don't actually want to pass value to this column.
Here is code to set default value.
To set default value while creating new table
CREATE TABLE myTable
(
EmpId int NOT NULL PRIMARY KEY,
FirstName varchar(50) NOT NULL,
EmpLastName varchar(50),
ProjectId INT,
IsActive INT DEFAULT 1
)
In the code above I have set default value for IsActive column. So when ever a row is created and user dont pass any data to this column value 1 will be automatically assigned to it.
To set default value on an existing column, do the following
ALTER TABLE myTable ADD CONSTRAINT IsActive_def DEFAULT 1 FOR IsActive
Here in the code above I have created a constraint IsActive_def on IsActive column and set default value 1.