0
0
Supabasecloud~3 mins

Why Primary keys and foreign keys in Supabase? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your data could organize itself perfectly and never get mixed up again?

The Scenario

Imagine you have a big notebook where you write down all your friends' phone numbers and addresses. But you don't have any order or system. When you want to find one friend's number, you have to flip through every page, hoping to find it.

The Problem

Without a clear system, finding or linking information becomes slow and confusing. You might write down the same friend's number twice by mistake or mix up addresses. This causes errors and wastes time when you want to update or check details.

The Solution

Primary keys and foreign keys act like labels and links in your notebook. A primary key is a unique label for each friend, so you never confuse one with another. A foreign key is like a reference that connects one friend's info to another, making it easy to find related details quickly and accurately.

Before vs After
Before
INSERT INTO friends (name, phone) VALUES ('Alice', '12345');
INSERT INTO addresses (friend_name, address) VALUES ('Alice', '123 Main St');
After
CREATE TABLE friends (id SERIAL PRIMARY KEY, name TEXT, phone TEXT);
CREATE TABLE addresses (id SERIAL PRIMARY KEY, friend_id INT REFERENCES friends(id), address TEXT);
What It Enables

It makes your data organized and connected, so you can quickly find, update, and trust your information without mistakes.

Real Life Example

When an online store tracks customers and their orders, primary keys identify each customer uniquely, and foreign keys link each order to the right customer, ensuring orders don't get mixed up.

Key Takeaways

Primary keys give each record a unique ID to avoid confusion.

Foreign keys link related data across tables for easy connection.

This system keeps data accurate, organized, and easy to manage.