Pathubs Logo Mark
PATHUBSFREE CAREER ROADMAPS
HomeExploreDiscoverCompare ⚖️My Progress 📊Support
Student Support & Feedback

Have Questions or Need Help?

Have questions, feedback, or suggestions for new roadmaps and interactive tools? Reach out to our team — we review every message to make practical learning better for everyone.

supportpathubs@gmail.com Official Telegram Support (@PathubsSupport)
Pathubs

100% Free, Zero-Paywall Tech Career Roadmaps, In-Depth Practical Content, and Live Interactive Virtual Labs for Learners Worldwide.

Popular Careers

  • Frontend Development
  • Backend Development
  • AI & LLM Engineering
  • Full Stack Web Dev
  • Data Analytics

Platform Tools

  • Career Discovery Quiz
  • Compare Careers

Contact & Info

  • About Us
  • supportpathubs@gmail.com
  • Support Pathubs

© 2026 Pathubs. All Rights Reserved. Structured learning, practical content, and hands-on practice for learners worldwide.

AboutPrivacy PolicyTerms & ConditionsSitemapRobots
Backend Developer Roadmap/Databases & SQL/Primary & Foreign Keys
Relational Databases & SQL Entity Identity Referential Integrity PostgreSQL & MySQL

Primary & Foreign Keys in Relational Databases

Master how primary keys guarantee unique row identity and how foreign keys enforce referential integrity across parent and child tables. Explore composite keys, CASCADE/RESTRICT actions, and engine differences in PostgreSQL and MySQL.

Primary Key RuleUNIQUE + NOT NULL (Single per Table)
Foreign Key RoleReferential Integrity Constraint
Referential ActionsCASCADE, RESTRICT, SET NULL, NO ACTION
1. Primary Keys2. Foreign Keys3. SQL Key Syntax4. Referential Actions5. SQL Constraint Playground6. Debugging Challenge7. PK vs FK Comparison8. Mini Challenge9. Mastery Quiz
01

Primary Keys: Guaranteeing Entity Identity

In a relational database, rows represent real-world entities (users, products, bank accounts, invoices). Without a reliable, immutable identifier, you cannot distinguish between two people with the same name or safely update a single record without accidentally corrupting duplicates.

What is a Primary Key?

A primary key is a column (or combination of columns) whose values uniquely identify each row in a table. It serves as the primary access path and address of the record.

UNIQUE + NOT NULL

A PRIMARY KEY constraint enforces two strict mathematical rules: every value must be completely unique across the table, and no value may ever be NULL.

Exactly One PK per Table

A table can have multiple unique columns, but it can have only one PRIMARY KEY constraint. This defines the table's canonical entity identity.

Single vs Composite Keys

A primary key can be a single column (e.g. id BIGINT) or a composite key formed by multiple columns (e.g. order_id + product_id in an order items table).

Primary Key vs Ordinary UNIQUE Column

PropertyPRIMARY KEYUNIQUE Column
Allowed Count per TableStrictly 1 per tableMultiple allowed per table (e.g. `email`, `username`, `ssn`)
NULL Values Permitted?NEVER. Implicitly enforces `NOT NULL`YES (in SQL standard / PostgreSQL, multiple rows can contain `NULL` because `NULL != NULL`)
Clustered Storage (MySQL InnoDB)Defines the physical clustered B-Tree row order on diskSecondary index pointing to the primary key value
Foreign Key TargetThe standard, default target for foreign key referencesCan be referenced by foreign keys, but requires explicit specification
02

Foreign Keys: Maintaining Referential Integrity

A foreign key is not merely an ID column copied from another table; it is a relational database constraint that links a column in a referencing (child) table to a primary key or unique key in a referenced (parent) table.

Table: usersParent (Referenced)
id (PK) | name | email
1 | Alice Chen | alice@example.com
2 | Bob Smith | bob@example.com
3 | Carlos Diaz | carlos@example.com
REFERENCES
Table: ordersChild (Referencing)
id (PK) | user_id (FK) | total
1001 | 1 → users.id(1) | $129.99
1002 | 1 → users.id(1) | $159.98
1003 | 2 → users.id(2) | $349.99

