Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

UPDATE query with variable number of OR conditions in WHERE

5 views
Skip to first unread message

JORGE MALDONADO

unread,
Mar 14, 2013, 6:25:48 PM3/14/13
to
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?

Respectfully,
Jorge Maldonado

Ben Morrow

unread,
Mar 14, 2013, 7:58:11 PM3/14/13
to
Quoth jorgem...@gmail.com (JORGE MALDONADO):
You can use IN for this:

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

Ben



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

Tom Lane

unread,
Mar 14, 2013, 11:15:17 PM3/14/13
to
Ben Morrow <b...@morrow.me.uk> writes:
> Quoth jorgem...@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
0 new messages