Search code examples
grailsgrails-orm

Grails GORM to return random rows from table?


In my grails application I have:

keywords = Keyword
    .findAll("from Keyword where locale = '$locale' order by rand() ", [max:20])

Assume there are thousands of rows in the table that match the above criteria. But it seems the rows that are returned from the table are not random but in the order the rows are stored in Db although within the context of 20 rows that are returned they are random. For my application to work I want this query to return completely random rows from the table like it could be row id 203 , row id 3789, row id 9087, row id 789, and so on. How is that possible?


Solution

  • I use the following style:

    Keyword.executeQuery('from Keyword order by rand()', [max: 9])
    

    and it returns random rows from the entire table (we're using MySQL).

    I'm not sure why execute query would behave differently from findAll though.