I just recently started using a SQL database for my new project and I have a question regarding one-to-many relationships.
A simplified example: let's say we have a User
that can define a list of Persons
(e.g. let's think of a Sims game). Each user just creates their own persons, a person can not be shared between users.
So we have a list of Users
, each user has a list of Persons
. I would now represent this in SQL like this (sorry if I don't use any official SQL representing syntax...):
Table Users
id: uuid (primary key)
Table Persons:
owner: uuid (foreign key from `Users`)
number: integer (auto-increment, starting from 0)
primary key: composite of owner and number
name: text
age: integer
gender: text
etc.
So now if I want to get a list of all Persons
that belong to a user, I can simply query the Persons
table to get all elements where the owner corresponds to the user. Ok.
Now my question: isn't that totally inefficient? I mean, if we have 1 million Users
that created 10 million Persons
, the SQL database has to query 10 million Persons
to find the maybe 5 persons that belong to the current user?
Wouldn't it be more efficient to add a list of persons to the Users
table, such that the "lookup" can happen faster? E.g. should I update the Users
table to this?
Table Users
id: uuid (primary key)
persons: list of uuid (foreign key from Persons)
Table Persons:
id: uuid (primary key)
etc.
I have seen in all recommendations that the first approach is better and more "SQL" like, but I guess the second approach must be orders of magnitude faster?
Thank you guys!