I do many queries in WITH statement. They should be in one transaction. Should I cover my big query in transaction explicitly or it is not necessary?
This is a rough example of my query:
WITH
remains_actual AS (
SELECT
...
)
affected_remains AS (
INSERT INTO
...
ON CONFLICT (...) DO UPDATE SET
...
RETURNING
...
)
affected_products AS (
SELECT DISTINCT
...
)
INSERT INTO
....
From the docs:
PostgreSQL actually treats every SQL statement as being executed within a transaction. If you do not issue a BEGIN command, then each individual statement has an implicit BEGIN and (if successful) COMMIT wrapped around it.
A WITH statement still counts as a single statement, so it will be run in an implicit transaction block.
You can test this for yourself with some CTEs which return the current transaction ID:
with
tx1 as (select txid_current()),
tx2 as (select txid_current())
select * from tx1, tx2;
txid_current | txid_current
--------------+--------------
12814 | 12814
(1 row)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With