Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using tuples in SQL "IN" clause

I have a table containing the fields group_id and group_type and I want to query the table for all the records having any tuple (group id, group type) from a list of tuples. For example, I want to be able to do something like:

SELECT * FROM mytable WHERE (group_id, group_type) IN (("1234-567", 2), ("4321-765", 3), ("1111-222", 5)) 

A very similar question is already asked at: using tuples in sql in clause , but the solution proposed there presumes the tuple list is to be fetched from another table. This doesn't work in my case is the tuple values are hard coded.

One solution is to use string concatenation:

SELECT * FROM mytable WHERE group_id + STR(group_type, 1) IN ("1234-5672", "4321-7653", "1111-2225") 

But the problem is that the table is quite big and doing a string concatenation and conversion for each record would be very expensive.

Any suggestion?

like image 652
Rafid Avatar asked Nov 04 '11 09:11

Rafid


People also ask

How do I select a tuple in SQL?

SELECT * FROM mytable WHERE (group_id, group_type) IN ( VALUES ('1234-567', 2), ('4321-765', 3), ('1111-222', 5) ); Show activity on this post. Show activity on this post. Show activity on this post.

Which clause is used to sort the tuples in a table?

Answer: ORDER BY Clause is used to display the tuples in ascending order of an attribute.

What is tuple in SQL with example?

In a relational database, a tuple contains all the data for an individual record. For example, in a database containing client contact information, the fields may be categories such as name, phone number, email address and mailing address, while a tuple for that database could be: Bill Gates. 206-555-1234.

How do you insert a tuple in SQL?

To insert a row into a table, you need to specify three things: First, the table, which you want to insert a new row, in the INSERT INTO clause. Second, a comma-separated list of columns in the table surrounded by parentheses. Third, a comma-separated list of values surrounded by parentheses in the VALUES clause.


1 Answers

Given a very minor tweak (replace double quotes with single and add the VALUES keyword), your proposed syntax is valid Standard SQL-92 syntax i.e.

SELECT *   FROM mytable  WHERE (group_id, group_type) IN (                                   VALUES ('1234-567', 2),                                           ('4321-765', 3),                                           ('1111-222', 5)                                  ); 

Sadly, MSFT have not added it to SQL Server and consider it an 'unplanned' feature.

FWIW PostgreSQL and Sqlite are examples of SQL products that support this syntax.

like image 162
onedaywhen Avatar answered Oct 22 '22 16:10

onedaywhen