jeff
jeff

Reputation: 387

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)

Upvotes: 0

Views: 70

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270431

I would recommend:

order by (case when order is not null) desc,
         rand()

Upvotes: 1

Akina
Akina

Reputation: 42728

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

Upvotes: 2

Related Questions