To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).
Now let's find how to do Random Sampling within Groups in SQL using RAND() function. Below SQL statement is to display rows in random order using RAND() function: Query: SELECT * FROM table_name order by RANDOM();
To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.
SELECT TOP 5 Id, Name FROM customerNames
ORDER BY NEWID()
That said, everybody seems to come to this page for the more general answer to your question:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
SELECT TOP 1 column FROM table
ORDER BY NEWID()
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1
SELECT column FROM table
ORDER BY RANDOM() LIMIT 1
SELECT TOP 5 Id, Name FROM customerNames ORDER BY NEWID()
In case someone wants a PostgreSQL solution:
select id, name
from customer
order by random()
limit 5;
Maybe this site will be of assistance.
For those who don't want to click through:
SELECT TOP 1 column FROM table
ORDER BY NEWID()
There is a nice Microsoft SQL Server 2005 specific solution here. Deals with the problem where you are working with a large result set (not the question I know).
Selecting Rows Randomly from a Large Table http://msdn.microsoft.com/en-us/library/cc441928.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With