So instead of
select something from x join y on x.foo = y.foo and blah = 'cheese' where some_complicated_join_conditions ...
union
select something from x join y on x.foo = y.foo and blah <> 'cheese' where -ome_other_complicated_join_conditions
...you can have with nerk as (
select something from x join y on x.foo = y.foo
where
hopefully you can find some common part of the complicated where clauses
)
select something from nerk where blah = 'cheese' and something
union
select something from nerk where blah <> 'cheese' and something_else
...obviously a trivial example but you get the idea. When I tested this on postgres (some time ago) this was very significantly faster for my use case.It also helps in use cases where you want to allow user-defined filtering and ordering logic controlled by a gui. You can put your basic query as the CTE and then have all the user-controlled bits and pieces in the final select and they don't get mixed up together.