1. Inserting a Valid Parent ID

When inserting an order with user_id = 1, the database checks the users table index. Since row 1 exists, the insert succeeds smoothly.

2. Inserting a Non-Existent ID

If a client attempts to insert user_id = 999, the database rejects the insert with an immediate foreign key constraint error. Orphaned records are mathematically prevented!

3. Deleting or Updating a Parent Row

If an administrator tries to delete user #1 while orders #1001 and #1002 exist, the database acts according to the configured referential action (CASCADE, RESTRICT, or SET NULL).

03

Key Constraints in SQL: PostgreSQL vs MySQL

While the core SQL concepts are standardized, syntax for auto-incrementing identity keys and foreign key indexing rules differ critically between PostgreSQL and MySQL.

schema.sql (PostgreSQL 16+)PostgreSQL
-- 1. Parent Table with Standard SQL IDENTITY Primary Key:
CREATE TABLE users (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(255) UNIQUE NOT NULL
);

-- 2. Child Table with Foreign Key Constraint:
CREATE TABLE orders (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id BIGINT NOT NULL,
  total NUMERIC(10, 2) NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW(),

  -- Foreign Key with explicit constraint name:
  CONSTRAINT fk_orders_user
    FOREIGN KEY (user_id)
    REFERENCES users(id)
    ON DELETE CASCADE
    ON UPDATE CASCADE
);

-- ⚠️ POSTGRESQL GOTCHA: Foreign keys are NOT automatically indexed!
-- You must manually create an index on the referencing child column
-- to prevent full table scans during parent deletes or joins:
CREATE INDEX idx_orders_user_id ON orders(user_id);

-- 3. Composite Primary Key Table (e.g. Order Items):
CREATE TABLE order_items (
  order_id BIGINT REFERENCES orders(id) ON DELETE CASCADE,
  product_id BIGINT REFERENCES products(id) ON DELETE RESTRICT,
  quantity INT NOT NULL CHECK (quantity > 0),
  
  -- Composite Primary Key: Both columns together form unique identity
  PRIMARY KEY (order_id, product_id)
);

Adding Constraints via ALTER TABLE

migrations/add_constraints.sqlSQL Standard
-- Add Primary Key to an existing table:
ALTER TABLE payments
  ADD CONSTRAINT pk_payments PRIMARY KEY (payment_id);

-- Add Foreign Key to an existing table:
ALTER TABLE payments
  ADD CONSTRAINT fk_payments_order
  FOREIGN KEY (order_id)
  REFERENCES orders(id)
  ON DELETE RESTRICT;
04

Referential Actions: ON DELETE & ON UPDATE

What should happen to referencing child rows when a referenced parent row is deleted or updated? Relational databases provide 4 standard referential actions to maintain data consistency:

1. CASCADE

Automatically propagates the delete or update to the child table. Deleting user #1 deletes all orders belonging to user #1.

ON DELETE CASCADE

2. RESTRICT

Immediately blocks the deletion or update of the parent row if any dependent child rows exist. Raises an error instantly.

ON DELETE RESTRICT

3. SET NULL

Retains the child row but sets its foreign key column to NULL. Requires the child column to be nullable!

ON DELETE SET NULL

4. NO ACTION

Similar to RESTRICT, but in PostgreSQL it can be deferred until transaction commit (DEFERRABLE).

ON DELETE NO ACTION
Architecture Trade-off: CASCADE vs RESTRICT
While ON DELETE CASCADE is convenient, in production systems it can be dangerous: deleting a single organization or account might silently wipe millions of historical invoices, audit logs, and payments. For financial and compliance records, professional architectures prefer ON DELETE RESTRICT combined with soft-deletes (deleted_at TIMESTAMP).
05

Interactive SQL Constraint Playground

