For a project I had a specific requirement where I needed to show data in a random order. Instead of doing this code, I found an easy solution to do this using raw SQL.
The trick is to add an ORDER BY NewId() to your SQL statement. This is guaranteed to produce a different order every time.
Let’s show a quick example using the good old Northwind database:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT Products.ProductName, ROW_NUMBER() OVER (ORDER BY NewId()) as RandomOrder | |
FROM Products |
When we execute this query, we'll see a different order everytime:
Next run: