I have a mysql table with only one column, the column has got some 3 letter words and some 4 letter words, and some 5 and 6 letter words.
I want a query to at first select randomly from all 3 letter words, when they’re all gone, then move on to 4 letter words, and so on.
This is my query:
SELECT `word` FROM `words` ORDER BY LENGTH(`word`) ASC, RAND() LIMIT 1
This works as expected so far in the few times I’ve tried, but I’d like to be sure that it’ll always work like this.
Your query looks fine to me, but I hope the table is small because MySQL will be scanning all the rows every time and then using filesort, all to return a single row.
Adding a
wordlengthcolumn and indexing it will not improve the query because theORDER BY RAND()function would invalidate use of the index.Consider splitting the words up into separate tables, depending on their length, at least you’ll only be scanning all rows for words of the same length. Select from the three_letter_words table first, and if there are no results, then select from the four_letter_words table, and so on.