The NOT NULL constraint in SQL is used to ensure that a column cannot have a NULL value. When you define a column with the NOT NULL constraint, the database will not allow the insertion of a record unless a value is provided for that column.
Syntax for NOT NULL Constraint
CREATE TABLE table_name (
column_name data_type NOT NULL
);
Example:
CREATE TABLE Employees (
EmployeeID INT NOT NULL,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
BirthDate DATE,
PRIMARY KEY (EmployeeID)
);
In this example, the EmployeeID, FirstName, and LastName columns are defined with the NOT NULL constraint, meaning that these columns cannot contain NULL values.
Adding NOT NULL to an Existing Column
If you want to add the NOT NULL constraint to an existing column, you can use the ALTER TABLE statement:
ALTER TABLE table_name
MODIFY column_name data_type NOT NULL;
Example:
ALTER TABLE Employees
MODIFY BirthDate DATE NOT NULL;
This will modify the BirthDate column to not allow NULL values.
Notes:
- If you try to insert a
NULLvalue into aNOT NULLcolumn, the database will throw an error. - The
NOT NULLconstraint is useful for ensuring data integrity when certain fields are mandatory.
No comments:
Post a Comment