Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many values in an "in" clause is too many in a SQL query?

Tags:

mysql

I have a SQL query that uses the values of an array in its WHERE clause:

 $ids = array 
         ( 
           [0] => 1 
           [1] => 2 
           [2] => 5 
         ) 

 $ids = join(',',$ids);   
 $sql = "SELECT * FROM cats WHERE id IN ($ids)"; 


My question is how many ids are too many?
Will it effect the speed?

Thanks all

like image 800
eMRe Avatar asked Dec 27 '11 23:12

eMRe


People also ask

What SQL clause limits the number of results?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.

What is the limit of in clause in Oracle?

In Oracle we can only put up to 1000 values into an IN clause.

How big can an SQL query be?

A Standard SQL query can have up to 10,000 parameters. The request size can be up to 10 MB, including additional properties like query parameters.

Can WHERE clause have multiple values?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.


2 Answers

Oracle has a limit of 1000, which I've hit before. MySQL doesn't seem to mind. The best solution is not to use an IN clause for that large a dataset though. Where do the ids come from? If from the same DB, then see if you can use a subquery instead that searches based on one parameter e.g. userid to find the linked ids. This will be far more efficient as MySQL can do a join internally using indexes.

like image 132
Matt Gibson Avatar answered Oct 31 '22 00:10

Matt Gibson


The more data you select, the longer this takes, but your primary concern should not be the number of ids you SELECT. Instead, you should ensure that your id has an INDEX on it or that it is the PRIMARY KEY. This will make lookups fast no matter how many ids you're grabbing.

like image 37
Interrobang Avatar answered Oct 30 '22 23:10

Interrobang