Re: INSERT OR UPDATE?

From: gordonb(dot)d7t5w(at)burditt(dot)org (Gordon Burditt)
To: pgsql-general(at)postgresql(dot)org
Subject: Re: INSERT OR UPDATE?
Date: 2005-10-09 06:52:36
Message-ID: 11khfhk75j9lr2e@corp.supernews.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

>I am writing an app in PHP that uses a PostGres database.
>One thing i have noticed is that what should/could be a single line of
>SQL code takes about 6 lines of PHP. This seem wasteful and redundant
>to me.
>
>Here is a sample of what I'm talking about ($db is a PDO already
>defined and created).
>
>$query[1] = "UPDATE my.table, SET somefield = '$someval' WHERE
>somecondition";
>$query[2] = "INSERT INTO my.table (somefield) VALUES ('$someval')";
>if(!$db->query($query[1])){
> $db->query($query[2]);
>}
>
>What I'm curious to know is if there is some way to simplify this,
>either buy some PHP builtin or extension, or possibly something in SQL
>I am missing. It seems to me that "UPDATE OR INSERT", should be valid,
>but I can't seem to find anything relevant at all about it.

MySQL permits (but it's not standard, and available in MySQL 4.1.0
and later):

INSERT INTO my.table (somefield) VALUES ('$someval') ON DUPLICATE
KEY UPDATE somefield = '$someval';

This is very useful for times when you want to count something (e.g.
SPAM), and if a record doesn't exist, make one with a count of 1.

I don't know whether something similar is available in PostGres.

Gordon L. Burditt

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Gregory Youngblood 2005-10-09 09:08:55 PostgreSQL missing in SuSE 10?
Previous Message andrew 2005-10-09 06:48:01 Re: INSERT OR UPDATE?