SQL NOT NULL constraint

SQL Tutorial

Here is a clear, practical, and complete guide to the SQL NOT NULL constraint, including behavior, examples, and engine differences.

What the SQL NOT NULL constraint Does

NOT NULL ensures that a column cannot contain NULL values.

Basic Syntax

In CREATE TABLE:

In ALTER TABLE:

 Example: Ensure a required column

  •  Prevents inserting a product without name or price.

 Inserting Rows With NOT NULL Columns

Valid:

Invalid (missing required field):



-- ERROR: name cannot be null

 Add NOT NULL to an Existing Column (with data present)

PostgreSQL:

MySQL:

SQL Server:

  •  Must remove NULLs first or the ALTER will fail.

Remove NOT NULL Constraint

PostgreSQL:

MySQL:

SQL Server:

Important Behavior Notes

  • NOT NULL prevents NULL but not empty strings (''), unless you enforce that separately.
  •  Most engines treat PRIMARY KEY as implicitly NOT NULL.
  •  Columns without an explicit constraint default to NULL unless changed.
  •  For mandatory columns, combine with CHECK or DEFAULT when helpful.

Best Practices

  •  Apply NOT NULL to all required fields
  •  Add sensible defaults (e.g., DEFAULT CURRENT_TIMESTAMP)
  •  Clean existing NULL data before adding constraints
  •  Avoid allowing NULL on foreign key columns unless logically required
  •  Use migrations to apply changes safely in production

You may also like...