PRIMARY KEY and NOT NULL
Objectives
By the end of this lesson, you should be able to:
- Explain what
PRIMARY KEYguarantees - Explain what
NOT NULLguarantees - Predict when an
INSERTwill be rejected by either constraint
💡 Why this matters: These are the two most common constraints in real schemas.
PRIMARY KEYmakes every row identifiable,NOT NULLmakes sure the columns that matter can’t quietly go missing.
⚠️ A note on verification: every statement and result in this lesson was run against a real, live PostgreSQL 18 database.
PRIMARY KEY: Uniquely Identifying a Row
id SERIAL PRIMARY KEY
PRIMARY KEY marks a column as the unique identifier for every row, no two rows can share the same value, and it can never be NULL. A table can only have one primary key (though it can span more than one column, covered in Module 9).
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL
);
Given id = 2, there’s exactly one row that could match, no ambiguity. This is the same surrogate-key idea, a plain integer with no meaning beyond identifying the row, that every table in this course uses.
NOT NULL: This Column Can’t Be Empty
first_name VARCHAR(50) NOT NULL
Every row must have a real value here, NULL isn’t allowed. Trying to insert one without it fails:
INSERT INTO employees (first_name, last_name, email, salary)
VALUES (NULL, 'Test', 'test@example.com', 50000);
ERROR: null value in column "first_name" of relation "employees" violates not-null constraint
Combining Them
Most tables use both together, PRIMARY KEY on the identifying column, NOT NULL on whichever other columns genuinely can’t be missing:
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
department VARCHAR(50),
salary NUMERIC(10,2) NOT NULL
);
department deliberately has no NOT NULL, from the last lesson, not every employee has one recorded yet, and that’s fine. first_name, last_name, and salary are all required, an employee row without them wouldn’t make sense.
Try It
- Explain, in one sentence each, what
PRIMARY KEYandNOT NULLeach guarantee. - Write a
CREATE TABLEstatement for adepartmentstable with aPRIMARY KEYidand aNOT NULLname. - Write an
INSERTstatement that would violate theNOT NULLconstraint onname, and explain what error you’d expect. - Explain why a table can only have one
PRIMARY KEY, but can have manyNOT NULLcolumns.
Recap
PRIMARY KEYguarantees a column uniquely identifies every row, and is neverNULL.NOT NULLguarantees a column always has a real value, rejecting anyINSERTorUPDATEthat would leave it empty.- A table has exactly one primary key, but as many
NOT NULLcolumns as make sense for the data.
Next lesson: UNIQUE, for columns that need distinct values without being the table’s primary key.