Open In App

SQL NOT NULL Constraint

Improve
Improve
Like Article
Like
Save
Share
Report

Pre-requisite: NULL Values in SQL

The SQL NOT NULL forces particular values or records should not to hold a null value. It is somewhat similar to the primary key condition as the primary key can’t have null values in the table although both are completely different things.

In SQL, constraints are some set of rules that are applied to the data type of the specified table, Or we can say that using constraints we can apply limits on the type of data that can be stored in the particular column of the table.

Constraints are typically placed specified along with CREATE statement. By default, a column can hold null values.

Query:

CREATE TABLE Emp(
    EmpID INT PRIMARY KEY,
    Name VARCHAR(50),
    Country VARCHAR(50),
    Age int(2),
  Salary int(10)
);

Output:

 

If you don’t want to have a null column or a null value you need to define constraints like NOT NULL. NOT NULL constraints make sure that a column does not hold null values, or in other words, NOT NULL constraints make sure that you cannot insert a new record or update a record without entering a value to the specified column(i.e., NOT NULL column).

It prevents for acceptance of NULL values. It can be applied to column-level constraints. 

Syntax:

CREATE TABLE table_Name

(

column1 data_type(size) NOT NULL,

column2 data_type(size) NOT NULL,

….

);

SQL NOT NULL on CREATE a Table

In SQL, we can add NOT NULL constraints while creating a table. 

For example, the “EMPID” will not accept NULL values when the EMPLOYEES table is created because NOT NULL constraints are used with these columns.

Query:

CREATE TABLE Emp(
    EmpID INT NOT NULL PRIMARY KEY,
    Name VARCHAR (50),
    Country VARCHAR(50),
    Age int(2),
  Salary int(10));

Output:

 

 

SQL NOT NULL on ALTER  Table

We can also add a NOT NULL constraint in the existing table using the ALTER statement. For example, if the EMPLOYEES table has already been created then add NOT NULL constraints to the “Name” column using ALTER statements in SQL as follows:

Query:

ALTER TABLE Emp modify Name Varchar(50) NOT NULL;

Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads