Thursday, February 24, 2005 12:34 PM Aylar

SQL 'SELECT CASE' problem

Darren came to me today requesting some help with an SQL  problem had run into; he was trying to return some conditional data using a ‘SELECT CASE’ in his query, but he kept being served NULL values for all the rows that did not match his ‘WHEN’ statements. He tried to check if the returned value from the CASE was a NULL in a WHERE clause:

select
    case
        when shipcountry = 'norway' and @year1 = datepart(yy, orderdate) then employeeid
        when shipcountry = 'brazil' and @year2 = datepart(yy, shippeddate) then employeeid
    end
from orders
where 1 is not null

That didn’t work because what he was checking was whether the column value was NULL or not and not the value of the actual value returned from the CASE. That’s when I suggested the following example to Darren:

select employeeid
from orders
where orderid in (
                  select
                      case
                          when shipcountry = 'norway' and @year1 = datepart(yy, orderdate) then orderid
                          when shipcountry = 'brazil' and @year2 = datepart(yy, shippeddate) then orderid
                      end
                 )

This works perfectly and does exactly what he wanted — you have got to love the power of nested queries ;)

NOTE: the actual sample queries have been modified for the Northwind database for your testing pleasure.

Filed under:

Comments

# re: SQL 'SELECT CASE' problem

Thursday, March 17, 2005 1:27 PM by Brad

I've been trying to avoid using Dynamic SQL in my queries recently using COALESCE in WHERE statements, but couldn't figure out how to use CASE. This is exactly what I needed. Right there in front of me the whole time. Thank you!

# re:SQL 'SELECT CASE' problem

Saturday, April 09, 2005 4:11 PM by TrackBack

^_^,Pretty Good!

# re: SQL 'SELECT CASE' problem

Tuesday, June 10, 2008 6:37 AM by George

What about using the CASE statement with the "TOP" option? I want to use TOP 1 if brand is N and if the brand is not N (V,A,S,C,etc), the TOP 1 option not to appear??

Also I want to condition the use of ORDER BY in the same select statement, by the appearance of the TOP option or of the brand selection (ofcourse with CASE also).

Thanks!!!

# re: SQL 'SELECT CASE' problem

Saturday, July 12, 2008 1:47 PM by Chochy

I did a google search and found your page - one comment - very difficult to read, I had to go into print preview to actually read it.  The dark blue on some of the key commands got lost in the background.

Leave a Comment

(required) 
(required) 
(optional)
(required)