Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IN clause vs. multiple SELECTs

Tags:

php

mysql

I was wondering which of these would be faster (performance-wise) to query (on MySQL 5.x CentOS 5.x if this matters):

SELECT * FROM table_name WHERE id=1;
SELECT * FROM table_name WHERE id=2;
.
.
.
SELECT * FROM table_name WHERE id=50;

or...

SELECT * FROM table_name WHERE id IN (1,2,...,50);

I have around 50 ids to query for. I know usually DB connections are expensive, but I've seen the IN clause isn't so fast either [sometimes].

like image 672
Eduard Luca Avatar asked May 13 '12 13:05

Eduard Luca


People also ask

How do you use multiple values in a where clause?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions. IN Syntax . SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...); or: SELECT column_name(s) FRO ...

How do you select multiple values in SQL?

SQL – SELECT IN. IN operator is a membership operator which returns values that match the values in a list or subquery. Using this operator we can specify multiple values in a WHERE Clause. This operator compares a value with a set of values, and it returns a true if the value belongs to that given set, else it returns false.

What is the use of using clause in SQL?

SQL | USING Clause. If several columns have the same names but the datatypes do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an EQUIJOIN. USING Clause is used to match only one column when more than one column matches. NATURAL JOIN and USING Clause are mutually exclusive.

What is the difference between MySQL using clause and natural join clause?

SQL | USING Clause 1 USING Clause is used to match only one column when more than one column matches. 2 NATURAL JOIN and USING Clause are mutually exclusive. 3 It should not have a qualifier (table name or Alias) in the referenced columns. 4 NATURAL JOIN uses all the columns with matching names and datatypes to join the tables. ...


2 Answers

I'm pretty sure the second option gives you the best performance; one query, one result. You have to start looking for > 100 items before it may become an issue.

See also the accepted answer from here: MySQL "IN" operator performance on (large?) number of values

like image 97
Ja͢ck Avatar answered Sep 25 '22 23:09

Ja͢ck


IMHO you should try it and measure response time: IN should give you better performances...
Anyway if your ids are sequential you could try

SELECT * FROM table_name WHERE id BETWEEN 1 AND 50
like image 39
Marco Avatar answered Sep 26 '22 23:09

Marco