SQL NOT NULL
By default a column may hold NULL. The NOT NULL constraint says a column must always have a value: inserting or updating a row so that the column is NULL fails.
CREATE TABLE table_name (
column datatype NOT NULL,
...
);Which TAD Market columns are required?
SELECT name AS column_name, "notnull" AS required
FROM pragma_table_info('customers');column_name | required
------------+---------
customer_id | 0
name | 1
contact | 0
email | 0
city | 0
country | 0
joined | 0
(7 rows)
Only the id (as primary key, it always gets a value) and name are mandatory for a customer; e-mail, city and the rest are optional — which is why some customers have a NULL email.
Missing a required value
INSERT INTO customers (city, country) VALUES ('Prague', 'Czechia');Error: NOT NULL constraint failed: customers.name
The same rule applies to UPDATE:
UPDATE products SET price = NULL WHERE product_id = 1;Error: NOT NULL constraint failed: products.price
NOT NULL vs empty values
NOT NULL only forbids NULL. An empty string '' or the number 0 is still a value:
INSERT INTO customers (name) VALUES ('');
SELECT customer_id, name, length(name) AS len
FROM customers
WHERE customer_id = 26;1 row affected.
customer_id | name | len
------------+------+----
26 | | 0
(1 row)
To reject empty strings too, add a CHECK:
CREATE TABLE tags (
tag TEXT NOT NULL CHECK (length(trim(tag)) > 0)
);
INSERT INTO tags VALUES ('organic');
INSERT INTO tags VALUES (' ');1 row affected.
Error: CHECK constraint failed: length(trim(tag)) > 0
Combining NOT NULL with DEFAULT
A NOT NULL column with a DEFAULT is easy to use: callers can leave it out, and it still never becomes NULL. products.stock works like that:
INSERT INTO products (name, price) VALUES ('Gift Card', 25);
SELECT name, price, stock FROM products WHERE name = 'Gift Card';1 row affected.
name | price | stock
----------+-------+------
Gift Card | 25 | 0
(1 row)
Adding NOT NULL later
| Database | Make an existing column NOT NULL |
|---|---|
| PostgreSQL | ALTER TABLE t ALTER COLUMN c SET NOT NULL; |
| MySQL | ALTER TABLE t MODIFY c VARCHAR(100) NOT NULL; |
| SQL Server | ALTER TABLE t ALTER COLUMN c VARCHAR(100) NOT NULL; |
| SQLite | not possible with ALTER — rebuild the table |
All of these fail if existing rows already contain NULLs, so fill them first with an UPDATE.
Tip: Make a column
NOT NULLunless "unknown" is a meaningful state for it. Fewer NULLs mean simpler queries and fewer three-valued-logic surprises.
Test yourself
Can a NOT NULL text column hold an empty string ''?
- Yes
- No
- Only in SQLite
- Only with a DEFAULT
What happens when an INSERT omits a NOT NULL column that has no DEFAULT?
- It gets 0
- It gets ''
- The insert fails
- It gets NULL anyway