I have a two tables that look like this (this is an example of what I actually have).
Table 1:
Yr, Value
1990, 1
1990, 2
1991, 2
1992, 3
Table 2:
Dte, Value2, ID
1/1/1990, 10, 1
1/2/1990, 11, 1
1/3/1990, 12, 2
1/1/1991, 20, 1
1/2/1991, 21, 2
I would like to join the two tables first using a left join first, then discard some of the values from the joined set, then group by ID. The code I have written looks something like this:
select avg(Value2) v2
from table2
left join table1 on (year(dte)=yr)
where Value>1
group by ID;
Does the join get performed first and then the filter condition in the where statement discard the rows from the merged table or does the where condition get evaluated first and then the join? The example above is just for illustration and this is a more general question about how the SQL does the operation.
this depends on the order in which your tables are stated and the order of your
wheres. in this case, the where is executed afterwards. so it would be more efficient to declare the tables in the inverse order, since you have the where clause for table1.the way you do it, all the rows from table1 are joined with the rows from table2 using the on-clause to narrow it down. then, last, the where clause is used on the result of the join. however, like this:
the where clause is executed first on table1, then the join is performed using the on-clause. this is done on the already reduced version of table1, and therefor it’s more efficient.