Taco8703
Taco8703

Reputation: 65

How to display NULL when criteria not met

I have this table

Column1  Column2
1        value1
2        value2
3        value3
4        value4

Using this statement:

SELECT * FROM table WHERE column2='value2'

Only displays this:

Column1  Column2
2        value2

I want to display this:

Column1  Column2
1
2        value2
3
4  

How?

Upvotes: 3

Views: 1742

Answers (1)

Aaron Bertrand
Aaron Bertrand

Reputation: 280625

Well, your WHERE clause is saying "show me the rows where column2 = value2" - so, as written, it can't possibly include any rows where column2 has any other value, because they've been filtered out.

Here's one way to accomplish what you're looking for, using a CASE expression (and no WHERE clause):

SELECT column1, column2 = CASE 
  WHEN column2 = 'value2' THEN 'value2'
  ELSE NULL
END
FROM dbo.table;

Upvotes: 6

Related Questions