Skip to content
Learn Netverks

Lesson

Step 13/36 36% through track

constraints-postgresql

Constraints in PostgreSQL

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~2 min
Level
beginner

This lesson

This lesson teaches Constraints in PostgreSQL: the SQL patterns, schema habits, and query reasoning you need before advancing in PostgreSQL.

Teams query Constraints in PostgreSQL on every PostgreSQL codebase—skipping it leaves gaps in debugging and data reviews.

You will apply Constraints in PostgreSQL in contexts like: Modern startups, geospatial apps, and analytics-friendly OLTP systems.

Copy Postgres SQL into psql, local PostgreSQL, or DB Fiddle (PostgreSQL dialect)—use \d and EXPLAIN ANALYZE where lessons show them. The in-browser lab ships later; psql is the practice path now.

When you can explain the previous lesson's ideas without copying example queries verbatim.

Constraints enforce data rules inside the database—so every client (psql, Python, Django admin) gets the same guarantees.

Constraint types

CREATE TABLE employees (
  id SERIAL PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  dept TEXT NOT NULL,
  salary NUMERIC(12,2) CHECK (salary > 0),
  UNIQUE (dept, email)
);

Practice: Apply DDL in a throwaway practice database. Use \d table in psql to verify constraints and indexes.

Deferrable foreign keys

ALTER TABLE order_items
  ADD CONSTRAINT fk_order
  FOREIGN KEY (order_id) REFERENCES orders(id)
  DEFERRABLE INITIALLY DEFERRED;

Deferred checks run at COMMIT—useful for bulk loads with temporary ordering issues.

Exclusion constraints (preview)

Exclusion constraints prevent overlapping ranges (scheduling). Requires btree_gist extension for some types—advanced topic beyond intro DDL.

Important interview questions and answers

  1. Q: UNIQUE NULL behavior?
    A: Multiple NULLs allowed in UNIQUE columns in Postgres—NULL is distinct.
  2. Q: CHECK vs app validation?
    A: Both—CHECK catches bad data from ad-hoc SQL and legacy scripts.

Self-check

  1. Which constraint ensures emails are distinct?
  2. Can you have two NULLs in a UNIQUE column?

Tip: CHECK constraints protect data from ad-hoc SQL and legacy scripts—not only your app.

Interview prep

UNIQUE and NULL?

Multiple NULLs allowed in UNIQUE columns in Postgres.

CHECK purpose?

Row-level boolean validation enforced by the database.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • DEFERRABLE when?
  • EXCLUDE constraint?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump