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.

PatternWhen to use itWhere the key livesConcrete examples
One-to-oneSplitting optional or private details from core accountsUnique foreign key on child pointing to users.idOne user has one profile or tax_settings row
One-to-manyOne parent owns zero, one, or many childrenChild table holds <parent>_id foreign keyOne customer has many orders; one venue has many courts
Many-to-manyBoth sides link to multiple rows on the other sideDedicated join table holding both foreign keysstudents join classes via enrollments; users join workspaces via workspace_members
Self-referencingNested folders, categories, or threaded repliesRow holds parent_id pointing to its own tablecategories.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.

text
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.

text
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.

text
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.

StrategyBehavior on parent deleteUse it forAvoid it for
Soft delete (`archived_at`)Row stays stored, hidden by archived_at IS NULLPaid orders, invoices, bookings, discontinued products, past membersShort-lived drafts or expired tokens
Restrict (`RESTRICT`)Blocks deleting parent while linked children existCustomers with orders, instructors with upcoming classesSub-records with no standalone value
Cascade (`CASCADE`)Automatically deletes every linked child rowDraft cart items, unpaid draft order_items, post_tags on draft postsRevenue, taxes, bookings, or audit history
Set null (`SET NULL`)Keeps child row and clears foreign key to nullprojects.created_by or bookings.coupon_idRequired 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.

  1. 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").

  2. 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.

  3. State your deletion and archive rules

    Tell ExaSpark which tables use archived_at soft deletes and which links use RESTRICT, SET NULL, or CASCADE.

  4. 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.

Starter prompt · App

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 shortcutWhy it breaks in productionClean 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 countsReplace with a proper join table (product_tags) holding both foreign keys
Duplicate rows in a join tableRapid double-clicks enroll a member twice or add duplicate workspace rolesAdd a composite UNIQUE (parent_a_id, parent_b_id) constraint on the join table
Historical receipts change when catalog edits happenReading products.price_cents live instead of snapshotting at purchase timeCopy unit_price_cents and product_title_snapshot onto order_items at checkout
Deleting a user crashes with a foreign-key errorChild records (bookings, orders) reference users.id with RESTRICTUse soft delete (archived_at) or anonymize personal fields while keeping ledger rows
Slow list screens doing N+1 lookupsLoading 50 bookings and running 50 separate queries to fetch each member's nameJoin 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.

Next steps

Still have a question?Ask our team and other builders on Discord.

From the blog