0

I need to select from all users that are not present in a set of other sub queries:

SELECT user_id
FROM (<userSubQuery1>)
WHERE 
    user_id NOT IN (<badUserSubQueryA>) AND
    user_id NOT IN (<badUserSubQueryB>) AND
    user_id NOT IN (<badUserSubQueryC>)

Only I need to do the NOT IN filters in many different queries where the userSubQuery and the badUserSubQueries may be different. E.g.:

SELECT user_id
FROM (<userSubQuery2>)
WHERE 
    user_id NOT IN (<badUserSubQueryB>) AND
    user_id NOT IN (<badUserSubQueryC>) AND
    user_id NOT IN (<badUserSubQueryD>)

All the sub queries, both the ones I'm selecting from and the once used in the NOT IN are complex so I don't want to duplicate the code for the NOT IN sub queries which are often the same (badUserSubQueryB and badUserSubQueryC in my example).

I could achieve this with dynamic sql but I'd rather not if I can avoid it. Is it possible?

3 Answers 3

2

How about storing all the bad user IDs in an indexed temporary table from which you can filter?

Sign up to request clarification or add additional context in comments.

5 Comments

As it's oracle, you could also use a materialized view for each of the subqueries.
How about not using performance impacting and resource draining implementations to solve what is actually a problem with the development process?
I considered having a functions that returns a plsql collection with the union of the result of all the badUserSubQueries. How would that compare performance wise to putting them in a temp table?
@user948705 In this case you could create a pipelined function returning the invalid user ids as if they were coming from a table akadia.com/services/ora_pipe_functions.html
why not create a "isUserOk(user, type)" function? (where type is "abc" or "bcd"). but then i would use dynamic sql to add the appropriate badUserSubqueries
2

How about creating a view for each complex subquery that you want to reuse?

1 Comment

Ye if I also put the userSubQuery in a view that would help. But I'd still need to have a separate query (although simpler) for each combination.
0

I would have a crack at it like this:

Try to think of this in reverse logic like this

SELECT user_id
FROM (<userSubQuery1>)
MINUS
(
SELECT useri_id
  FROM <badUserSubQueryB> 
UNION
SELECT useri_id
  FROM <badUserSubQueryC> 
UNION
SELECT useri_id
  FROM <badUserSubQueryD>
)

Let me know how it goes

Cheers , Alex

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.