When we create a join between 2 tables in Oracle, with some additional filter condition on one or both tables, will oracle join the tables first and then filter or will it filter the conditions first and then join.
Or in simple words, which of these 2 is a better query
Say we have 2 tables Employee and Department, and I want employees all employee + dept detail where employee salary is grater than 50000
Query 1:
select e.name, d.name from employee e, department d where e.dept_id=d.id and e.salary>50000;
Query 2:
select e.name, d.name from (select * from employee where salary>50000) e, department d where e.dept_id=d.id;
Generally it will filter as much as possible first. From the explain plan, you can actually see where the filtering is done, and where the joining is done, for example, create some tables and data:
Now if I explain both the queries you provided, you will find that Oracle transforms each query into the same plan behind the scenes (it doesn’t always execute what you think it does – Oracle has license to ‘rewrite’ the query, and it does it a lot):
Notice the filter operations applied to the query. Now explain the alternative query:
Once you learn how to get the explain plans and how to read them, you can generally work out what Oracle is doing as it executes your query.