PostgreSQL: Can i use tuple in where clause?

All we need is an easy explanation of the problem, so here it is.

Actually might be a simple question:

Given 2 tables:

table1: A,B,C
(A1,B1,28471),
(A1,B2,01244),
(A2,B1,1283a),
(A2,B2,82r7e);

table2: A,B,D,E,F,G
(A1,B1,18,1,6,8),
(A2,B2,18,2,3,0),
(A3,B1,18,7,1,4),
(A4,B2,18,1,9,6);

Will the following statement result in a the following result given the example tables:

SELECT E,F,G FROM table2 WHERE (A,B) IN (SELECT A,B FROM table1)

expected result:

 E F G
(1,6,8), -- (A1,B1)
(2,3,0); -- (A2,B2)

Can someone confirm this is a valid method to select based on tuples?

asking as the most likely next step is to UPDATE the E field by adding +5 for matching results

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Consider EXISTS instead:

SELECT E,F,G
FROM   table2 t2
WHERE  EXISTS (
   SELECT FROM table1 t1
   WHERE  (t1.A,t1.B) = (t2.A,t2.B)
   );

db<>fiddle here

Equivalent and typically cheaper.
And the negation NOT EXISTS is not as treacherous as the discouraged (not completely equivalent) NOT IN. See:

Aside, I would call (A,B) a "composite type" or "row type" rather than a "tuple".

Method 2

Thanks to Peter Vandivier (couldnt flag his comment as the answer)

Yes it is possible:

What have you tried๐Ÿ˜‰ โ€“ Peter Vandivier 12 mins ago

Note: Use and implement method 1 because this method fully tested our system.
Thank you ๐Ÿ™‚

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply