Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantly update created record with a WITH clause

I'm trying to update a record, created with WITH clause in the same query, like so:

WITH
  document AS (
    INSERT INTO documents (name) VALUES ($1)
    RETURNING *
  )
UPDATE documents
SET documents.description = $2
FROM document
WHERE documents.id = document.id;

I've also tried

WITH
  new_document AS (
    INSERT INTO documents (name) VALUES ($1)
    RETURNING *
  ),
  updated_document AS (
    UPDATE documents
    SET documents.description = $2
    WHERE documents.id = (SELECT id FROM new_document)
    RETURNING *
  )
SELECT * FROM updated_document;

But it doesn't seem to work. I know this example is silly since I can simply create a new document with both name and description at the same time, but I need it to do it this way in my app; the example is simplified on purpose.

Edit

I've created a Gist with a real world example. I know I can embed the logic of updating document_id into the function body. I guess. But imagine that urls can correspond not only to documents, but to many other entities, like, documents, stories, users, articles, tags, etc., etc., embedding references to all these entities into the function body is tedious, since (due to function overloading) I would have to create functions like get_url_for_document(id uuid), get_url_for_story(id uuid), get_url_for_user(id uuid), etc., etc.

like image 366
Anton Egorov Avatar asked Feb 22 '26 16:02

Anton Egorov


1 Answers

Do it in two separate statements or inside a function. You cannot do it like you tried due to the way how WITH is implemented.

From documentation:

The sub-statements in WITH are executed concurrently with each other and with the main query. Therefore, when using data-modifying statements in WITH, the order in which the specified updates actually happen is unpredictable. All the statements are executed with the same snapshot (see Chapter 13), so they cannot "see" one another's effects on the target tables.

like image 64
Nick Avatar answered Feb 24 '26 06:02

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!