Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are queries in the WITH statement executed in a single transaction in PostgreSQL?

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
    ....
like image 403
Evgenii Karavskii Avatar asked Nov 28 '25 19:11

Evgenii Karavskii


1 Answers

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)
like image 178
Nick Barnes Avatar answered Dec 01 '25 13:12

Nick Barnes