DEV Community

Cover image for SQL-Quick tip #2 - Randomize rows
Allan Simonsen
Allan Simonsen

Posted on

2 2

SQL-Quick tip #2 - Randomize rows

Sql Server tips and tricks

This is part of a series of quick tips and tricks I have accumulated over the year, that I think can be useful for others.
If you have similar short tips and tricks please leave a comment.

Randomize rows

Sometimes you want the returned rows of your query to be randomized. That could be when generating test data.
The trick is to use ORDER BY NEWID(). The NEWID() function will generate a new random guid for each row and when sorted the rows will be randomized.
This is not something you should put into your production code unless you have no other way of randomizing you rows, because Sql Server has no way of optimizing this kind of query so if the trick is used on a large table it will take time and computing resources.

DECLARE @names TABLE ([Name] VARCHAR(50))

INSERT INTO @names (Name) 
VALUES ('Joe'), ('Bob'), ('Anne'), ('Jane')

SELECT Name
  FROM @names
 ORDER BY NEWID() -- By ordering by NEWID() the rows will be randomized
Enter fullscreen mode Exit fullscreen mode

Sql Server Management Studio screenshot

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay