Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi!

I'm a newbie to MS SQL! I have a doubt regarding IN Keyword.

Please explain the difference in these queries

With IN Keyword
SQL
SELECt * FROM Products
WHERE UnitPrice IN (SELECT UnitPrice FROM Products Where UnitPrice >10)


Without IN Keyword
SQL
SELECt * FROM Products
WHERE UnitPrice = (SELECT UnitPrice FROM Products Where UnitPrice >10)


Thanks in advance!
Posted

Simple: The first will work, the second will fail.

That's a generalisation, but it's also true. The second will fail the moment there is more than one Product where the UnitPrice is greater than 10, because the subquery
SQL
SELECT UnitPrice FROM Products Where UnitPrice >10
will return more than one value, and the equality test cannot cope with that.

The IN clause says "matches any of these values" so it will work with one or more Products where the UnitPrice is greater than 10.
 
Share this answer
 
Comments
Abhinav S 17-Jan-13 4:25am    
Correct and 5.
The OP will get an error in such a scenario.
here
SQL
SELECt * FROM Products
WHERE UnitPrice = (SELECT UnitPrice FROM Products Where UnitPrice >10)



SELECT UnitPrice FROM Products Where UnitPrice >10 if this query return more than one value error will throw. that means you can assign more than one value to Unitprice
.but if you use in operator i it will check the unit price selected and will get appropriate one.
like
SQL
SELECt * FROM Products
WHERE UnitPrice IN (10,11,12,13)
// willnot throw error

XML
<pre lang="sql">SELECt * FROM Products
WHERE UnitPrice =(10,11,12,13)</pre>
//throw error
 
Share this answer
 
Comments
Abhinav S 17-Jan-13 4:25am    
5.
IN vs. JOIN vs. EXISTS[^] is an article that should help you understand the difference between these two queries in terms of performance and other factors.
 
Share this answer
 
Comments
OriginalGriff 17-Jan-13 4:21am    
It's a bit more fundamental than that, Abhinav - what happens if there are two products with a unit price of 11? :laugh:
Abhinav S 17-Jan-13 4:25am    
Ah the classic subquery returned multiple records error.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900