Table relationships guide
Connect tables with clean foreign keys, join tables, and safe deletion rules so bookings, orders, and SaaS teams stay accurate as your app grows.
Why separate tables beat one giant spreadsheet
Putting customer name, email, phone, item price, and booking time into one wide table works for ten test rows, then quietly breaks once real customers edit details or place repeat orders.
If a returning customer changes their phone number, a flattened table forces you to hunt down twenty past rows. Miss one row and your roster disagrees with billing. Separate linked tables give every fact one source of truth.
Relational databases connect tables using two keys:
- Primary key (`id`). A permanent unique identifier on every row (usually a UUID) that never changes when a customer updates their name or email.
- Foreign key (`customer_id`, `court_id`, `workspace_id`). A column on a child table pointing to a parent's primary key, guaranteeing that linked parent exists.
When bookings.customer_id references users.id, updating a member's phone number once updates every linked booking immediately.
Choosing the right relationship pattern
Most business apps use four relationship patterns. Naming the exact pattern in your prompt helps ExaSpark pick the right foreign keys and indexes on the first turn.
| Pattern | When to use it | Where the key lives | Concrete examples |
|---|---|---|---|
| One-to-one | Splitting optional or private details from core accounts | Unique foreign key on child pointing to users.id | One user has one profile or tax_settings row |
| One-to-many | One parent owns zero, one, or many children | Child table holds <parent>_id foreign key | One customer has many orders; one venue has many courts |
| Many-to-many | Both sides link to multiple rows on the other side | Dedicated join table holding both foreign keys | students join classes via enrollments; users join workspaces via workspace_members |
| Self-referencing | Nested folders, categories, or threaded replies | Row holds parent_id pointing to its own table | categories.parent_category_id; comments.reply_to_id |
One-to-many: the everyday backbone
Always put the foreign key on the "many" side, never on the "one" side. A customer places many bookings, so bookings holds user_id pointing to users.id. Storing a list of booking IDs inside users breaks filtering, counting, and constraints.
Many-to-many: why join tables pull double duty
Whenever two tables need multiple links in both directions — orders with multiple products, or users across multiple workspaces — place a join table in the middle.
A join table also holds attributes about the link itself, such as a member's role in a specific workspace, checked_in_at for a class session, or quantity and unit_price_cents inside an order. Add a composite unique constraint like UNIQUE (user_id, class_id) so double-clicks never create duplicate links.
Real-world schema blueprints
Five lines of table structure save hours of rework across later turns. Adapt these three production blueprints directly in your prompts.
Online store: orders, products, and price snapshots
orders and products connect many-to-many through order_items. Copying the title and price onto order_items at checkout guarantees future price edits never rewrite old customer receipts.
customers (id PK, email UNIQUE, full_name)
products (id PK, sku UNIQUE, title, price_cents int, archived_at)
orders (id PK, customer_id FK->customers RESTRICT, status, total_cents int, created_at)
order_items (id PK, order_id FK->orders CASCADE, product_id FK->products RESTRICT,
product_title_snapshot, unit_price_cents int, quantity int > 0)Multi-tenant SaaS: workspaces, memberships, and projects
Placing role on the workspace_members join table lets one person be an admin in their own agency workspace and a viewer inside a client's workspace.
workspaces (id PK, name, slug UNIQUE, plan)
workspace_members (id PK, workspace_id FK->workspaces CASCADE, user_id FK->users CASCADE,
role enum('owner','admin','member','viewer'), UNIQUE(workspace_id, user_id))
projects (id PK, workspace_id FK->workspaces RESTRICT, created_by FK->users SET NULL,
title, archived_at)Booking studio: instructors, classes, and enrollments
Booking apps pair one-to-many (instructors -> classes) with many-to-many (members <-> classes via enrollments), keeping attendance tied to each session.
instructors (id PK, full_name, bio)
classes (id PK, instructor_id FK->instructors SET NULL, title, starts_at UTC, capacity int)
enrollments (id PK, class_id FK->classes RESTRICT, user_id FK->users RESTRICT,
status enum('booked','waitlisted','canceled','attended'), checked_in_at UTC,
UNIQUE(class_id, user_id) WHERE status IN ('booked','waitlisted'))Deletion rules: cascade, restrict, or soft delete
Every foreign key must answer one question: what happens to child rows if someone deletes the parent? Leaving this vague risks erasing financial records or hitting unexpected database errors.
| Strategy | Behavior on parent delete | Use it for | Avoid it for |
|---|---|---|---|
| Soft delete (`archived_at`) | Row stays stored, hidden by archived_at IS NULL | Paid orders, invoices, bookings, discontinued products, past members | Short-lived drafts or expired tokens |
| Restrict (`RESTRICT`) | Blocks deleting parent while linked children exist | Customers with orders, instructors with upcoming classes | Sub-records with no standalone value |
| Cascade (`CASCADE`) | Automatically deletes every linked child row | Draft cart items, unpaid draft order_items, post_tags on draft posts | Revenue, taxes, bookings, or audit history |
| Set null (`SET NULL`) | Keeps child row and clears foreign key to null | projects.created_by or bookings.coupon_id | Required ownership keys like bookings.user_id |
Prompting relationships into your ExaSpark app
Follow four quick steps whenever you introduce linked tables so ExaSpark generates accurate constraints, clean joins, and intuitive forms right away.
Name each entity and cardinality
Write out which records own many children and which pairs need a join table (for example, "each order has many order items linked to products").
List payload fields on join tables
Specify any columns that belong on the link itself, such as
role,quantity,checked_in_at, or checkout price snapshots.State your deletion and archive rules
Tell ExaSpark which tables use
archived_atsoft deletes and which links useRESTRICT,SET NULL, orCASCADE.Seed and inspect in Cloud (Preview)
Ask ExaSpark to seed linked sample rows in Preview, then open the Cloud tab to verify foreign keys resolve cleanly before publishing.
Create a studio booking schema with four linked tables: `users`, `instructors`, `classes`, and `enrollments`. Each class belongs to one instructor (`SET NULL` on instructor archive) and tracks `starts_at` in UTC plus `capacity`. Use `enrollments` as a join table connecting `classes` and `users` with `status` (`booked`, `waitlisted`, `canceled`, `attended`), `paid_cents`, and `checked_in_at`. Prevent duplicate active enrollments for the same user and class, archive discontinued classes with `archived_at` instead of hard deleting, and seed realistic linked Preview rows so we can test class rosters.
Common relationship mistakes & fixes
Most slow queries and messy data bugs trace back to a handful of structural shortcuts. Spot and fix them early in Preview before real customers create Live rows.
| Symptom or shortcut | Why it breaks in production | Clean relational fix |
|---|---|---|
Comma-separated IDs in a text column (e.g., "tag1,tag4,tag9") | Impossible to index reliably, easy to corrupt, and breaks joins or counts | Replace with a proper join table (product_tags) holding both foreign keys |
| Duplicate rows in a join table | Rapid double-clicks enroll a member twice or add duplicate workspace roles | Add a composite UNIQUE (parent_a_id, parent_b_id) constraint on the join table |
| Historical receipts change when catalog edits happen | Reading products.price_cents live instead of snapshotting at purchase time | Copy unit_price_cents and product_title_snapshot onto order_items at checkout |
| Deleting a user crashes with a foreign-key error | Child records (bookings, orders) reference users.id with RESTRICT | Use soft delete (archived_at) or anonymize personal fields while keeping ledger rows |
| Slow list screens doing N+1 lookups | Loading 50 bookings and running 50 separate queries to fetch each member's name | Join bookings with users in a single server query and index foreign keys |
For deeper guidance on evolving existing Live tables without data loss, read Safe schema updates.