Skip to content
Advertisement

Postgres Update Multiple Rows with Multiple Returns Preserving Order

So I have a Table A that is missing a relation with Table B such that I want to add the relationship information preserving the order based on insert. Table B can have multiple pieces where UUIDs are unique to a grouping and the order is preserved by and index.

So I can have in Table B:

What I want to do is add those columns to Table A and copy that information over to Table A in that order where we can assume that Table A has entries that match the same count as Table B.

Example Data:

Let’s say table test_a is a trip for a traveler, test_b is a list of the cities they went to. Example Alice has traveled twice to Chicago and Charlotte. Along the way they keep a log of their trip in test_c. What I want is to add the uuid and idx from test_b to test_c assuming the order in test_b matches the order found in test_c.

Advertisement

Answer

step-by-step demo:db<>fiddle

Joining the records from table_b on table_c needs a common join condition.

Assuming, the ids are correctly increasing with the entrys (so a newer records has a higher id), they can be used as order criterion. If not, you’ll need one, because there’s nothing like an insert order. Inserting a record does not ensure any query order.

Well, to create the common join condition, you can use the row_number() window function, which creates a row count within an ordered group (= partition). In your case, the partition is the traveler, the order is the id (here table_b):

which yields (notice the last column, which was created)

The same can be done with table_c.

Now, you created a normalizing row count on every traveler‘s records. Because the record numbers equal (which you presumed in your question), this is your join condition:

  1. table_c with row counts
  2. table_b with row counts
  3. Join on traveler and row count

Well, if you want to add the table_b‘s columns uuid and idx to table_c, you need new columns:

And then you have to fill them using an UPDATE statement, which uses the query above:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement