Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select multiple rows by primary key in MySQL?

Tags:

select

mysql

SELECT * FROM `TABLE` WHERE
(`PRIMARY_KEY`= `VALUE1`) OR
(`PRIMARY_KEY`= `VALUE2`) OR
(`PRIMARY_KEY`= `VALUE3`) OR
(`PRIMARY_KEY`= `VALUE4`) OR
(`PRIMARY_KEY`= `VALUE5`) OR ...

This works. But is there a faster way?

like image 880
Jader Dias Avatar asked Dec 03 '25 11:12

Jader Dias


2 Answers

Using the value in (list) construct is not faster, but the SQL-code will be much easier to read/understand once someone needs to maintain the code.

SELECT * 
FROM `TABLE` 
WHERE `PRIMARY_KEY` in( `VALUE1`
                       , `VALUE2`
                       , `VALUE3`
                       , `VALUE4`
                       , `VALUE5`
                      ) 

Updated: Rewritten to reflect the feedback from the comments.

like image 111
lexu Avatar answered Dec 05 '25 00:12

lexu


SELECT * FROM table WHERE primary_key IN (value1, value2, ...)
like image 33
Ignacio Vazquez-Abrams Avatar answered Dec 05 '25 00:12

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!