Friday 14 August 2015

Tip - IN clause other way around

How to do you write a query to fetch the records from a table where particular value is present in 2 different columns or in either of them ? 

Phewww.. pretty simple isn't it ?

Let us give it a shot...

DECLARE @TAB TABLE
(
ID SMALLINT,
NUM SMALLINT
)

INSERT INTO @TAB
SELECT 1,1 UNION ALL
SELECT 2,1 UNION ALL
SELECT 3,3 UNION ALL
SELECT 1,4

With reference to the question raised @ the top we have to write a query to find the records containing 1 in either of the columns from @TAB or featuring in both of them.. 



SELECT * FROM @TAB
WHERE ID = 1 OR NUM = 1

--OR 

SELECT * FROM @TAB
WHERE ID IN (1) OR NUM IN (1)

Those who had either of the above answer in mind have hit the bulls eye. 

Now where is fun if there isn't the twist .. what would you say if I tell you that there is one more way to write IN clause query ..

This is how...

SELECT * FROM @TAB
WHERE 1 IN (ID,NUM)

Bamboozled, are you ? And I am not kidding you..  Yes, we can use IN clause other way around.. Cooooool, isn't it ? Well have fun.

No comments:

Post a Comment

bloggerwidgets