I am learning Oracle SQL on the job, and am looking for some (ideally compact and efficient) conditional expression that evaluates to true if any item in list A occurs in list B.
I have a table IVS
with a column of values CODES
, and a table POP
with a collection of columns (CDE_VAL_1
through CDE_VAL_26
). For any row/record in POP
, each of the CDE_VAL_*
fields may contain a value from the IVS.CODES
column, or else contain NULL
. Say I have a subset of IVS
(call it IVS_sub
), then I am looking for a way select the subset of POP
such that each selected record has some code from IVS_sub.CODES
in any one of the CDE_VAL_*
fields.
I have code that "works" but runs too slowly for me to test my code more than once or twice in a day. Obviously this is prohibitively slow, I need to be able to test and rewrite/fix the code with reasonable turnover.
This is my current (slow) method as a minimal example:
SELECT DISTINCT * FROM POP
INNER JOIN IVS
ON IVS.CODES IN (CDE_VAL_1, /*... pretend i listed them all here*/, CDE_VAL_26)
Note that the actual query I'm running is much more complicated, has a couple other joins, filtering, etc (that being said, I am positive that my bottleneck is this issue, removing the IVS join takes the query from ~2.5 hours to ~10 minutes).
I have also tried:
SELECT DISTINCT * FROM POP
INNER JOIN IVS ON (CDE_VAL_1 IN IVS.CODES
OR CDE_VAL_2 IN IVS.CODES
/* ... */
OR CDE_VAL_26 IN IVS.CODES)
However, this is cluttered and ugly, and more importantly it makes the code harder to follow. It also doesn't seem to run particularly faster, at least for small test queries I've run.
Preferably I'd like to end up with something like
SELECT * FROM POP
/* other joins and stuff */
INNER JOIN IVS ON ANY_OF(CDE_VAL_1, ... ) IN IVS.CODES
WHERE /*where conditions*/
or similar, where ANY_OF(...) IN ...
is just standing in for whatever solution. Ideally that solution would be a relatively compact snippet with a clear meaning at a glance.
Conceptually this is just "If the intersection of these two lists isn't empty", but so far I haven't seen anything like that.
(Note: We aren't using PL/SQL, just pure Oracle SQL queries, though if there are solutions that require PL/SQL I'd be interested in hearing them, if only to use them as ammo to convince my boss to get us some training or something for it.)