I understand how to use the WITH clause for recursive queries (!!), but I’m having problems understanding its general use / power.
For example the following query updates one record whose id is determined by using a subquery returning the id of the first record by timestamp:
update global.prospect psp
set status=status||'*'
where psp.psp_id=(
select p2.psp_id
from global.prospect p2
where p2.status='new' or p2.status='reset'
order by p2.request_ts
limit 1 )
returning psp.*;
Would this be a good candidate for using a WITH wrapper instead of the relatively ugly sub-query? If so, why?
If there can be concurrent write access to involved tables, there are race conditions in the following queries. Consider:
Your example can use a CTE (common table expression), but it will give you nothing a subquery couldn’t do:
The returned row will be the updated version.
If you want to insert the returned row into another table, that’s where a
WITHclause becomes essential:Data-modifying queries using CTEs were added with PostgreSQL 9.1.
The manual about
WITHqueries (CTEs).