ASP.NET Cafe
new tricks every week

MS SQL. Get rows in random order.

Monday, 15 September 2008 06:42 by dmitriy

During web development often task is to get some stuff in random order. For example, to display random articles, products, testimonials and so on.

First thing you want to do is to write something like this:

SELECT TOP 10 * 
FROM Articles 
ORDER BY RAND() 

And previous query DOES NOT work. It shows records in regular order. Why? Because RAND() calculated once, not in each row.

The following way works fine:

SELECT TOP 10 * 
FROM Articles 
ORDER BY NEWID() 

That's all. Nice and easy. Not recommended for HUGE tables... but this is crazy to try show something randomly from the huge table. Use other ways. For example sub queries.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:  
Categories:   Main | SQL
Actions: E-mail | del.icio.us | Kick it! | DZone it! | Permalink | Comments (0) | Comment RSSRSS comment feed

Comments

Add comment


 

  Country flag

biuquote
  • Comment
  • Preview
Loading