2

I have multiple IN conditions with subqueries.

SELECT
    S.name,
    S.email
FROM something S
WHERE 
    1 NOT IN (SELECT id FROM tags WHERE somethingId = S.id)
    AND 2 NOT IN (SELECT id FROM tags WHERE somethingId = S.id)
    AND 3 NOT IN (SELECT id FROM tags WHERE somethingId = S.id)

Maybe there are better solutions? Something like:

    (1, 2, 3) NOT IN (SELECT id FROM tags WHERE somethingId = S.id)
2
  • 1
    Do a NOT EXISTS instead. (Which is also null-safe.) Commented Jan 5, 2017 at 9:00
  • 1
    You should prefere JOIN or EXISTS() as they are faster and more flexible in many situations. Commented Jan 5, 2017 at 9:01

1 Answer 1

4

Re-write to use NOT EXISTS instead. I.e return from S when there is no row in tags with somethingId equals to s.id and id is 1, 2 or 3.

SELECT
    S.name,
    S.email
FROM something S
WHERE NOT EXISTS (SELECT 1 FROM tags WHERE id in (1, 2, 3) and somethingId = S.id)

Also NOT EXISTS is "null-safe". (NOT IN (select returning a null) will return no rows at all.)

Sign up to request clarification or add additional context in comments.

1 Comment

I'm idiot... I could thought about that my self... :( Thank you. I will accept your answer as soon as I can.

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.