Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use filter my WHERE clause on a CASE statement column in SQL Server? [duplicate]

In my select statement there is a CASE WHEN THEN ELSE END AS statement that I am not able to filter on in my WHERE clause. I do not see why this would be an issue, could someone shed some light?

SELECT        
CASE 
    WHEN m.Country IN ('CANADA', 'UNITED STATES', 'USA', 'MEXICO') THEN 'NA' 
WHEN m.Country IN ('BRAZIL') THEN 'JD2' 
    WHEN m.Country IN ('NZ', 'NEW ZEALAND', 'AUSTRALIA', 'AUSTRALASIA') THEN 'ANZ' 
ELSE 'Unknown' 
    END AS DerivedRegion,
    m.ID,
    m.[Account Name], 
m.[Display Name], 
m.[Last Name], 
m.[First Name]
FROM dbo.Users AS m
WHERE DerivedRegion = 'Unknown'

There WHERE clause gives me the error: Invalid column name 'DerivedRegion', why?

like image 987
LaRae White Avatar asked Jun 05 '14 14:06

LaRae White


People also ask

Can you filter on a case statement SQL?

CASE statements allow you to categorize data that you're interested in -- and exclude data you're not interested in. In order to do this, you can use a CASE statement as a filter in the WHERE statement to remove output you don't want to see.

Can we use WHERE clause in case statement?

Another way to use the Case Statement is within the WHERE clause. There, it may be utilized to alter the data fetched by a query based on a condition. Within that context, the Case Statement is ideally suited to both static queries, as well as dynamic ones, such as those that you would find inside a stored procedure.

Can case be used in WHERE clause in SQL?

You can use a CASE Statement anywhere a valid expression is used within the SELECT statement such as the WHERE clause's filter criteria.

Does WHERE clause used to filter records?

The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.


1 Answers

WHERE is processed before SELECT. It doesn't know what DerviedRegion is at that point. I'd recommend using a NOT IN in this case to exclude the list of countries. However, if you really want to use your CASE you could do something like this

SELECT *
FROM
(
    SELECT        
        CASE 
            WHEN m.Country IN ('CANADA', 'UNITED STATES', 'USA', 'MEXICO') THEN 'NA' 
            WHEN m.Country IN ('BRAZIL') THEN 'JD2' 
            WHEN m.Country IN ('NZ', 'NEW ZEALAND', 'AUSTRALIA', 'AUSTRALASIA') THEN 'ANZ' 
            ELSE 'Unknown' 
        END AS DerivedRegion,
        m.ID,
        m.[Account Name], 
        m.[Display Name], 
        m.[Last Name], 
        m.[First Name]
    FROM dbo.Users AS m
) AS x
WHERE x.DerivedRegion = 'Unknown'

Check out MSDN and scroll down to Logical Processing Order of the SELECT statement to see the order in which a query is processed.

like image 154
cadrell0 Avatar answered Oct 01 '22 14:10

cadrell0