Table relationships in Supabase - Time & Space Complexity
When working with table relationships in Supabase, it's important to understand how the number of related records affects the time it takes to fetch data.
We want to know: how does the time to get related data grow as the amount of related data grows?
Analyze the time complexity of fetching a user and their related orders.
const { data, error } = await supabase
.from('users')
.select('id, name, orders(*)')
.eq('id', userId)
This code fetches one user by ID and includes all their related orders in the result.
Here are the key operations that repeat:
- Primary operation: Fetching each related order record from the orders table.
- How many times: Once for each order linked to the user.
As the number of orders for a user grows, the time to fetch all orders grows roughly the same way.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 orders | Fetching 1 user + 10 orders |
| 100 orders | Fetching 1 user + 100 orders |
| 1000 orders | Fetching 1 user + 1000 orders |
Pattern observation: The time grows linearly with the number of related orders.
Time Complexity: O(n)
This means the time to fetch data grows directly in proportion to the number of related records.
[X] Wrong: "Fetching related data is always a single fast operation regardless of size."
[OK] Correct: Each related record adds to the total data fetched, so more related records mean more time.
Understanding how related data fetching scales helps you design efficient queries and explain your reasoning clearly in real-world situations.
"What if we only fetched the count of related orders instead of all order details? How would the time complexity change?"