SQL Server: Tips and Tricks - 2 (2017)
How to create Not Null Constraint on Column in SQL Server Table
You are creating customer table for one of your requirement, you want to make sure the First name Column always have the value. How will you make sure First Name Column always have the value?
Constraints defined rules which make sure the data we insert in column follow the rules.
For above requirement we can create Not Null constraint on a column, Not Null Constraint make sure the value inserted in that column is not null. If user will try to insert row without providing the value for the column on which we have created the Not Null Constraint, The insert will fail as column cannot accept Null values.
To create Not Null Constraint on Column in a Table, we have to Add Not Null after the Data Type as shown below for First Name Column.
Create Table Customer
(FirstName VARCHAR(50) Not Null,
You can see that I did not provide Not Null Constraint for other columns, that means those column can accept Null values or Unknown value.
Let's insert below rows and see what happen
insert into dbo.Customer ( FirstName,LastName,Age,PhoneNumber,DOB,Gender)
As you can see that the transaction failed as we can't insert the Null in First Name column, No Record will be inserted.
Let's consider second Insert, Where we are not inserting anything in First Name column. Still the insert will fail, as when you don't provide the column in insert list, it try to insert Null value for that column and we have created Not Null Constraint on First Name column.
insert into dbo.Customer (LastName,Age,PhoneNumber,DOB,Gender)