0

I have to run multiple selects on a table for and get resultset for 2 columns. One solution i found is by using UNION as below.

SELECT cap_id, cap_code FROM cap_master
where cap_type = 'Type1' and cap_desc = 'CapDesc1' 
 UNION
SELECT cap_id, cap_code FROM cap_master
where cap_type = 'Type2' and cap_desc = 'CapDesc2' 

Is there any other way to do this. There could be some 10-20 select statements in one go. Will this affect performance, if so what would be a better approach.

1 Answer 1

1

I think you should just be able to use one query with a larger WHERE clause using OR statements.

Example

SELECT cap_id, cap_code
FROM cap_master
WHERE (cap_type = 'Type1' AND cap_desc = 'CapDesc1`) 
    OR (cap_type = 'Type2' AND cap_desc = 'CapDesc2')

That is a least a starting point for getting results for only when the cap_type and cap_desc are specific values.

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

2 Comments

Thanks Dan!! This will reduce my query a lot. Any idea, will this cause any performance overhead if have have 10-20 conditions ? If yes, what is the better approach?
I don't know your use case, but it would seem having those conditions means you aren't using your query in the right place within your solution. I can't speak to a better approach there. I do know UNION will try to sort through duplicates, which you shouldn't have. There is another question that digs into performance between the two query options that you can view here. From my experience, OR statements tend to work better than multiple result-sets using UNION or UNION ALL

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.