Execute real SQL queries against an interactive relational database engine. Trigger genuine constraint violation errors (duplicate primary keys, orphaned foreign keys, null primary keys) and observe referential actions in real time.

Live SQL Engine (PostgreSQL / MySQL InnoDB)

SQL Query EditorCtrl+Enter or click Run SQL
Schema: public (users, products, orders)
Database Console Output:
PostgreSQL 16.2 database initialized. Schema active: public.
Tables: users (3 rows), products (3 rows), orders (3 rows).
Table: usersPK: id (3 rows)
id (PK)nameemail
1Alice Chenalice@example.com
2Bob Smithbob@example.com
3Carlos Diazcarlos@example.com
Table: ordersFK: user_id → users.id (3 rows)
id (PK)user_id (FK)total
10011$129.99
10021$159.98
10032$349.99
06

Debugging Challenge: 7 Realistic Relational Key Pitfalls

Diagnose real database errors: duplicate primary keys, null keys, orphaned foreign keys, non-unique referenced targets, type mismatches, and SET NULL contradictions. Select the scenario and pick the architectural fix.

Fixed: 0 of 7

Duplicate Primary Key Insertion

PostgreSQL
Database Error: `ERROR: duplicate key value violates unique constraint "users_pkey"` (Key (id)=(1) already exists).
-- Setup:
INSERT INTO users (id, name, email) VALUES (1, 'Alice', 'alice@example.com');

-- ❌ Buggy operation attempting duplicate PK:
INSERT INTO users (id, name, email) VALUES (1, 'Bob', 'bob@example.com');
How do you fix this database error?
07

Primary Key vs Foreign Key: Architectural Contrast

A concise side-by-side comparison illustrating the complementary roles of primary keys and foreign keys in relational modeling:

DimensionPRIMARY KEYFOREIGN KEY
Primary ObjectiveIdentifies rows uniquely in its own tableReferences an existing key in another table
Uniqueness RequirementMust be strictly unique across all rowsDoes NOT need to be unique (in a 1-to-many relationship, many child rows share the same parent key)
NULL Values Permitted?Never. Forbids NULL valuesPermitted (unless explicitly marked NOT NULL; nullable FKs represent optional relationships)
Cardinality per TableStrictly 1 primary key constraint per tableA table can have multiple foreign keys linking to different tables
Integrity EnforcedEntity Integrity (ensures every entity has a unique identity)Referential Integrity (ensures no orphaned references exist)
08

Mini Challenge & Architectural Synthesis

Design a robust relational schema connecting customers to orders. Identify the primary key, foreign key, parent table, child table, and configure a safe referential action.

Relational Schema Design: E-Commerce Store

Requirement: You are building the relationship between customers and orders. Customers place orders. If a customer account is deleted, all their pending orders should automatically be deleted with them.
1. Primary Key in Parent Table:
2. Foreign Key in Child Table:
3. Parent Table Name:
4. Child Table Name:
5. ON DELETE Action:

Entity Identity (PK)

Every row needs a deterministic identifier. A primary key enforces UNIQUE + NOT NULL and acts as the row's physical cluster or lookup root.

Referential Integrity (FK)

Foreign keys link child rows to parent keys. They prevent orphaned records and ensure child values map to real, existing entities.

Referential Actions

Configure CASCADE to propagate deletions automatically, or RESTRICT to block deletion of parents with active dependencies.

Postgres FK Indexing Gotcha

PostgreSQL does NOT automatically index foreign key columns. Always create explicit indexes on referencing columns to prevent full table scans.

09

Primary & Foreign Keys Mastery Quiz

Verify your mastery of relational database constraints, referential integrity, and engine differences across PostgreSQL and MySQL with these 7 scenario-based questions.

Interactive Assessment

Primary & Foreign Keys Mastery Quiz

Test your understanding of identity constraints, foreign key referential actions, composite keys, and indexing mechanics.

Question 1 of 7Score: 0 / 7
What is the fundamental difference between a PRIMARY KEY constraint and a UNIQUE constraint in SQL?