SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Not understanding CASE function in WHERE clause
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Rock_query
Yak Posting Veteran

52 Posts

Posted - 05/22/2013 :  16:56:35  Show Profile  Reply with Quote
I copied a CASE function as a part of a WHERE function, then modified some column names to test this on the AdventureWorks2012 database.

Here is the code:

select top 5 ProductID, ActualCost
from Production.TransactionHistory
where
case
when ActualCost < 30.00 then 'Cheap'
when ActualCost < 12.00 then 'Really Cheap'
when ActualCost > 30.00 and ActualCost < 100.00 then 'Average'
else 'Expensive'
end = 'Average'

The results are two columns with these values:

Product ID: 894, 907, 916, 941, 945
ActualCost: 89.88, 78.81, 38.95, 59.93 and 67.70

I don't understand how this is working.

1. Is SQL selecting the first 5 ProductIDs, then looking at their ActualCost? Or is SQL grouping the ActualCosts, then extracting the top 5 ProductIDs?

2. Also, END = 'Average' implies that there should be a column displayed called Average right?

chadmat
The Chadinator

USA
1974 Posts

Posted - 05/22/2013 :  17:08:26  Show Profile  Visit chadmat's Homepage  Reply with Quote
No, columns come from the Select list.

-Chad
Go to Top of Page

Lamprey
Flowing Fount of Yak Knowledge

4612 Posts

Posted - 05/22/2013 :  17:21:22  Show Profile  Reply with Quote
Using a CASE expression in the WHERE clasue like that works, but it is a bit superfluous and makes the intent less clear (IMHO).

1. SQL is getting 5 random rows that statisfy the predicate.
2. No. That that is just a predicate.

Again, no need for the case expression:
select top 5 
	ProductID, 
	ActualCost
from 
	Production.TransactionHistory
where 
	ActualCost > 30.00 
	and ActualCost < 100.00
Go to Top of Page

Rock_query
Yak Posting Veteran

52 Posts

Posted - 05/22/2013 :  20:01:39  Show Profile  Reply with Quote
quote:
Originally posted by Lamprey

Using a CASE expression in the WHERE clasue like that works, but it is a bit superfluous and makes the intent less clear (IMHO).

1. SQL is getting 5 random rows that statisfy the predicate.
2. No. That that is just a predicate.

Again, no need for the case expression:
select top 5 
	ProductID, 
	ActualCost
from 
	Production.TransactionHistory
where 
	ActualCost > 30.00 
	and ActualCost < 100.00




Thank you Lamprey.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000