Primary keys and foreign keys help keep data organized and connected in databases. They make sure each piece of data is unique and related to the right information.
Primary keys and foreign keys in Supabase
CREATE TABLE table_name ( column_name data_type PRIMARY KEY, other_column data_type, foreign_key_column data_type REFERENCES other_table(primary_key_column) );
The PRIMARY KEY ensures each row is unique.
The REFERENCES keyword creates a foreign key linking to another table's primary key.
CREATE TABLE users ( id SERIAL PRIMARY KEY, name TEXT );
CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), amount NUMERIC );
CREATE TABLE comments ( comment_id SERIAL PRIMARY KEY, post_id INTEGER REFERENCES posts(id), content TEXT );
CREATE TABLE empty_table ( id SERIAL PRIMARY KEY );
This example creates two tables: customers and purchases. Each customer has a unique ID. Each purchase links to a customer using a foreign key. Then it inserts sample data and shows how to get purchase info with customer names.
CREATE TABLE customers ( customer_id SERIAL PRIMARY KEY, customer_name TEXT NOT NULL ); CREATE TABLE purchases ( purchase_id SERIAL PRIMARY KEY, customer_id INTEGER REFERENCES customers(customer_id), purchase_amount NUMERIC NOT NULL ); -- Insert sample data INSERT INTO customers (customer_name) VALUES ('Alice'), ('Bob'); INSERT INTO purchases (customer_id, purchase_amount) VALUES (1, 100.50), (2, 200.75); -- Query to show purchases with customer names SELECT purchases.purchase_id, customers.customer_name, purchases.purchase_amount FROM purchases JOIN customers ON purchases.customer_id = customers.customer_id;
Primary key lookup is very fast because it uniquely identifies rows.
Foreign keys help keep data consistent by preventing invalid links.
Common mistake: forgetting to add a primary key, which can cause duplicate rows.
Use primary keys to identify rows; use foreign keys to connect tables.
Primary keys make each row unique in a table.
Foreign keys link rows in one table to rows in another.
They help keep your data organized and connected.
Practice
primary key in a Supabase table?Solution
Step 1: Understand the role of primary keys
A primary key is used to uniquely identify each row in a table so no two rows have the same key.Step 2: Differentiate from foreign keys
Foreign keys link tables, but primary keys ensure uniqueness within one table.Final Answer:
To uniquely identify each row in the table -> Option CQuick Check:
Primary key = unique row ID [OK]
- Confusing primary key with foreign key
- Thinking primary key speeds up insertion
- Assuming primary key stores large data
Solution
Step 1: Review SQL syntax for primary keys
The correct syntax usesPRIMARY KEY (column_name)to set the primary key.Step 2: Check each option
CREATE TABLE users (id INT, PRIMARY KEY (id)); uses correct syntax. CREATE TABLE users (id INT, FOREIGN KEY (id)); wrongly uses FOREIGN KEY. CREATE TABLE users (id INT UNIQUE); only makes column unique but not primary key. CREATE TABLE users (id INT NOT NULL); only sets NOT NULL.Final Answer:
CREATE TABLE users (id INT, PRIMARY KEY (id)); -> Option AQuick Check:
Primary key syntax = PRIMARY KEY (column) [OK]
- Using FOREIGN KEY instead of PRIMARY KEY
- Using UNIQUE but missing PRIMARY KEY
- Assuming NOT NULL sets primary key
CREATE TABLE authors (id SERIAL PRIMARY KEY, name TEXT); CREATE TABLE books (id SERIAL PRIMARY KEY, title TEXT, author_id INT REFERENCES authors(id));
What happens if you try to insert a book with
author_id that does not exist in authors?Solution
Step 1: Understand foreign key constraints
Theauthor_idinbooksreferencesauthors(id), so it must match an existing author.Step 2: Check behavior on invalid foreign key
Inserting a book with a non-existingauthor_idviolates the foreign key constraint, causing the insert to fail.Final Answer:
The insert will fail due to foreign key constraint violation -> Option AQuick Check:
Foreign key enforces valid references [OK]
- Assuming insert succeeds with invalid foreign key
- Thinking foreign key sets NULL automatically
- Believing foreign key deletes referenced rows
CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT NOT NULL, FOREIGN KEY (customer_id) REFERENCES customers(id) );
When trying to insert an order with
customer_id NULL, you get an error. What is the likely cause?Solution
Step 1: Check NULLability of foreign key column
Foreign key columns allow NULL unless the column definition includes NOT NULL.Step 2: Identify the constraint causing error
Here, customer_id INT NOT NULL prevents inserting NULL values.Final Answer:
Foreign key columncustomer_iddoes not allow NULL -> Option DQuick Check:
NOT NULL on FK column blocks NULL [OK]
- Assuming foreign key columns always allow NULL
- Confusing primary key NULL rules
- Thinking composite key is required here
projects and tasks. Each task belongs to one project. Which setup correctly enforces this relationship with primary and foreign keys?Solution
Step 1: Define primary key on projects
Theprojectstable must have a primary key to uniquely identify each project.CREATE TABLE projects (id SERIAL PRIMARY KEY, name TEXT); CREATE TABLE tasks (id SERIAL PRIMARY KEY, description TEXT, project_id INT REFERENCES projects(id));
and B do this correctly.Step 2: Define foreign key on tasks
Each task must reference a project via a foreign key.CREATE TABLE projects (id SERIAL PRIMARY KEY, name TEXT); CREATE TABLE tasks (id SERIAL PRIMARY KEY, description TEXT, project_id INT REFERENCES projects(id));
correctly usesproject_id INT REFERENCES projects(id).Step 3: Check other options
CREATE TABLE projects (id SERIAL PRIMARY KEY, name TEXT); CREATE TABLE tasks (id SERIAL PRIMARY KEY, description TEXT, project_id INT PRIMARY KEY);
wrongly makesproject_ida primary key in tasks, which is incorrect.CREATE TABLE projects (id SERIAL, name TEXT); CREATE TABLE tasks (id SERIAL PRIMARY KEY, description TEXT, project_id INT);
misses primary key on projects and foreign key on tasks.CREATE TABLE projects (id SERIAL PRIMARY KEY, name TEXT); CREATE TABLE tasks (id SERIAL PRIMARY KEY, description TEXT, project_id INT UNIQUE);
uses UNIQUE onproject_idwhich wrongly restricts tasks to one per project.Final Answer:
CREATE TABLE projects (id SERIAL PRIMARY KEY, name TEXT); CREATE TABLE tasks (id SERIAL PRIMARY KEY, description TEXT, project_id INT REFERENCES projects(id));
-> Option BQuick Check:
Primary key on projects + foreign key on tasks = correct [OK]
- Making foreign key a primary key in child table
- Missing foreign key constraint
- Using UNIQUE on foreign key wrongly
Ready to prove it?
Pass the test and this pattern moves unknown
