Primary keys and foreign keys in Supabase - Time & Space Complexity
When working with primary keys and foreign keys in Supabase, it's important to understand how the number of database operations grows as data increases.
We want to know how the time to insert or query data changes when tables have these keys.
Analyze the time complexity of inserting rows with primary and foreign keys.
// Insert a new user
const { data: user } = await supabase
.from('users')
.insert([{ id: 1, name: 'Alice' }])
.select()
// Insert a new order linked to the user
const { data: order } = await supabase
.from('orders')
.insert([{ id: 101, user_id: 1, product: 'Book' }])
.select()
This sequence inserts a user with a primary key and an order referencing that user via a foreign key.
Look at the main database calls that happen repeatedly as data grows.
- Primary operation: Insert row into 'users' and 'orders' tables.
- How many times: Once per new user and once per new order.
Each insert checks keys to keep data consistent. As you add more rows, each insert still does a quick check.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 users + 10 orders | 20 insert operations |
| 100 users + 100 orders | 200 insert operations |
| 1000 users + 1000 orders | 2000 insert operations |
Pattern observation: The number of operations grows directly with the number of rows inserted.
Time Complexity: O(n)
This means the time to insert rows grows linearly with the number of rows you add.
[X] Wrong: "Adding foreign keys makes inserts take much longer as data grows exponentially."
[OK] Correct: Foreign key checks are efficient and use indexes, so insert time grows linearly, not exponentially.
Understanding how keys affect database operations shows you can design data that stays fast and reliable as it grows.
"What if we added an index on the foreign key column? How would that affect the time complexity of inserts and queries?"
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
