MySQL & MariaDB error 1048: Column cannot be null
Column 'name' cannot be null (5.6.51) The statement explicitly put NULL into a column declared NOT NULL. Unlike a missing value, an explicit NULL is rejected even when the column has a default.
| MySQL | MariaDB | |
|---|---|---|
| Symbol | ER_BAD_NULL_ERROR | ER_BAD_NULL_ERROR |
| SQLSTATE | 23000 | 23000 |
| Type | Server error | Server error |
| Versions | every release since 5.0 active | every release since 5.5 active |
What it means
Column 'name' cannot be null. Note the difference from 1364: 1364 is raised when you leave out a NOT NULL column that has no default; 1048 when you send NULL for it. A column default is only used when the column is omitted, never when NULL is supplied explicitly (except for TIMESTAMP columns under the old explicit_defaults_for_timestamp=OFF).
Why it happens
- The application sends
NULLfor an empty form field or a missing JSON key. - An ORM includes every column in the INSERT, with NULL for unset ones.
INSERT … SELECTfrom a source column that contains NULLs.LOAD DATAwith\Nin the file for a NOT NULL column.
How to fix it
- Send a real value, or leave the column out of the INSERT so the default applies.
- Give the column a sensible default:
ALTER TABLE p MODIFY name VARCHAR(20) NOT NULL DEFAULT ''; - Use
COALESCE(src_col, '')inINSERT … SELECT. - If NULL is a legitimate value, make the column nullable.
Reproduce it yourself
These steps are the exact test our harness runs. Use a scratch server, never production.
Connect with
mysql -u root -pand create a scratch database and the test data:CREATE DATABASE demo; USE demo; CREATE TABLE p (id INT PRIMARY KEY, name VARCHAR(20) NOT NULL);Run:
INSERT INTO p VALUES (1, NULL);
You get: Column 'name' cannot be null(11.8.9)
Verified fixes
Supply a value, or give the column a default and omit it
ALTER TABLE p MODIFY name VARCHAR(20) NOT NULL DEFAULT ''; INSERT INTO p (id) VALUES (1); SELECT COUNT(*) FROM p;
Tested on
| Step | MySQL | MariaDB | |||||||
|---|---|---|---|---|---|---|---|---|---|
| 5.6 | 5.7 | 8.0 | 8.4 | 9 | 10.6 | 10.11 | 11.4 | 11.8 | |
| Insert NULL into a NOT NULL column repro | ✓ 1048 | ✓ 1048 | ✓ 1048 | ✓ 1048 | ✓ 1048 | ✓ 1048 | ✓ 1048 | ✓ 1048 | ✓ 1048 |
| Supply a value, or give the column a default and omit it fix | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |