Skip to content
Advertisement

Ordering with PostgreSQL trigger when updating and inserting

I’m looking to sort the rows based on a variable. I’m pulling my hair out trying to wrap my head around this kind of trigger. I’ve only ever written triggers that gets some values from other tables.

Example: I have rows with the columns lets say: name and order.

Now I insert without order but the ON INSERT trigger should make it 3 automatically

But now we update the third buildorder to be in the 1st position

All the other rows should now change to reflect this change in ordering. How would I go about writing a trigger for this?

Example result:

Advertisement

Answer

This is a terrible idea.

Instead, define order_buildorder as a real column.

That way, you can always insert a new row to be ordered between two already existing rows without updating existing rows (just take the arithmetic mean of the values between which you want to insert).

If you need an integral order, generate it on the fly using a window function when you select the data.

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