What is the best way to select multiple rows by ID in sql?
SELECT *
FROM `table`
where ID in (5263, 5625, 5628, 5621)
is probably better, but not faster.
SELECT *
FROM `table`
WHERE `ID` in (5623, 5625, 5628, 5621)
While Researching this further I came across an interesting blog post that explains how to use a set to get faster SQL performance from In clauses, by creating list of ids into a Common Table Expression (CTE) and then joining on that.
So you could code the PHP equivalent of the following to get maximum performance.
DECLARE @idList varchar(256)
SET @idList = '5623, 5625, 5628, 5621'
;with ids (id) as
(
SELECT value FROM UTILfn_Split(@idList,',')
)
SELECT t.*
FROM table as t
INNER JOIN ids
ON t.ID = ids.id