11

I need help writing a conditional where clause. here is my situation:

I have a bit value that determines what rows to return in a select statement. If the value is true, I need to return rows where the import_id column is not null, if false, then I want the rows where the import_id column is null.

My attempt at such a query (below) does not seem to work, what is the best way to accomplish this?


DECLARE @imported BIT

SELECT id, import_id, name FROM Foo WHERE
    (@imported = 1 AND import_id IS NOT NULL)
    AND (@imported = 0 AND import_is IS NULL)

Thanks.

3 Answers 3

19

Change the AND to OR

DECLARE @imported BIT

SELECT id, import_id, name FROM Foo WHERE
    (@imported = 1 AND import_id IS NOT NULL)
    OR (@imported = 0 AND import_is IS NULL)

Decomposing your original statement

you have essentially written

    @imported = 1 
    AND import_id IS NOT NULL
    AND @imported = 0 
    AND import_is IS NULL

wich is equivalent to

    @imported = 1 AND @imported = 0 
    AND import_id IS NOT NULL AND import_is IS NULL

what results in two pair of clauses that completely negate each other

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

Comments

2

I think you meant

SELECT id, import_id, name FROM Foo WHERE
    (@imported = 1 AND import_id IS NOT NULL)
    OR (@imported = 0 AND import_is IS NULL)
    ^^^

Comments

1

Your query would require an OR to select between the different filters. It's better for the optimizer if you use separate queries in this case. Yes, code redundancy is bad, but to the optimizer these are radically different (and not redundant) queries.

DECLARE @imported BIT

IF @imported = 1
  SELECT id, import_id, name
  FROM Foo
  WHERE import_id IS NOT NULL
ELSE
  SELECT id, import_id, name
  FROM Foo
  WHERE import_id IS NULL

2 Comments

Thanks for the suggestion, but the query I gave was just an example, it is much more complicated, so splitting them like this is not feasible at the moment.
More complexity -> more reason to break up this into the correct number of queries. stackoverflow.com/questions/266697/…

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.