Sql Server

SQL | NOT NULL Constraint

SQL | NOT NULL Constraint

SQL | NOT NULL Constraint

This constraint tells that we cannot store a null value in a column. That is, if a column is specified as NOT NULL then we will not be able to store null in this particular column any more.
By default, if you don’t specify the NOT NULL constraint, SQL Server will allow the column to accepts NULL.


Add Not Null constraintIn New Table

CREATE TABLE Employee(
    person_id INT IDENTITY PRIMARY KEY,
    first_name VARCHAR(255) NOT NULL,
    last_name VARCHAR(255) NOT NULL,   
email VARCHAR(255) NOT NULL,
    phone VARCHAR(20)
);





Add NOT NULL constraint to an existing column
First, update the table so there is no NULL in the column:

UPDATE Employee SET phone = '0000000000' WHERE phone IS NULL;


alter the table to change the property of the column:

ALTER TABLE Employee
ALTER COLUMN email VARCHAR(255) NOT NULL;




Removing NOT NULL constraint

ALTER TABLE Employee
ALTER COLUMN phone VARCHAR(20) NULL;





Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram