How can I write an efficient SQL query that returns columns form table A plus a bit column that specifies whether the PK of table A exists in table B? I am using MS SQLServer 2005. Thanks.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends if the foreign table relationship is 1:1 or 1:Many. If is 1:1 the you can use a normal join:
If the relation is 1:Many then the join would multiply the result, so you have to restrict it, and there are several ways. A simple way is using outer apply and top:
As for performance, almost all solution proposed will perform the same, provided there is an appropriate index on B(id) in place.