• iconteach@devfunda.com

NOT NULL

NOT NULL

07-09-2025 23:25:01 Time to read : 12 Minutes

By default, a column in PostgreSQL can store NULL values. If you want to make sure a column always has a value, you must use the NOT NULL constraint. This tells the database that NULL values are not allowed for that column.

Remember, NULL does not mean “empty” or “zero.” It simply means the value is unknown or missing.

Using without NOT NULL Constraint

Step 1: Create a Table Without NOT NULL

CREATE TABLE students_null (
    student_id SERIAL PRIMARY KEY,
    name VARCHAR(50),        -- no NOT NULL here
    age INT
);

Step 2: Insert Data


-- Insert without name (NULL allowed)
INSERT INTO students_null (age) VALUES (20);

-- Check data
SELECT * FROM students_null;

Now with NOT NULL
Step 1: Create a Table With NOT NULL


CREATE TABLE students_notnull (
    student_id SERIAL PRIMARY KEY,
    name VARCHAR(50) NOT NULL,   -- NOT NULL applied
    age INT
);

Step 2: Try Insert Without Name

INSERT INTO students_notnull (age) VALUES (20);

 

Want to learn in class