I have two tables, TableA and TableB.
TableA is a large dataset with thousands/millions of record and has a unique key (ID) and 3 alternate keys (NAME,SCHOOL,DATE).
Table B is a smaller dataset with thousands of record and has no unique keys.
TableA --------- ID NAME SCHOOL DATE RECORD STATUS
TableB --------- NAME SCHOOL
Now, I need to join these two tables to get the list of unique IDs to be use in another query. Below is the sample query, but this took so long more hours to run.
SELECT a.ID AS ID_key, a.school, a.name
FROM TableA a, TableB b
WHERE a.name = b.name
AND a.school = b.school
AND a.status = 'Active'
Is there any way to optimize this query? Thanks in advance.
Why are you joining the tables at all if all the information required is in table A?
The only possible reason I can think of is if you want to exclude rows in A that don’t have a corresponding row in B but, if your schema is set up properly, you would probably have a foreign key constraint to enforce that.
If that’s not the case, get rid of the join altogether:
If there is a valid reason for the join (and, from your comment, that seems to be the case), make sure that you have indexes on
nameandschoolin both tables, and that your runstats (or whatever Oracle calls its query optimisation data) are up to date.Also run a query analysis (
explain) on that query to find out where the problem lies. Once you have that as a baseline, you can begin modifying things (like adding indexes) to see if the query improves. Remember the #1 mantra for optimisation: measure, don’t guess!