Relationships — Complete Guide
Relationships — 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 9 of 100
Relationships
SQL → Advanced
SQL · 1 — Queries · ~6 min · PostgreSQL — Foundations
What is this?
Relationships link tables through foreign keys — one customer has many orders, one order has many line items. Referential actions like ON DELETE CASCADE define what happens when parent rows disappear.
Why should you care?
Without FKs, a Swiggy order_line could reference restaurant_id=999 when that restaurant was deleted, breaking settlement reports.
See it live — copy this example
Run in pgAdmin or psql.
CREATE TABLE customers (
customer_id bigserial PRIMARY KEY,
email text UNIQUE NOT NULL
);
CREATE TABLE orders (
order_id bigserial PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers(customer_id)
);
What happened?
- customers is the parent; orders.customer_id must match an existing customer_id.
- PostgreSQL blocks orphan orders.
- You can later add ON DELETE RESTRICT or CASCADE depending on business rules.
Practice next
- Create customers and orders in PostgresVerse.
- Insert a customer, then an order referencing that id.
- Attempt an order with customer_id=0 and read the FK violation.
- Add order_items referencing orders with ON DELETE CASCADE.
- Draw the FK graph with pgAdmin ERD after three related tables exist.
Remember
FK enforces parent-child integrity at the database. Choose DELETE actions deliberately per table. Normalize; do not repeat parent columns unnecessarily.
PostgresVerse CRM links
Support searches orders by customer email via JOIN instead of stale copied fields.
Outcome: Email change propagates automatically because orders only store customer_id.
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!