avoid repeating same logic in 'select' and 'where' clauses?
680314Jan 16 2009 — edited Jan 18 2009I'll preface by saying I'm self-taught and have only been fiddling with SQL for a couple of months, so forgive me if this is a dumb question. I have a query written to pull out customers who are configured to have their products stored at the wrong warehouse, according to the first 3 digits of the zip code. Here is an extremely simplified version of a query I'm trying to run:
select custno, custbuy_zip_cd, custbuy_prim_ship_loc_cd as Warehouse,
case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
end as StdWhse
from customers
where case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
end <> custbuy_prim_ship_loc_cd
or (case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
end is not null and custbuy_prim_ship_loc_cd is null)
Now, the query works, but it seems overly convoluted and feels like there must be a way to make it simpler and faster. I'm using the same 'case when' 3 times. Originally, I had thought I could use the aliases from the 'select' clause in the 'where' clause, which would simplify things:
select custno, custbuy_prim_ship_loc_cd as Warehouse,
case when substr(custbuy_zip_cd,1,3) in ('839','848') then '20'
when substr(custbuy_zip_cd,1,3) in ('590','591') then '33'
end as StdWhse
from customers
where StdWhse <> custbuy_prim_ship_loc_cd
or (StdWhse is not null and custbuy_prim_ship_loc_cd is null)
I then found out that that caused 'invalid identifier' errors. My first attempt at a solution was to use a subquery in the 'from' clause, but that ran the 'case when' on every single customer instead of the small subset, so it wound up taking much longer even though it looked neater. Any tips on how to clean up that first query to make it run faster?
this is Oracle 11i, I believe. As a side note, I don't have write access to the database.