I have two sql queries as following
SELECT rc.stateId,rs.stateName FROM
(SELECT DISTINCT cityid FROM HolidayPackageCity) AS hpc
INNER JOIN
(SELECT cityid,stateid FROM RegCity WHERE countryCode='IN' AND stateId IS NOT NULL) AS rc
ON hpc.cityId=rc.cityId
INNER JOIN
RegState AS rs
ON rc.stateId=rs.stateId
vs
SELECT DISTINCT rc.stateId,rs.stateName
FROM HolidayPackageCity AS hpc
INNER JOIN
RegCity AS rc
ON hpc.cityId=rc.cityId
INNER JOIN
RegState AS rs
ON rc.stateId=rs.stateId
WHERE rc.countryCode='IN' AND rc.stateId IS NOT NULL
In first query first i filter the data of a particular table then apply joining and in second table first i apply joins then i apply where condition to filter the data.
The thing i want to know is which one is faster from both of that and why.
Second query is faster, because optimizer would first filter table with where clause, and then create internal temp table which later use for join. Conclusion – better solution is join with tables which contains smaller data sets.
By the way, optimizer easier deal with second query, which no contains subqueries.