1

mytable contains records for id 1, 2, 3, 10, 12 and 20, and specifically does not include records for id 5 and 15.

How can I perform some query such as:

SELECT id, id IN (1,5,10,15,20) AS status
FROM mytable
WHERE id IN (1,5,10,15,20);

and return records:

id  status
1   true
5   false
10  true
15  false
20  true

If there was some other table, I could just outer join mytable, but there is none. The following will certainly not work, but is there some sort of fictional table I can join against?

SELECT id, isnull(mytable.id) AS status
FROM *
LEFT OUTER JOIN mytable
WHERE id IN (1,5,10,15,20);

1 Answer 1

1

You can create a derived table in the FROM clause:

SELECT i.id, (t.id is not null) AS status
FROM (SELECT 1 as id UNION ALL SELECT 5 UNION ALL SELECT 10 UNION ALL SELECT 15 UNION ALL SELECT 20
     ) i LEFT JOIN
     mytable t
     ON i.id = t.id;
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, I have never used a derived table such as this one, but only dynamically generate the IN list. Potentially going to be big and ugly (could have hundreds of thousands of rows). Concerns? Maybe best to leave it to the application?
@user1032531 better to leave it to the application
@M0rtiis Will do. Thanks

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.