Constraints

Updated · 11 min read
mediumPostgreSQL 18sqlconstraintsnot-nullcheckdefaultddl

A constraint is a rule the database enforces on every row, so bad data is refused before it's stored. In CREATE TABLE you saw a table accept a session with minus 45 minutes and a missing topic, because types alone don't know your rules. Constraints do. The Fee Tracker already has plenty: a payment's amount must be positive, its method must be card, check or cash, and every payment must name a student. This lesson covers NOT NULL, DEFAULT and CHECK, naming constraints, and adding or removing them later. Keys, the constraints that connect tables, come in the next two lessons.

In One Minute

  • NOT NULL means a column must have a value.
  • DEFAULT value fills in a column when an INSERT leaves it out.
  • CHECK (condition) refuses any row for which the condition is false; NULL passes a CHECK.
  • CONSTRAINT name CHECK (...) gives a rule a name, so its error message says what went wrong.
  • ALTER TABLE ... ADD CONSTRAINT checks every existing row first; DROP CONSTRAINT removes a rule.

Why Rules Belong in the Database

Rules in the database protect the data no matter who writes it. The Fee Tracker might be filled by a web form, a spreadsheet import and someone typing in psql. If only the web form checks that amounts are positive, the import can still store -10.00. A constraint stops every one of them, and it can't be forgotten in some new program next year.

Here's Navika's study log again, this time with rules:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER,
  student_id INTEGER NOT NULL,
  minutes    INTEGER NOT NULL DEFAULT 30 CHECK (minutes > 0),
  topic      VARCHAR(60)
);
 
INSERT INTO study_sessions (session_id, student_id, topic)
VALUES (1, 103, 'JavaScript loops');
 
SELECT * FROM study_sessions;
Output
CREATE TABLE
 
INSERT 0 1
 
 session_id | student_id | minutes |      topic
------------+------------+---------+------------------
          1 |        103 |      30 | JavaScript loops
(1 row)

The INSERT didn't mention minutes, so the DEFAULT of 30 filled it in. A constraint written next to one column, like these, is a column constraint; you'll see table constraints shortly.

NOT NULL

NOT NULL refuses a row that leaves the column empty. Forgetting the student:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER,
  student_id INTEGER NOT NULL,
  minutes    INTEGER NOT NULL DEFAULT 30 CHECK (minutes > 0),
  topic      VARCHAR(60)
);
 
INSERT INTO study_sessions (session_id, topic)
VALUES (1, 'JavaScript loops');
Output
CREATE TABLE
 
ERROR:  null value in column "student_id" of relation "study_sessions" violates not-null constraint
DETAIL:  Failing row contains (1, null, 30, JavaScript loops).

The detail line shows the row PostgreSQL refused, with null where the student should be. Columns without NOT NULL, like topic, accept NULL, which is the default for every column. A good habit: make a column NOT NULL unless a missing value really makes sense. In the Fee Tracker, email and method may be missing; first_name and amount_usd may not.

DEFAULT

DEFAULT gives a column a value when an INSERT doesn't supply one. It's used when the column is left out of the column list, or when you write the keyword DEFAULT in its place:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER,
  student_id INTEGER NOT NULL,
  minutes    INTEGER NOT NULL DEFAULT 30 CHECK (minutes > 0),
  topic      VARCHAR(60)
);
 
INSERT INTO study_sessions VALUES (1, 103, DEFAULT, 'Java streams');
 
SELECT * FROM study_sessions;
Output
CREATE TABLE
 
INSERT 0 1
 
 session_id | student_id | minutes |    topic
------------+------------+---------+--------------
          1 |        103 |      30 | Java streams
(1 row)

A default only fills a value that's missing; it never overrides a value you give, not even NULL. Common defaults are a status like 'active', a count of 0, and CURRENT_DATE or now() for "when this row was added".

A missing student is refused; a missing minutes value is filled with the default 30

CHECK

CHECK (condition) refuses any row for which the condition is false. A negative session:

SQL▶ Try it
CREATE TABLE study_sessions (
  session_id INTEGER,
  student_id INTEGER NOT NULL,
  minutes    INTEGER NOT NULL DEFAULT 30 CHECK (minutes > 0),
  topic      VARCHAR(60)
);
 
