Does join ordering matter in sql?
I am using postgresql, suppose I am having two tables one is user(name,age,comment_id) and other is comment(comment_id, text) , now there are billions of users but thousands of comments. Does the order in which joins are written in where clause matters?
Ex : Query 1
select a.name, b.text
from user as a, comment as b
where
b.comment_id = 1 and
a.comment_id = b.comment_id
Ex : Query 2
select a.name, b.text
from user as a, comment as b
where
a.comment_id = b.comme开发者_C百科nt_id and
b.comment_id = 1
The join order does not matter for inner joins, but it does matter for outer joins.
As far as I read your code you don't use any join at all. You create the whole cartesian product and then filter with WHERE. Let's hope your query optimizer takes care of that.
And yes, it does matter. Always try to do the more selective (which kills more rows from the cartesian product) first and take a look at the QEP of your DBMS.
Your query should read something like:
select a.name, b.text from
user as a
[left|right|inner|outer] join comment as b on a.comment_id = b.comment_id
where b.comment_id = 1
Join order does not matter until you hit thresholds. One threshold makes the Geqo kick in, the other two kick in when the number of explicit and implicit joins is too great.
In the where clause, order is irrelevant and PG reserves the right to reorder everything based on boolean logic. This makes this query dangerous:
select 1 from stuff where x <> 0 and y / x > 1 -- should use case instead
精彩评论