Revisiting UPDATE FROM ... ORDER BY not respected

From: Carlo Stonebanks <stonec(dot)register(at)sympatico(dot)ca>
To: <pgsql-general(at)postgresql(dot)org>
Subject: Revisiting UPDATE FROM ... ORDER BY not respected
Date: 2011-04-12 23:08:01
Message-ID: BLU0-SMTP618AED1D8371E34867FFDE96AB0@phx.gbl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

A few years ago I asked about creating a single UPDATE statement to assign
id's from a sequence, with the sequences applied in a particular order. In
other words, order the table, then apply nextval-generated id's to the id
field in question.

Here is the original post:
http://archives.postgresql.org/pgsql-general/2009-04/msg01123.php

The explanation and solution provided made total sense. To my surprise,
every now and then users still report sequences being applied out of order.
Below is the code in question. I admit that I am completely baffled. Does
anyone have any clues?

UPDATE my_schema.my_table

SET id = the_next.id

FROM (

SELECT

order_by_value,

nextval('my_schema.id_seq') AS id

FROM (

SELECT order_by_value

FROM my_schema.my_table

WHERE id IS NULL

ORDER BY order_by_value

) AS ordered

) AS the_next

WHERE

my_table.order_by_value = the_next.order_by_value

AND my_table.id IS NULL;

I should mention that this is an example only - the actual code is dynamic
SQL within a PL/PGSQL stored proc. The articles my_schema, my_table and
order_by_value will be replaced by variables and the code above would be a
string that is then fed to an EXECUTE statement. Would that make ANY sort of
a difference?

Thanks!

Carlo

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Shianmiin 2011-04-12 23:09:21 Re: PostgreSQL backend process high memory usage issue
Previous Message Joel Stevenson 2011-04-12 22:47:28 Re: Column storage (EXTERNAL/EXTENDED) settings for bytea/text column