INSERT INTO study_sessions (session_id, student_id, minutes)
VALUES (1, 103, -45);
Output
CREATE TABLE
 
ERROR:  new row for relation "study_sessions" violates check constraint "study_sessions_minutes_check"
DETAIL:  Failing row contains (1, 103, -45, null).

PostgreSQL named the constraint itself, study_sessions_minutes_check, from the table and column. The Fee Tracker's own checks work the same way. A payment by an app that isn't allowed:

SQL▶ Try it
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (103, 5, 25.00, '2026-01-05', '2026-01-05', 'venmo');
Output
ERROR:  new row for relation "payments" violates check constraint "payments_method_check"
DETAIL:  Failing row contains (8, 103, 5, 25.00, 2026-01-05, 2026-01-05, venmo).

A CHECK refuses only false. NULL makes the condition unknown, and unknown passes:

SQL▶ Try it
CREATE TABLE ratings (
  stars INTEGER CHECK (stars BETWEEN 1 AND 5)
);
 
INSERT INTO ratings VALUES (NULL);
 
SELECT * FROM ratings;
Output
CREATE TABLE
 
INSERT 0 1
 
 stars
-------
  NULL
(1 row)

That's why payment 5's missing method is allowed even though method has a CHECK. If a value must exist and follow a rule, use NOT NULL and CHECK together, as minutes does.

minus 45 makes the condition false and is refused; NULL makes it unknown and passes

Naming Constraints and Table Constraints

Write CONSTRAINT name before a rule to choose its name, so the error says what went wrong in your own words. A check that compares two columns must be written as a table constraint, after the column list:

SQL▶ Try it
CREATE TABLE study_plans (
  plan_id   INTEGER,
  starts_on DATE NOT NULL,
  ends_on   DATE NOT NULL,
  CONSTRAINT plan_ends_after_start CHECK (ends_on >= starts_on)
);
 
INSERT INTO study_plans VALUES (1, '2026-01-05', '2026-01-01');
Output
CREATE TABLE
 
ERROR:  new row for relation "study_plans" violates check constraint "plan_ends_after_start"
DETAIL:  Failing row contains (1, 2026-01-05, 2026-01-01).

plan_ends_after_start tells whoever reads the error exactly which rule failed. Good names say what must be true.

Seeing a Table's Constraints

information_schema.table_constraints lists every constraint on a table:

SQL▶ Try it
SELECT constraint_name, constraint_type
FROM information_schema.table_constraints
WHERE table_name = 'payments'
ORDER BY constraint_name;
Output
          constraint_name           | constraint_type
------------------------------------+-----------------
 payments_amount_usd_check          | CHECK
 payments_amount_usd_not_null       | CHECK
 payments_course_id_fkey            | FOREIGN KEY
 payments_course_id_not_null        | CHECK
 payments_due_on_not_null           | CHECK
 payments_method_check              | CHECK
 payments_paid_on_not_null          | CHECK
 payments_payment_id_not_null       | CHECK
 payments_pkey                      | PRIMARY KEY
 payments_student_id_course_id_fkey | FOREIGN KEY
 payments_student_id_fkey           | FOREIGN KEY
 payments_student_id_not_null       | CHECK
(12 rows)

The payments table carries twelve rules: two checks you've met, a NOT NULL for each required column (PostgreSQL 18 lists those as named constraints, shown here as CHECK), a primary key, and three foreign keys, which the next lessons explain. In psql, \d payments lists them in a friendlier layout.

Adding and Removing Constraints Later

ALTER TABLE ... ADD CONSTRAINT checks every existing row before the rule is accepted. Suppose the program wants a rule that payments are never late:

SQL▶ Try it
ALTER TABLE payments
ADD CONSTRAINT paid_on_time CHECK (paid_on <= due_on);
Output
ERROR:  check constraint "paid_on_time" of relation "payments" is violated by some row

Some payments already were late, so the rule can't be true for every row, and PostgreSQL refuses it. Fix the data first, or choose a rule the data really follows. DROP CONSTRAINT removes a rule by its name, which is one more reason to name rules well:

SQL▶ Try it
ALTER TABLE payments DROP CONSTRAINT payments_method_check;
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (103, 5, 25.00, '2026-01-05', '2026-01-05', 'venmo')
RETURNING payment_id, method;
Output
ALTER TABLE
 
 payment_id | method
