pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Ben Morrow <ben@morrow.me.uk>
Cc: jorgemal1960@gmail.com
Cc: pgsql-sql@postgresql.org
Subject: Re: UPDATE query with variable number of OR conditions in WHERE
Date: Thu, 14 Mar 2013 23:15:17 -0400
Message-ID: <19955.1363317317@sss.pgh.pa.us> (raw)
In-Reply-To: <20130314235807.GA81164@anubis.morrow.me.uk>
References: <20130314235807.GA81164@anubis.morrow.me.uk>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-sql>

Ben Morrow <ben@morrow.me.uk> writes:
> Quoth jorgemal1960@gmail.com (JORGE MALDONADO):
>> I am building an UPDATE query at run-time and one of the fields I want to
>> include in the WHERE condition may repeat several times, I do not know how
>> many.
>> 
>> UPDATE table1
>> SET field1 = "some value"
>> WHERE (field2 = value_1 OR field2 = value_2 OR .....OR field2 = value_n)
>> 
>> I build such a query using a programming language and, after that, I
>> execute it. Is this a good approach to build such a query?

> You can use IN for this:

>     UPDATE table1
>     SET field1 = "some value"
>     WHERE field2 IN (value_1, value_2, ...);

IN is definitely better style than a long chain of ORs.  Another
possibility is to use = ANY(ARRAY):

    UPDATE table1
    SET field1 = "some value"
    WHERE field2 = ANY (ARRAY[value_1, value_2, ...]);

This is not better than IN as-is (in particular, IN is SQL-standard and
this is not), but it opens the door to treating the array of values as a
single parameter:

    UPDATE table1
    SET field1 = "some value"
    WHERE field2 = ANY ($1::int[]);

(or text[], etc).  Now you can build the array client-side and not need
a new statement for each different number of comparison values.  If
you're not into prepared statements, this may not excite you, but some
people find it to be a big deal.

			regards, tom lane


-- 
Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-sql



view thread (3+ messages)

Message-ID: <19955.1363317317@sss.pgh.pa.us>
Permalink:  ../19955.1363317317@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/19955.1363317317@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: tgl@sss.pgh.pa.us, ben@morrow.me.uk, jorgemal1960@gmail.com
  Subject: Re: UPDATE query with variable number of OR conditions in WHERE
  In-Reply-To: <19955.1363317317@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox