WITH can increase clarity and improve queries by forcing a re-examining of the query, but a query rewritten using 'WITH' can still error out because it is too long or complex.
I had a query that was very complex. In my experience long case statements often create queries that fail. I replaced a failing long case by placing very simple case statements in a pre-query using with like the following:
Code:
with source as
select
field 1,
field 2,
case when field1 < somevalue then 0 else 1 end as flg1,
case when field2 > somevalue then 0 else 1 end as flg2
from tablename
where cond
This meant that my query logic was much simplified and it ran:
Code:
select
field1,
field2,
case
when flg1 = 0 and flg2 = 0 then 1
when flg1 = 0 and flg2 = 1 then 2
when flg1 = 1 and flg2 = 0 then 3
when flg1 = 1 and flg2 = 1 then 4
end as mycasename
from source
The logic is much more exposed and it ran, but with does not guarantee the query will not be too complex.