------------+--------
          8 | venmo
(1 row)

With the check gone, venmo is accepted. NOT NULL and DEFAULT have their own forms:

You want toWrite
Require a valueALTER TABLE students ALTER COLUMN phone SET NOT NULL;
Allow missing valuesALTER TABLE students ALTER COLUMN phone DROP NOT NULL;
Set a defaultALTER TABLE courses ALTER COLUMN level SET DEFAULT 'Beginner';
Remove a defaultALTER TABLE courses ALTER COLUMN level DROP DEFAULT;

SET NOT NULL checks existing rows too: on students, it fails with column "phone" of relation "students" contains null values, because Navika has no phone. MySQL writes these with MODIFY COLUMN, and SQL Server adds a default as a named constraint (ADD CONSTRAINT df_level DEFAULT 'Beginner' FOR level). Tabs showing each database's version are coming to this course.

paid_on <= due_on is false for the late payments, so the new constraint is refused

Common Mistakes

Trusting the application to check everything. Imports and scripts skip it. Put rules in the database.

Expecting CHECK to refuse NULL. It doesn't. Add NOT NULL.

Adding a rule the existing data breaks. ADD CONSTRAINT fails. Fix or check the data first.

Unnamed constraints. study_sessions_minutes_check is fine, but s_check on a two-column rule says nothing. Name them.

Interview Corner

What types of constraints does SQL have?

NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY and CHECK, plus DEFAULT, which supplies a value rather than refusing one. PostgreSQL also has exclusion constraints.

Does a CHECK constraint allow NULL?

Yes. A CHECK refuses a row only when its condition is false; with NULL the condition is unknown, so the row passes. Add NOT NULL to require a value.

What happens when you add a constraint to a table that already has data?

The database checks every existing row. If any row breaks the rule, the ALTER TABLE fails and the constraint isn't added.

Practice

Challenge: Create a practice_goals table with goal_id INTEGER, a required student_id, a required goal of up to 80 characters, a target_minutes column that defaults to 60 and must be between 15 and 600, and a status that defaults to 'open' and must be 'open' or 'done'. Name the two checks. Insert a goal for Navika (103), "Finish JavaScript Basics", leaving out target_minutes and status, and show the row.

Show solution
SQL▶ Try it
CREATE TABLE practice_goals (
  goal_id        INTEGER,
  student_id     INTEGER NOT NULL,
  goal           VARCHAR(80) NOT NULL,
  target_minutes INTEGER NOT NULL DEFAULT 60,
  status         VARCHAR(10) NOT NULL DEFAULT 'open',
  CONSTRAINT target_minutes_range CHECK (target_minutes BETWEEN 15 AND 600),
  CONSTRAINT status_allowed CHECK (status IN ('open', 'done'))
);
 
INSERT INTO practice_goals (goal_id, student_id, goal)
VALUES (1, 103, 'Finish JavaScript Basics');
 
SELECT * FROM practice_goals;
Output
CREATE TABLE
 
INSERT 0 1
 
 goal_id | student_id |           goal           | target_minutes | status
---------+------------+--------------------------+----------------+--------
       1 |        103 | Finish JavaScript Basics |             60 | open
(1 row)

Both defaults filled in, and both checks passed. Try changing the INSERT to give target_minutes a value of 5, and the target_minutes_range rule refuses it.

Quick check: Constraints

3 questions
1minutes has CHECK (minutes > 0) but no NOT NULL. Which value is accepted?
2A column is NOT NULL DEFAULT 30. You insert a row without that column. What is stored?
3Some payments were late. What does ALTER TABLE payments ADD CONSTRAINT paid_on_time CHECK (paid_on <= due_on); do?

Key Takeaways

You want toWrite
Require a valueminutes INTEGER NOT NULL
Fill a missing valueminutes INTEGER DEFAULT 30
Enforce a ruleCONSTRAINT minutes_positive CHECK (minutes > 0)
Add a rule laterALTER TABLE t ADD CONSTRAINT name CHECK (...);
Remove a ruleALTER TABLE t DROP CONSTRAINT name;

Was this tutorial helpful?

Lesson 31 of 115