SQL Not Null

The NOT NULL constraint ensures a column must have a value. It prevents inserting or updating rows with NULL in that column.

On this page

SQL NOT NULL Constraint

The NOT NULL constraint ensures that a column cannot have a NULL value. This is useful for required fields such as names, emails, or identifiers.

NOT NULL in CREATE TABLE

CREATE TABLE customers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(150) NOT NULL
);

Example: Insert Requires Values

If a column is defined as NOT NULL, you must provide a value when inserting a row (unless a DEFAULT is defined).

INSERT INTO customers (name, email)
VALUES ('John Smith', 'john@example.com');

NOT NULL with DEFAULT

You can combine NOT NULL with a DEFAULT value.

CREATE TABLE customers (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  status VARCHAR(20) NOT NULL DEFAULT 'active'
);

Add NOT NULL with ALTER TABLE

In MySQL / MariaDB, you typically modify the column definition to add NOT NULL.

ALTER TABLE customers
MODIFY name VARCHAR(100) NOT NULL;

Remove NOT NULL (Allow NULL)

To allow NULL values again, modify the column without NOT NULL.

ALTER TABLE customers
MODIFY name VARCHAR(100) NULL;

Common Mistakes

  • Trying to set NOT NULL on a column that already contains NULL values
  • Forgetting DEFAULT values for required columns when appropriate
  • Assuming empty string and NULL are the same (they are different)

Best Practice

Use NOT NULL for fields that must always have a valid value. Combine it with sensible DEFAULT values when needed.

Next Step

Continue with SQL UNIQUE to ensure values in a column are not duplicated.