on duplicate key

From: "A B" <gentosaker(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: on duplicate key
Date: 2008-09-25 16:25:33
Message-ID: dbbf25900809250925k7e451a61l89c69ca9cfb218b@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hello.
I was just asked by a mysql-user how do you do
insert ..... on duplicate key update ....
(or however they have it in mysql) in postgresql, if you are going to
run commands from the command line?

My solution up till now has been a function with the

BEGIN
insert ....
EXCEPTION WHEN OTHERS THEN
update ...
END;

I think this is not possible to run this kind of commands on the
command line. Correct?

As I see it, there are three ways
1) a function
2) try to rewrite it as two separate queries insert ... ; update
... ; where the insert will fail sometimes
3) try to search and see if there were any result back, but that would
require the IF THEN construct which is also not available outside of
functions, right?

Is it correct to assume that a function that is searching for the key
and then choosing to insert or update depending on what it found, is
about as fast as doing an insert within a begin- exception-end
statement or are there some inherent speed differences?

Comparing method 1 and 2, are there any noticable speed differences
when the exception is triggered?

What should I answer the mysql-user?

By the way, is there any work done on getting this functionality? I
must admit that it would be handy some times ;-)
Shouldn't this kind of question be added to the FAQ?

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Reg Me Please 2008-09-25 16:31:05 Counting rows in a PL/PgSQL CURSOR without fetching?
Previous Message Justin Yao 2008-09-25 16:22:25 Re: how can I find out the numeric directory name of each database in PostgreSQL 8.3