Search code examples
mysqlsqlruby-on-railsruby-on-rails-5

query sort records randomly


I am showing in my view all the users of my user table, in the table there is a field called "order" in which I assign a number to the first 200 records so that these users who had the value in the "order" field are will show first that those who had null in that field.

Is it possible that those first 200 users can show them first and randomly?

this is my query:

@users = User.includes(:plan).with_avatar



@users = @users.order( '`order` DESC, sponsor DESC, id DESC' ) 
@users = @users.paginate(page: page).per_page(18)

Solution

  • Is it possible that those first 200 users can show them first and randomly?

    ORDER BY CASE WHEN order <= 200
                  THEN RAND()
                  ELSE order
                  END