By default a column may be left empty, that is, hold NULL. NOT NULL forbids it: every row must give the column a value, whether on insert or on update.
On a new table
Section titled “On a new table”Every production needs a title and a format, while the country and budget may not be known at first:
CREATE TABLE Productions ( ProductionID int NOT NULL, Title varchar(200) NOT NULL, Format varchar(50) NOT NULL, Country varchar(50), Budget decimal(14, 2));An insert that leaves the title out is refused:
INSERT INTO Productions (ProductionID, Format)VALUES (2, 'Feature film');-- Refused: Title cannot be NULLChoose NOT NULL for any column the rest of the system relies on. A query that groups invoices by supplier, for instance, quietly misbehaves if some invoices have no supplier.
On an existing table
Section titled “On an existing table”Adding NOT NULL to an existing column is written differently in each database. To make Country required:
| Database | Statement |
|---|---|
| SQL Server | ALTER TABLE Productions ALTER COLUMN Country varchar(50) NOT NULL; |
| MySQL | ALTER TABLE Productions MODIFY Country varchar(50) NOT NULL; |
| PostgreSQL | ALTER TABLE Productions ALTER COLUMN Country SET NOT NULL; |
| Oracle | ALTER TABLE Productions MODIFY Country NOT NULL; |
The change fails if any existing row already has no country. Fill those rows in first, for example with an UPDATE.