1

I have to query data in the database, have the following table

COLUMNS:  Type, Location, name, etc.

DATA:
 1. Stores in NJ, name = xyz
 2. Restaurants in NY
 3. Hotels in US
 4. Stores in PA
 5. Restaurants in VA
 6. Hotels in MD
 7. Stores in NJ, name = abc
 8. etc.

I need a query, to fetch the data from 1, 2, 3

Right now, I have the following query. This runs faster. But is there any other query I can use without UNION

select type, location from table1 
where type='stores' and location='NJ' and name='XYZ'
  UNION
select type, location from table1 
where type='restaurants' and location='NY'
  UNION
select type, location from table1 
where type='hotels' and location='US'
1
  • Don't use union in a situation like this. It will try to do a distinct, which means that you're unnecessarily de-duplicating. Commented Jun 6, 2012 at 16:08

2 Answers 2

2

You can use OR:

select type, location from table1 
where (type='stores' and location='NJ' and name='XYZ')
or (type='restaurants' and location='NY')
or (type='hotels' and location='US');
Sign up to request clarification or add additional context in comments.

2 Comments

thanks Andrew for your answer. I tried this, it is taking considerable time compared to my previous query. My table contains huge amounts of data.
Do your tables have accurate (enough) statistics?
1

UNION ALL is faster then using OR and prolly is what you really need:

select type, location from table1 
where type='stores' and location='NJ' and name='XYZ'
  UNION ALL
select type, location from table1 
where type='restaurants' and location='NY'
  UNION ALL
select type, location from table1 
where type='hotels' and location='US'

If you really want the OR:

select type, location from table1 
where (type='stores' and location='NJ' and name='XYZ')
or (type='restaurants' and location='NY')
or (type='hotels' and location='US');

To make your query faster, create indexes on type, location and name columns!

5 Comments

ya, tried OR, but my query is very slow now. Is there anything I can use such as scalar subquery etc. If so, what will the syntax be for that.
To make it faster create indexes on type, location and name columns!
Thanks aF. I created index as suggested by you. Still no luck.
@user12121 - it would help to know what indexes you have on TABLE1, how up-to-date the statistics are, how many rows you have in the table, how many rows exist for each of the conditions you're querying, the rewritten query you're using, and the plan Oracle generates for the rewritten query.
Thanks everyone for your help. I looked at the query plan and I saw where the problem is coming from.

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.