Given a table foo
with a composite primary key (a,b)
, is there a legal syntax for writing a query such as:
SELECT ... FROM foo WHERE a,b IN (SELECT ...many tuples of a/b values...);
UPDATE foo SET ... WHERE a,b IN (SELECT ...many tuples of a/b values...);
If this is not possible, and you could not modify the schema, how could you perform the equivalent of the above?
I'm also going to put the terms "compound primary key", "subselect", "sub-select", and "sub-query" here for search hits on these aliases.
Edit: I'm interested in answers for standard SQL as well as those that would work with PostgreSQL and SQLite 3.
Firebird uses this concatenation formula:
With concatenation, this works with PostgreSQL:
The IN syntax you suggested is not valid SQL. A solution using EXISTS should work across all reasonably compliant SQL RDBMSes:
Be aware that this is often not especially performant.
Replace the
select 1 from bar
with yourselect ... many tuples of a/b values ...
.Or create a temporary table of your
select ... many tuples of a/b values ...
and use it in place ofbar
..You've done one very little mistake. You have to put a,b in parentheses.
That works!
If you need a solution that doesn't require the tuples of values already existing in a table, you can concatenate the relevant table values and items in your list and then use the 'IN' command.
In postgres this would look like this:
SELECT * FROM foo WHERE a || '_' || b in ('Hi_there', 'Me_here', 'Test_test');
While in SQL I'd imagine it might look something like this:
SELECT * FROM foo WHERE CONCAT(a, "_", b) in ('Hi_there', 'Me_here', 'Test_test');