Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

i have a small doubt, this is my query

declare @table table(id int, name varchar(100))

insert into @table values (1,'a')
insert into @table values (2,'b')
insert into @table values (3,'c')

select * from @table where id in (1,2,5)

as you can see, in the above query i hard coded 1,2,5 in the select statement. but now i want to read them from another table, so i tried as:

declare @table2 table(id int)

insert into @table2 values (1)
insert into @table2 values (2)
insert into @table2 values (5)

select t1.* from @table t1 join @table2 t2 on t1.id=t2.id

i used join here. for both the queries im getting the same result. is this the proper way. i mean instead of hard coding, im taking the values from a table.

share|improve this question
It is worth mentioning that the second query would only be equivalent to the first if you could guarantee that the id column in @table2 was unique. Otherwise, the join operation would generate duplicate rows and you would want to use one of the alternatives suggested in Guffa's answer. – Cheran Shunmugavel Oct 21 '12 at 7:14
CheranShunmugavel, yes @table2 will contain only unique values. – Harsha Oct 23 '12 at 5:49

2 Answers

up vote 3 down vote accepted

Yes, that is the correct way.

You can also use:

select * from @table where id in (select id from @table2)

Or:

select * from @table t1 where exists (select * from @table2 t2 where t1.id = t2.id)

If the query optimiser manages it right, those will be executed exactly the same way as the join.

share|improve this answer

Additionally you could also write:

SELECT * FROM @table t1 JOIN @table2 t2 USING(id);

if the columns in both tables are named identically.

share|improve this answer
i think i forgot to mention, im using sql server and using keyword doesnt support here. anyway thank you for the answer. – Harsha Oct 19 '12 at 17:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.