Re: How to update a table with the result of deleting rows in another table

From: Michael Lewis <mlewis(at)entrata(dot)com>
To: Alban Hertroys <haramrae(at)gmail(dot)com>
Cc: Hemil Ruparel <hemilruparel2002(at)gmail(dot)com>, pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: How to update a table with the result of deleting rows in another table
Date: 2020-10-06 20:02:14
Message-ID: CAHOFxGp-5Op0Bdoe=mTcyWG8NiJ6yN_NsgrWkSWDhNxdsPNHAw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

>
> Adding the customer id to your returning clause and using update..from
> could help:
>
> with data as (
> delete from orders
> where customer_id = <customer id>
> returning customer_id, price
> ), total as (
> select customer_id, sum(price) as total_price
> from data
> group by customer_id
> )
> update paymentdetail
> set temp_credit = temp_credit + total.total_price
> from total
> where customer_id = total.customer_id
>

You could skip the "total" cte and just update the same rows repeatedly.
I'm not sure if the same row being repeatedly updated in the same statement
creates additional row versions or just updates the existing one.

> ...CTE’s act as optimisation fences.
>

It might be worth noting PG12 changes that behavior in simple cases where
the CTE is not recursive, not referenced more than once, and is side-effect
free.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Adalberto Caccia 2020-10-06 20:04:13 Re: Handling time series data with PostgreSQL
Previous Message James B. Byrne 2020-10-06 15:35:54 [SOLVED] Re: UUID generation problem