Select Random SQL


Sometimes if you want to extract some records from a table you can use the following SQL syntax

select * from table order by rand() limit 10

Different SQL servers have different syntax on selecting random rows. For example, MSSQL uses the following syntax.

select top 10 * from mytable order by newid()

However, this is very inefficient and can be replaced by fetching everything into an array and items are chosen randomly in script language such as PHP.

The alternative would be to have an extra field in the table that is indexed and random populated. Every time the column is updated. The SQL with the indexing can be good enough. This method is less time-consuming but at the cost of additional column and operation required.

The following may be also useful.

select * from table where ID >= rand() * (select max(ID) from table) limit 10

It does not necessary have to be ID. Any numerical fields would be OK. This is far efficient than the methods above, especially if you have index built on the column ID.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
229 words
Last Post: Some SEO Tips
Next Post: Checking Bots using PHP Script

The Permanent URL is: Select Random SQL

Leave a Reply