Select Random Records in MySQl, SQL Server & Oracle, etc
Quite often a user will want a random display of items from his database. Ads, Thumbnails, Topics... whatever.... Here are some quick queries that can perform just that task for you:
Scenario: I want to select 5 records from my famous-foo table in no particular order, and I have no idea how many records are there....
In MySQL:
select * from famous-foo order by rand() limit 5
In SQL Server (7, 2000+):
select top 5 * from famous-foo order by newid()
In Oracle:
select * from famous-foo sample(5)
select * from (select * from famous-foo order by dbms_random.value) where rownum = 5
In PostreSQL
select * from famous-foo order by random() limit 5

There are no comments for this entry.
[Add Comment]