SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Random Ordering of Results using NEWID

A discussion of how NEWID can be used to help randomize the results returned from a SQL query.

A scenario I hadn’t encountered until recently is as follows: How does one get a certain number of randomly selected records from a table? Nope, I didn’t need to do this for work. Instead, I’m using it as a way to help determine ideas to write about for this site!

Recently I created a database table to help track potential post ideas. I have dozens of ideas [and add new ones as I think of them], but I had no good way to whittle the list down to help in the decision making process. Well, now I do. Behold:

SELECT top 4 NUMBER, description FROM SQLPostIdeas
WHERE isnull(DatePosted, '') = '' AND isnull(IsDuplicate, 0) = 0

I’ll always get 4 ideas to choose from when running this query because of the top 4 statement, and the records returned are randomly selected [because of the order by statement].


No comments.

Leave a Comment

Please register or log in to leave a comment.