Re: INSERT OR UPDATE? - Mailing list pgsql-general

From gordonb.d7t5w@burditt.org (Gordon Burditt)
Subject Re: INSERT OR UPDATE?
Date
Msg-id 11khfhk75j9lr2e@corp.supernews.com
Whole thread Raw
In response to INSERT OR UPDATE?  (smorrey@gmail.com)
Responses Re: INSERT OR UPDATE?  ("shakahshakah@gmail.com" <shakahshakah@gmail.com>)
List 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

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: Comand line or postgresql.conf?
Next
From: "andrew"
Date:
Subject: Re: INSERT OR UPDATE?