Friday, November 6, 2009

SQL Commands for Displaying Random Record

Have you ever seen the applications that displays a random tips, messages or informations? For example, displays messages, advice or tips on web pages. Every time with or without refresh, the page displays the message, the message appears change at random.

Displaying Random Record can be made only by using SQL statement, without your hard-work to write a script or program. There is in the SQL function RAND (). This function can generate random numbers.

By default, this function will result in real numbers range from 0 - 1.

Example usage: SELECT RAND ();

SQL Commands, Random Record


Above statement will produce output random real numbers range from 0 - 1.

Function RAND () in the example above is placed in the SELECT. But you can also put it in the ORDER BY.

Example usage: SELECT * FROM table ORDER BY RAND ();
SQL Commands, Random Record
Well ... if the above statement will show a record that will be selected at random among all the records in the table.

You may then ask, what if you want to select N records at random from all that is in the table? The way that is easy enough just by adding a LIMIT command N.

Example usage: SELECT * FROM table ORDER BY RAND () LIMIT 3;

SQL Commands, Random Record

Statement on the record will show random 3.

You can also use the WHERE, as in the following statement SELECT * FROM table WHERE conditions ORDER BY RAND () LIMIT 3;

Miraculously ... let's say you choose N random records with a SQL statement above, then the N records are not the same.

0 comments:

Post a Comment

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Sweet Tomatoes Printable Coupons