How slow is "very slow", in seconds?
The reason why your query could be slow is most likely that you didn't place an index on name
. 2000 rows should be a piece of cake for MySQL to handle.
The other possible reason is that you have many columns in the SELECT
clause. I assume in this case the MySQL engine first copies all this data to a temp table before sorting this large result set.
I advise the following, so that you work only with indexes, for as long as possible:
SELECT userid, name, pic
FROM tbl_mst_users
JOIN (
-- here, MySQL works on indexes only
SELECT userid
FROM tbl_mst_users
WHERE name LIKE 'queryStr%'
ORDER BY RAND() LIMIT 5
) AS sub USING(userid); -- join other columns only after picking the rows in the sub-query.
This method is a bit better, but still does not scale well. However, it should be sufficient for small tables (2000 rows is, indeed, small).
The link provided by @user1461434 is quite interesting. It describes a solution with almost constant performance. Only drawback is that it returns only one random row at a time.