From: Alban Hertroys <haramrae@gmail.com>
To: Hemil Ruparel <hemilruparel2002@gmail.com>
Cc: pgsql-general@postgresql.org
Subject: Re: How to update a table with the result of deleting rows in another table
Date: Tue, 6 Oct 2020 14:45:52 +0200
Message-ID: <DAF94EE1-F4B3-44ED-95B9-ED007B64F363@gmail.com> (raw)
In-Reply-To: <CANW1aT9p5_5Pv20-YGKfyo3ybQd2CVuBfDV6YHaeF34ZW2qovQ@mail.gmail.com>
References: <CANW1aT9p5_5Pv20-YGKfyo3ybQd2CVuBfDV6YHaeF34ZW2qovQ@mail.gmail.com>
> On 6 Oct 2020, at 7:37, Hemil Ruparel <hemilruparel2002@gmail.com> wrote:
>
> I am trying to delete orders for a given customer on a given date and add the cost of those orders to credit for the customer.
>
> So far, I came up with this:
> ```
> with data as (
> delete from orders
> where customer_id = <customer id>
> and date = '2020-10-05' returning price
> ), total as (
> select sum(price) from data
> )
> update paymentdetail
> set temp_credit = temp_credit + (select * from total)
> where customer_id = <customer id>
> ```
>
> which works. but is there a better way to update one table using the result of deleting rows from another table given that I only want the aggregate of the result?
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 also do this using subqueries instead of CTE’s, that may perform better as CTE’s act as optimisation fences.
Alban Hertroys
--
If you can't see the forest for the trees,
cut the trees and you'll find there is no forest.
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: haramrae@gmail.com, hemilruparel2002@gmail.com
Subject: Re: How to update a table with the result of deleting rows in another table
In-Reply-To: <DAF94EE1-F4B3-44ED-95B9-ED007B64F363@gmail.com>
References: <CANW1aT9p5_5Pv20-YGKfyo3ybQd2CVuBfDV6YHaeF34ZW2qovQ@mail.gmail.com> <DAF94EE1-F4B3-44ED-95B9-ED007B64F363@gmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox