In the given schema, there is a table A having column A1,A2,A3,A4
There are three more tables i.e. B,C,D
If the value in A4 is b, i have to lookup table B. If the value in A4 is c, i have to lookup table C. If the value in A4 is d, i have to lookup table D.
Currently, we have implemented using switch case i.e.
select * from A
where
CASE
WHEN SUBSTRING(A4,4,3) IN ( '023','009','011','013','015','017','019','021')
THEN A3 NOT IN ( select Z from B)
WHEN SUBSTRING(A4,4,3) IN ( '006','024','028','031')
THEN A3 NOT IN ( select Z from C)
WHEN SUBSTRING(A4,4,3) IN ( '004','025')
THEN A3 NOT IN ( select Z from D)
END
Is there any better and more efficient way to resolve this problem?
Best Answer
First of all, append a computed column, say
A4Key
, set toSUBSTRING(A4, 4, 3)
.This column shall be kept up-to-date either by your application code or by triggers, such as:
first solution
Then, rewrite your query to:
Now, evaluate your query plans to devise the best indexes.
second solution
Create a table such as:
With initial data set by:
And keep it up-to-date with the changing (?) data from B, C and D.
Done that, now you may, with blazing performance (after creating some indexes):