select TABLE1.FIELD1,
TABLE1.FIELD2,
TABLE1.FIELD3,
TABLE1.FIELD4,
TABLE1.FIELD5,
TABLE2.FIELD6,
TABLE2.FIELD7
from TABLE1,
TABLE2
where TABLE1.FIELD8 = 'value'
and TABLE2.FIELD6 = TABLE1.FIELD6;
I am searching for some data from 2 different tables.
(Oracle database – wherefields indexed for both tables)
The above query is taking 500ms to be executed.
When I search the tables seperately for the same fields
they finish in less than 20ms each.
I could search TABLE1 for the data I need (+FIELD6)
and then search TABLE2 for the rest using FIELD6.
My question is. Why is it so much slower when I join the tables.
Am I doing something wrong?
EDIT: Adding oracle’s explain plan
PLAN_TABLE_OUTPUT
----------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost |
----------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 6318 | 586K| 620 |
| 1 | HASH JOIN | | 6318 | 586K| 620 |
| 2 | TABLE ACCESS BY INDEX ROWID| TABLE1 | 6318 | 450K| 2 |
| 3 | INDEX RANGE SCAN | INDEX_TABLE1_FIELD8 | 2527 | | 1 |
| 4 | TABLE ACCESS FULL | TABLE2 | 430K| 9242K| 508 |
----------------------------------------------------------------------------------------
Note: cpu costing is off, 'PLAN_TABLE' is old version
I can’t see anything wrong with your query, and the (good) advice given in other answers will help you understand what is going on in detail.
In concept, however, you have to bear in mind the order of the data in each table, and whether the data is grouped up or spread out. It’s all well saying “it only takes 20ms to find”, but how long will it take to match the two data sets?
If both data sets are Known to be in the same order, the RDBMS can align them relatively quickly. But the RDBMS can only know this from an index.
If you have an index on Table1 that is Field8 then Field6, all the “values” will be lumped together, then ordered by Field6. If, however, you have an index of Field6 then Field8, the records you’re interested in will be ordered but spread out through the index. Finally, if you don’t have indexes on these fields, everything will be randomly ordered and spread out.
Depending on these types of factor, there are literally dozens of ways the RDBMS may complete your query. For best performance, one needs to understand what the RDBMS would need to do, then give it the index(es) to make it as easy as possible.