Jader Dias
Jader Dias

Reputation: 90475

How to select multiple rows by primary key in 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?

Upvotes: 2

Views: 3687

Answers (4)

lexu
lexu

Reputation: 8849

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.

Upvotes: 8

SQLMenace
SQLMenace

Reputation: 135021

what about

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

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134177

You can use the IN keyword to achieve this:

SELECT * FROM Table WHERE PRIMARY_KEY IN (VALUE1, VALUE2, ...)

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798706

SELECT * FROM table WHERE primary_key IN (value1, value2, ...)

Upvotes: 4

Related Questions