In my jsp application I have a search box that lets user to search for user names in the database. I send an ajax call on each keystroke and fetch 5 random names starting with the entered string.
I am using the below query:
select userid,name,pic from tbl_mst_users where name like 'queryStr%' order by rand() limit 5
But this is very slow as I have more than 2000 records in my table.
Is there any better approach which takes less time and let me achieve the same..? I need random values.
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
SELECTclause. 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:
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.