Skip to content
AI-powered appsNewChat, vision, voice, generationBookings & schedulingAppointments that book themselvesShops & sellingA storefront in every pocketClient & businessRun the operation from one placeCommunities & clubsA home that is not a group chat
Health & wellnessHabits, tracking and calmGames2D, 3D and multiplayerPersonal & toolsThe tool you wish existedInternal toolsThe tool ops never had time for
See all use cases
ArcadeNewPricingSecurity
EngineThe game engine and World EditorHow it worksFrom one sentence to a live productDocsGuides for building and publishingBlogStories, guides and newsChangelogWhat shipped latelyStatusUptime of every serviceSupportGet help from the team
AI-powered appsBookings & schedulingShops & sellingClient & businessCommunities & clubsHealth & wellnessGamesPersonal & toolsInternal tools
See all use cases
ArcadeNewPricingSecurity
EngineHow it worksDocsBlogChangelogStatusSupport
Language
Blog
GlossaryNovember 22, 20263 min read

What are primary and foreign keys?

The two columns that let a database connect players to scores and customers to orders without copying anything. What they are, how to pick them, and the delete rule that bites.

Startbase Team
Editorial ink illustration of a library card tied by string to a loan slip, the string in ember orange

Key takeaways

  • A primary key is a unique, permanent, meaningless ID for each row; a foreign key is a column holding another table's primary key.
  • Declared foreign keys stop orphan rows, and the ON DELETE rule decides what happens to children when a parent is deleted.
  • Postgres indexes primary keys automatically but not foreign key columns, so busy foreign keys usually need an index.

A primary key is the column that gives every row in a table its own unique, permanent ID, and a foreign key is a column in another table that stores one of those IDs to say "this row belongs to that one." Together they let a database connect customers to orders, players to scores and posts to comments without copying the same data into several places.

An everyday example: the library card

Every library member gets a card number nobody else will ever have. That number is the primary key of the members list. When you borrow a book, the loan slip does not copy your name, address and phone; it writes your card number. That number on the slip is a foreign key. If you move house, the library updates one record, and every old slip still points at you.

The same idea in a small game backend:

  • `players`: `id` (primary key), `username`, `created_at`
  • `scores`: `id` (primary key), `player_id` (foreign key to `players.id`), `points`, `level`

To show a leaderboard with names, the database joins the two tables where `scores.player_id = players.id`. Rename a player once and every score shows the new name instantly.

What makes a good primary key

  • Unique and never reused. If row 42 is deleted, 42 must not go to a new user, or old foreign keys will suddenly point at a stranger.
  • Meaningless. Do not use an email address or phone number as the key. People change them, and every row that refers to them would have to change too.
  • Generated for you. Apps use either an auto-incrementing number or a UUID, a 36-character random ID. UUIDs are a common default in Postgres apps because they can be created anywhere and do not reveal how many users you have.

A key can also be a pair of columns. A `team_members` table can use (`team_id`, `user_id`) together as its primary key, which makes it impossible for the same person to join the same team twice.

What a foreign key actually protects

Declared in the database, a foreign key is a rule, not just a naming habit. Postgres refuses a score whose `player_id` matches no player, so you never end up with orphan rows that show as "Unknown" on a leaderboard. You also choose what happens when the parent row is deleted:

  • `ON DELETE CASCADE`: delete a project and its tasks go with it. Right for data that means nothing on its own.
  • `ON DELETE SET NULL`: delete a staff member and their past bookings stay, with no staff attached.
  • `ON DELETE RESTRICT`: refuse to delete a customer who still has invoices.

The wrong choice is a classic quiet bug. A cascade from `users` to `orders` means one account deletion erases that customer's sales history from your revenue reports.

Why it matters when building with Startbase

With Startbase Cloud on, your app gets a Postgres database and the agent writes its tables as SQL migrations in your project, keys included. You rarely type a key yourself, but naming the relationships in your prompt gets the right shape on the first try. One practical detail from the database docs: in the Backend tab's table browser, a table without a primary key is read-only, so you cannot edit or delete its rows there.

Set up the data for a booking app. Tables: customers, staff, services, bookings. Each booking belongs to one customer, one staff member and one service. If a staff member is deleted, keep their past bookings with staff set to empty. Never allow deleting a customer who has upcoming bookings. Use UUID primary keys.

For the bigger picture, read database basics for non-developers, then row-level security explained, which uses these same ID columns to decide who can see each row.

Common confusions

  • It is not a security key. A foreign key has nothing to do with API keys or passwords. It is a column of IDs.
  • Keys are not automatically fast to search. Postgres builds an index for every primary key, but not for foreign key columns. A column you filter on constantly, like `scores.player_id`, usually needs a database index added.
  • The ID is not the row's position. Sorting a table or deleting rows never renumbers IDs, and gaps in the sequence are normal.

Frequently asked questions

Can a table have more than one primary key?

No. A table has exactly one primary key, but that key can be made of several columns together. Other columns that must be unique, like an email, get a separate unique constraint.

Should I use numbers or UUIDs as IDs?

Either works. Auto-incrementing numbers are short and readable; UUIDs can be generated anywhere and do not reveal how many rows you have, which is why many Postgres apps default to them.

Can a foreign key point to the same table?

Yes. A `comments` table can have a `parent_id` pointing at another comment for threaded replies, and an `employees` table can have a `manager_id` pointing at another employee.

On this page

  • An everyday example: the library card
  • What makes a good primary key
  • What a foreign key actually protects
  • Why it matters when building with Startbase
  • Common confusions

Keep reading

More in Glossary
Editorial ink illustration of a hand-cranked music box drum plucking a metal comb, the crank handle in ember orange
GlossaryNovember 22, 2026

What is a game loop?

Every real-time game runs one repeating cycle: read input, update the world, draw it. Here is what that cycle looks like and why it decides how your game feels.

3 min read
Editorial ink illustration of a brass stopwatch beside a small wind-up toy car, the second hand in ember orange
GlossaryNovember 22, 2026

What is delta time?

Delta time is the number that keeps your game the same speed on every screen. Here is how to use it, where it breaks, and how to spot a game that forgot it.

3 min read

Read less. Ship more.

Everything in this post is one prompt away. Describe your app and watch it build.

Start building

Apps, games, backends and publishing from one conversation.

Product

  • Features
  • Use cases
  • Pricing
  • Changelog

Resources

  • Blog
  • Docs
  • Support
  • Status
  • Security

Contact

  • w@startbase.ai
  • X / Twitter
  • LinkedIn
  • Instagram

Legal

  • Terms
  • Privacy

© 2026 Startbase. All rights reserved.