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 id
s to query for. I know usually DB connections are expensive, but I've seen the IN
clause isn't so fast either [sometimes].
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 ...
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.
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.
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. ...
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With