SELECT a random row with SQL
By Pete Freitag
There are lots of ways to select a random record or row from a database table. Here are some example SQL statements that don't require additional application logic, but each database server requires different SQL syntax.
Select a random row with MySQL:
SELECT column FROM table ORDER BY RAND() LIMIT 1
Select a random row with PostgreSQL:
SELECT column FROM table ORDER BY RANDOM() LIMIT 1
Select a random row with Microsoft SQL Server:
SELECT TOP 1 column FROM table ORDER BY NEWID()
Note: SQL Server also supports using ORDER BY rand()
but it will not actually select a random row order, the results will always be the same.
Select a random row with IBM DB2
SELECT column, RAND() as IDX FROM table ORDER BY IDX FETCH FIRST 1 ROWS ONLY
Thanks Tim!
Select a random record with Oracle:
SELECT column FROM ( SELECT column FROM table ORDER BY dbms_random.value ) WHERE rownum = 1
Thanks Mark Murphy
You may find that ORDER BY RAND() in MySQL or ORDER BY RANDOM() is PostgreSQL do not yield great performance on very large tables. Another approach you can take in that situation is to do a count and then offset. So it requires two queries, and works like this:
SELECT count(*) AS n FROM table
Then you pick a random number between 0 and n and use it as the OFFSET value:
SELECT column FROM table LIMIT 1 OFFSET :randomValue
The LIMIT and OFFSET statements work in both MySQL and PostgreSQL, other database engines have similar functionality.
You'll have to pick that random value using your programming language of choice. This approach may not be that much faster so you should see how fast the original random query
SELECT a random row with SQL was first published on September 14, 2005.
If you like reading about sql, databases, postgresql, mysql, sqlserver, oracle, or select then you might also like:
- SQL Reserved Key Words Checker Tool
- Order by NULL Values in MySQL, Postgresql and SQL Server
- INFORMATION_SCHEMA Support in MySQL, PostgreSQL
- Returning TOP N Records
Discuss / Follow me on Twitter ↯
Tweet Follow @pfreitagComments
Personally - I would go with application logic so my app would work across multiple databases in most cases. In some cases I would go with the db specific option.
SELECT column FROM
(
SELECT column FROM table
ORDER BY dbms_random.value
)
WHERE rownum = 1
Here's a link to a method (requiring application logic) that has much better performance with large sets: http://www.greggdev.com/web/articles.php?id=6 The examples are PHP (ick), but they're easily understandable.
I don´t need to make an inline view. That gives me the first row in the recordset :-)
SELECT col FROM tbl LIMIT 1 OFFSET 1
Really It helps me more!!!!!1
Select cols
From table
SAMPLE RANDOMIZED ALLOCATION 10
Thanks
Renu
I want a table in sql server in which third column contains the sum of 2nd column. For Example
Col1 Col2 Col3
A 1 1(Sum of 1 and 0)
B 2 3(Sum of 2 and 1)
C 4 6(Sum of 4 and 2)
D 5 9(Sum of 4 and 5)
Thanks in Advance
I appreciate it!
Thanks in advance
I want to retrieve some fields like customer name,customer_number and the totals of the sold_qty,billed_fees per annum for different customers in a single row per customer. I am getting group by expression error when I try can anyone provide some updates?
In a small dataset I find that the same record as that just selected randomly can be randomly selected again.
How would you modify the random query (for MS SQL Server) to NOT INCLUDE the previously selected record on a new request.
In my use we randomly display a new image (redord) on refreshing the web-browser page (which causes the query to run.)
Thank you.
can any one help me by giving suggetion or query?
thanks in advance
Each time you run the script you will get the same set of rows.
Any ideas greatly appreciated.
I have a table
2. name of the table is constant. ex:CustomFields
3. but the columns names & no of colmuns differ.
4. as this table contains millions of rows, it is difficult to browse which column has atleast one value in its respective rows.
5. so find the columns which have atleast one value in it.
6. two sets of results i want: a) cols with atleast one value b) cols with out any value.
How to select it.
Any help would be greatly appreciated.
Thank You.
i am dealing Medical Lab Information System. the table is given below
testname testvalue
-------- ---------
AC 21
PC 12
i want the table selection like the following
AC PC
21 12
Please give me solution..
thanks in advance..
my email:selvinm@gmail.com
'Get the number of possible rows in the table
varcount = run "Select count(rowid) from table"
'then, in code, generate a random number between 0 to the rowcount
varOFFSET = rnd * varcount
'Then run your new select statement offsetting it by the random value
randomrow = run "SELECT column FROM table
LIMIT 1 OFFSET " & varOFFSET
I tested it and it improved performance greatly. I only have 5000 records and it helped a lot. I imagine with millions of records this would be much more valuable.
It's been a while! Looked up this post because I couldn't remember the DB2 syntax I contributed earlier -- come to find out, it doesn't work on DB2 v8.2 running on z/OS. I get an exception saying the RAND() function is non-deterministic, and as such, can't be used in an ORDER BY CLAUSE...
The work-around:
SELECT <column_name>, RAND() as IDX FROM <table_name> ORDER BY IDX FETCH FIRST 1 ROWS ONLY
empno =100
salary=1000
dept name=IT
------------
empno =100
salary=1000
dept name=IT
------------
empno =100
salary=1000
dept name=IT
------------
empno =100
salary=1000
SELECT * FROM people ORDER BY RND(personID)
It's important you use a number column
I hav Q.. and trying to fd an answer.. I need all ur help:
I have a table in which I have result, defect,name as columns:
Name Result Defect
A P x
A P x1
B P X2
When defect is not null and defect!=' ', I select the rest of the defect
for a particular 'name'='A'
I get the below result
x
x1
i.e two rows, but I need this in a single row like:
x,x1
is this possible?
I tried with COALESCE function in T-SQL... here it goes below:
I need a confirmation whether its correct or not... cos I dont have sufficient permission to create this function in my DB...
CREATE FUNCTION dbo.UDF_getdefect
( @name varchar(1000) )
RETURNS varchar(1000)
AS
BEGIN
DECLARE @defect varchar(1000), @Delimiter char
SET @Delimiter = '+'
SELECT @defected = COALESCE(@defected + @Delimiter, ') + defect FROM
(Select defect
from table1
where defect is NOT NULL and defect != ' '
and name =@name) derived
where defect is NOT NULL and defectReportId != ' '
and name =@name
RETURN ( SELECT REPLACE(@defected,')+(',') + (') AS [Defects])
END
If I need the result of this function in another Select query can I use it as below?
(Select getDefect(name),name from table1) as defected
select top 1 column from tabela order by RND(INT(NOW*id)-NOW*id)
"id" is the column auto_numeric primary key
;D
Another great solution to selecting a random row: count number of rows in the table, pick a random value from 0 to that count (using applic logic to do random), then fetch data on that row using "LIMIT ROW#,1". This is the only method that works flawlessly here, across hundreds of millions of rows, in production, on mysql 5.0 in a myisam table in under 100msec. The trick is to use the same WHERE clause on both the count and the pull.
where rownum<=4
minus
select rownum,ename,sal from (select ename,sal from emp order by sal desc)
where rownum<=3