In SQL, the NOT NULL
constraint is used to ensure that a column cannot contain any NULL
values. When you define a column with the NOT NULL
constraint, it means that every row inserted into the table must have a value for that column, and the value cannot be NULL
.
Here's how you can define a column with the NOT NULL
constraint
CREATE TABLE table_name ( column1 datatype NOT NULL, column2 datatype, ... );
In this syntax:
table_name
: The name of the table you are creating.column1
: The name of the column.datatype
: The data type of the column.NOT NULL
: The constraint that specifies the column cannot contain NULL
values.Example:
Let's say we have a table named employees
and we want to ensure that the first_name
and last_name
columns cannot contain NULL
values:
CREATE TABLE employees ( employee_id INT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, salary DECIMAL(10, 2) );
In this example, both first_name
and last_name
columns are defined with the NOT NULL
constraint. This means that every row inserted into the employees
table must have a non-NULL value for both first_name
and last_name
.
If you try to insert a row into the employees
table without providing values for first_name
or last_name
, or if you try to update an existing row to set either of these columns to NULL
, you will receive an error due to the NOT NULL
constraint violation.
Using the NOT NULL
constraint helps enforce data integrity by ensuring that essential data is always present in the database, and it can also improve query performance by eliminating the need to check for NULL
values in queries.