108 SQL NOT NULL
The webpage explains the SQL NOT NULL constraint. Here are the key points:
- By default, SQL table columns can store NULL values.
- The NOT NULL constraint ensures that a specified column cannot accept NULL values—it must always have a value.
- This constraint prevents inserting or updating a record without a value in a NOT NULL column.
- You can add NOT NULL:
- When creating a table (e.g., making ID, LastName, and FirstName NOT NULL columns during table creation).
- On an existing table using ALTER TABLE:
- In SQL Server/MS Access:
ALTER TABLE Persons ALTER COLUMN Age int NOT NULL; - In MySQL/older Oracle:
ALTER TABLE Persons MODIFY COLUMN Age int NOT NULL; - In newer Oracle versions:
ALTER TABLE Persons MODIFY Age int NOT NULL;
- In SQL Server/MS Access:
- The page includes an exercise: the purpose of the NOT NULL constraint is to enforce that a column must always contain a value.[1]
This constraint is essential for ensuring data integrity by making certain that important columns aren’t left empty.
SQL NOT NULL Constraint
By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.
SQL NOT NULL on CREATE TABLE
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept NULL values when the "Persons" table is created:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
SQL NOT NULL on ALTER TABLE
To create a NOT NULL constraint on the "Age" column when the "Persons" table is already created, use the following SQL:
SQL Server / MS Access:
ALTER TABLE Persons
ALTER COLUMN Age int NOT NULL;
My SQL / Oracle (prior version 10G):
ALTER TABLE Persons
MODIFY COLUMN Age int NOT NULL;
Oracle 10G and later:
ALTER TABLE Persons
MODIFY Age int NOT NULL;