Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning complex query on update sql

I want to return query with multiple joins and with clause after updating something.

For example my query is:

WITH orders AS (
  SELECT product_id, SUM(amount) AS orders
  FROM orders_summary
  GROUP BY product_id
)
SELECT p.id, p.name,
p.date_of_creation,
o.orders, s.id AS store_id,
s.name AS store_name
FROM products AS p
LEFT JOIN orders AS o
ON p.id = o.product_id
LEFT JOIN stores AS s
ON s.id = p.store_id
WHERE p.id = '1'
id name date orders store_id store_name
1 pen 11/16/2022 10 1 jj
2 pencil 11/10/2022 30 2 ff

I want to return the exact query but with updated result in my update:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

UPDATE products
SET name = 'ABC'
WHERE id = '1'
RETURNING up_qeury

Desired result on update:

id name date orders store_id store_name
1 ABC 11/16/2022 10 1 jj

>Solution :

You can try UPDATE products ... RETURNING *. That may get you the content of the row you just updated.

As for UPDATE .... RETURNING someQuery, You Can’t Do That™. You want to do both the update and a SELECT operation in one go. But that’s not possible.

If you must be sure your SELECT works on the precisely the same data as you just UPDATEd, you can wrap your two queries in a BEGIN; / COMMIT; transaction. That prevents concurrent users from making changes between your UPDATE and SELECT.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading