I would like to discuss this simple postgres query and figure out if I have got a bit of the theory behind postgres and DBs in general. Here it comes:
-- Query 1
SELECT posts.*, users.*
FROM posts INNER JOIN users
ON posts.user_id = users.id
WHERE
posts.user_id = :id
ORDER BY posts.creation_time
It clearly involves two tables (users
and posts
) which are joined together. There is a index on (posts.creation_time
, posts.user_id
) to speed up the search.
My understanding is that I ALSO need a foreign key that associates posts.user_id
to users.id
not only to enforce a form of referencial integrity as such, but olso, and probably more importantly, to speed up the ON posts.user_id = users.id
bit of the query.
Am I right in saying so?
Now conside this version of the query:
-- Query 2
SELECT posts.*, users.*
FROM posts INNER JOIN users
ON posts.user_id = users.id
WHERE
users.id = :id
ORDER BY posts.creation_time
Assuming the aforementioned foreign key (posts.creation_time
, posts.user_id
) exists, would this query scale, taking into account the variable in the equation lives on the other side of the join?
My guess is that it won't scale
Thanks