0

I am working in SQL Server 2012. I know I can use there 'where' clause in a query to do a multi-variable search on a single column, eg.:

select * from cars where manufacturer in ('Ford', 'Toyota')

would return all rows that have Fort or Toyota as the manufacturer. However, what if I needed to be more specific, and I wanted to see cars made from Ford in 1995, and cars made in Toyota in 1996? Doing a query like this:

select * 
from cars 
where manufacturer in ('Ford', 'Toyota') 
  and year in ('1995', 1996)

would bring me back the data I needed, but also cars Toyota made in 1995, and cars Ford made in 1996, which I do not want in my dataset. I've seen some suggestions to do a query like this:

select * 
from cars 
where (manufacturer, year) in (('Ford', '1995'), ('Toyota', 1996))

However, this does not compile... I'm thinking this is a MySQL query. I would also like to be able to take the parameters for the where query from other tables, and not have to type in 'Ford', 'Toyota', '1995' every time I want to search

1
  • Why use INinstead of AND, OR? The last statement isn't standard SQL Commented Jan 22, 2016 at 16:21

2 Answers 2

2

Maybe this is what you are looking for?

select * from cars 
where (manufacturer = 'Ford'   and year = '1995') 
   or (manufacturer = 'Toyota' and year = '1996')
Sign up to request clarification or add additional context in comments.

5 Comments

That works for single queries, thanks! What if I had 100 (manufacturer + year) year combinations in a separate temp table? I liked using 'in' because I can run queries against it, but I am not seeing how I can make a subquery that would automatically return the combinations without me keying them in by hand
@user856358 If that was the case you should probably consider using a join instead and specify the predicate as the join condition instead of in the where clause.
I think I understand, so instead of doing a where query, do a table join on manufacturer in (a,b,c) and year in (x,y,z), and let the join do the filtering?
@user856358 Something like that; hard to say exactly how to do it without any sample data and desired results. Maybe you should post a new follow-up question if you want more precise suggestions.
I wasn't even thinking about using joins to filter, I feel like this put me on the right track.
1

Just right the filter as you typed it in the question:

WHERE 
    (manufacturer='Ford' and year=1995) or 
    (manufacturer='Toyota' and year=1996)

There's no need to overcomplicate the WHERE statement. In fact, where (manufacturer, year) in (('Ford', '1995'), ('Toyota', 1996)) isn't standared SQL

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.