what's the best way to emulate "insert ignore" and "on duplicate key update" with postgresql ?
views:
3614answers:
2Looks like PostgreSQL supports a schema object called a rule.
http://www.postgresql.org/docs/current/static/rules-update.html
You could create a rule ON INSERT
for a given table, making it do NOTHING
if a row exists with the given primary key value, or else making it do an UPDATE
instead of the INSERT
if a row exists with the given primary key value.
I haven't tried this myself, so I can't speak from experience or offer an example.
Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.
You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.
There's an example of this in the documentation: http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html, example 38-1 right at the bottom.
That's usually the easiest way. You can do some margic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.
This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)