Tables & Constraints — Complete Guide
Tables & Constraints — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 7 of 100
Tables & Constraints
SQL → Advanced
SQL · 1 — Queries · ~6 min · PostgreSQL — Foundations
What is this?
Tables define columns and types; constraints enforce rules — PRIMARY KEY, UNIQUE, NOT NULL, CHECK, and FOREIGN KEY. PostgreSQL rejects inserts that violate constraints instead of silently corrupting data.
Why should you care?
Swiggy cannot allow an order with a negative total or a line item pointing to a deleted restaurant — constraints catch that at insert time.
See it live — copy this example
Run in pgAdmin or psql.
CREATE TABLE orders (
order_id bigserial PRIMARY KEY,
customer_id bigint NOT NULL,
total_amount numeric(10,2) CHECK (total_amount >= 0),
status text NOT NULL DEFAULT 'pending'
);
What happened?
- bigserial auto-generates order_id.
- CHECK blocks negative totals.
- DEFAULT fills status when omitted.
- PRIMARY KEY implies UNIQUE and NOT NULL on order_id.
Practice next
- Connect to PostgresVerse and CREATE TABLE orders as shown.
- Insert a valid row with INSERT INTO orders (customer_id, total_amount) VALUES (1, 249.00);
- Try INSERT with total_amount -1 and read the CHECK error.
- Add UNIQUE (customer_id, created_at) after adding a created_at column.
- Name a constraint explicitly: CONSTRAINT orders_total_nonneg CHECK (...).
Remember
Constraints are enforced on every INSERT/UPDATE. CHECK validates expressions; FK validates references. \d tablename lists constraints in psql.
PostgresVerse order guardrails
An intern API tries to POST total_amount=-50; PostgreSQL rejects it before the bug reaches finance.
Outcome: Product team adds CHECK constraints instead of duplicating validation in three services.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!