NOT NULL Constraint
beginnerbasics
2 min read
What is NOT NULL?
The NOT NULL constraint ensures a column cannot store a NULL value. Every INSERT or UPDATE must provide an actual value for that column.
NULL represents the absence of data. In many cases, certain columns like names, emails, or prices must always have a value, and NOT NULL enforces that rule.
Syntax
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price NUMERIC(10,2) NOT NULL
);Adding NOT NULL to an existing column:
ALTER TABLE students ALTER COLUMN email SET NOT NULL;When to Use
- Columns that must always have meaningful data (name, email, price)
- Columns used in calculations that cannot handle NULLs
- Foreign key columns that should always reference a parent
Key Points
- Rejects NULLs — Any INSERT or UPDATE that tries to set the column to NULL will fail.
- Default Values — Pair NOT NULL with DEFAULT to provide a fallback value.
- ALTER TABLE — You can add or remove NOT NULL on existing columns.
- Part of PRIMARY KEY — Primary key columns are implicitly NOT NULL.
- Data Quality — NOT NULL is one of the simplest ways to improve data quality.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
NOT NULL Constraint Challenge
Write a query that solve this task: ensure name and price are always provided for products.
Expected result
A products table where name and price must have values. category can be NULL.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is NOT NULL?
Initializing database...Each run starts from fresh sample data.
More Examples
Add NOT NULL to an existing column
Make the email column required in the students table.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
What happens if I insert NULL into a NOT NULL column?
PostgreSQL raises an error: 'null value in column violates not-null constraint' and the INSERT is rejected.
Can I remove a NOT NULL constraint?
Yes. Use ALTER TABLE table_name ALTER COLUMN col DROP NOT NULL; to make the column nullable again.