September 14, 2005
SQL to Select a random row from a database table
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()
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
Feel free to post other example, variations, and SQL statements for other database servers in the comments.
Related Entries
123 people found this page useful, what do you think?
Trackback Address: 466/2A738BB0EE08AFD98813801EAD41CB70
Fortunately additional application logic allows your app to be cross DB.
Indeed it does Bryan, but these will usually perform better. Like most things in programming there is a tradeoff.
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.
Agree, just adding more information to your post.
Thanks, I probably should have posted a bit about that tradeoff in the post - oh well its down here now.
The Oracle one doesn't work; you need an inline view:
SELECT column FROM ( SELECT column FROM table ORDER BY dbms_random.value ) WHERE rownum = 1
At least on MySQL (and I'd imagine the others) the ORDER BY RAND() method scales very poorly, since it requires not only generating a random number for every row in the table, but then also sorting those unindexed values. Get more than a couple thousand rows in your table and it's ridiculously slow.
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.
If you have a table with many rows, you can make this query much faster.
A simple SELECT * FROM table ORDER BY RAND() has to do a sort in memory- expensive. If you change the query to SELECT * FROM table WHERE RAND()>0.9 ORDER BY RAND() then you've reduced the overhead of the sort by 90%.
This will have the overhead of many RAND() statements, but on DB2 mainframes, it is a much faster technique.
I have no problems using "SELECT * FROM table WHERE column ='value' AND rownum <= 1" in Oracle 9i. I don´t need to make an inline view. That gives me the first row in the recordset :-)
Hai, Ths s elango.I have tried the above query what u have given but its not working in my database. I m tried in Sql Server Enterprise Manager... It given the following error.. [Miscrosoft][ODBC Sql Server Driver][Sql Server]'RANDOM' is not a recoganized function name. Could u pls help me to resolve ths solution.. bye bye Excepting u r reply as soon as possible Elango.M
Thanks. The systax worked perfect on my Oracle 9.2, and I used it in one of my SQR reports.
Hi guys,Thanx , it worked perfectly on my oracle database n retrived the rows i reqd for an update
How to delete the duplicate values (if 2 rows there, delete one row)in single table
how to retrieve second record from a table without using the where clause
To get the second record on mysql or postgresql you can use LIMIT and OFFSET, eg:
SELECT col FROM tbl LIMIT 1 OFFSET 1
It's a very helpful media which solves our difficult problem. Really It helps me more!!!!!1
It's great info - but I can't get it working in my script using a MDB Database via ODBC
Just one more db missing, firebird. Select a random row with Firebird: 1) Install ib_udf (comes with the server) or at least the rand() function with this statement: DECLARE EXTERNAL FUNCTION rand RETURNS DOUBLE PRECISION BY VALUE ENTRY_POINT 'IB_UDF_rand' MODULE_NAME 'ib_udf';
2)Now proceed in selecting a random row from the database: SELECT FIRST 1 * FROM country ORDER BY rand()
how can pull two records from mysql randomly
what about MsAccess databse, how to select random row?
hemant: just adjust the LIMIT clause: SELECT column FROM table ORDER BY RAND() LIMIT 2 will pull two rows.
How can I select a random record from a random table? Can anyone help?
Great article, very useful, it helped me avoid using stored proceedures and cursors for a specific solution
Is there any one know SQL Random function for NCR Teradata? thanks so much for reading this.
for Teradata, use the sample feature: select * from table_name sample 1
using an integer will return that many rows, using a decimal will return that percent (ie .01 will bring back a 1 percent sample of rows)
In Teradata,we can get random records use the below given Query.
Select cols From table SAMPLE RANDOMIZED ALLOCATION 10
Thanks Renu
Is there a way to pull top 10 rows in Teradata? I know in other databases we dan do it. "SAMPLE" pulls the rows and then gets random sample, I'm trying to pull only top 10 rows and not spool the whole table. --thanx
Oracle also has a SAMPLE function, similar to Teradata mentioned above.
I have no problems using "SELECT * FROM table WHERE column ='value' AND rownum <= 1" in Oracle 9i. I don´t need to make an inline view. That gives me the first row in the recordset :-)
For PostgreSQL this worked much better:
SELECT * FROM table OFFSET RANDOM() LIMIT 1;
Throug Query 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 want to delete first 10 rows in sql 2000, can any one help me?
>>I want to delete first 10 rows in sql 2000, can any one help me?
Delete Top 10 from [table_name]
To delete the first 10 rows in sql 2000/Sybase from table test_table (Follows the order of the clustered index on the table)
set rowcount 10 delete from test_table
How do i delete first 'n' rows from a table on PL/SQL ??? ( I tried the following 2 options but it gave an error saying command not properly ended: "set rowcount 10 delete from test_table" "Delete Top 10 from [table_name]" )
Please Suggest ... Thanks, Shantanu
Thanks for the great mySQL syntax. I'm using this on an application with a nice, small database, and it works perfectly. Saves me a good chunk of application logic.
I appreciate it!
Can anyone help me in "How to delete first 10 rows in db2 udb"
Thank You Hill
whts the sql statement to select one record at a time.the next record want to see when we click next button.
Can anydody tell me how to delete all the duplicate rows in a table. The database in POSTGRESQL. Thanks in advance
How to select data in second row from a table in SQL Server 2000?
How to select data in second row from a table in SQL Server 2000?
How to delete one of the two duplicate rows
How to create procedure using ( two tables from one database and two tables from another database) in ms-sql
How to retrieve the third row from a table in sql server without using primary key or any other distinct key and dont use order.
How to change the order of the columns in the created table?
How I can delete any random row from a table.
How to select top 10 records?
Hi All,
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?
welcome to the general support SQL forum for outsourcing companies (hey guys, remember that your boss is charging someone for your work. you're supposed to know things like this already! ;-)
how to get random values in SQL.
Your examples were very clear and (almost) just what I need to do.
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.
i want to delete last 2 records for a particular proposal from a proposal details table in orcale database. can any one help me by giving suggetion or query?
thanks in advance
The firebird solution above does not work because the rand() function returns the same number each time within a query. So rows are not randomly ordered.
Each time you run the script you will get the same set of rows.
To implement a row limit for a select or delete, try the following... it works in just about every database:
truncate table tablename --10
Note: the --10 is an option specifying the row limit. You can then perform your select or delete statement after that and the results will be truncated at 10 rows (or however many you specify). For example:
truncate table customers --10
select * from customers
This will return the first 10 customers. Enjoy!
Hi,
This is Ravi, need to know how to fetch the random rows in sybase.
Thanks
Ravi
hello guys what up! please help me to learn MySQL syntax at PHP
Need to pull every 100th row from table in MS Server 2000. We can't use incrementing id columns as deletions and sorting requirements would render those values useless. Any ideas greatly appreciated.
how to retrive nth row from a table in sqlserver with out using top and cursor
please give the answer for the below
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.
DO NOT FOLLOW THE COMMENT FROM "Nonnamiss"!
The TRUNCATE command will *delete* your data.
The "-- 10" command is a SQL comment and will have no effect.
Pete, I suggest you delete/mark this dangerous post.
how can i fatch specified no of rows starting from some row no. for eg. if i want to fatch records from 5th row to 10th row how can i do it.
Hi,
I want to update one table in sybase but it is taking very long time as the table contains millions of records. The server is going down. Is there any way to do batch wise
oh my god, what is with you people, and people asking questions like how to select top 10 records, well maybe you write select top 10 ?!? are you serious ? are you programmers or housewives ?
sorry for my bad english.
Hi,
I have a table with 2 colums, and I wanted to get all the records in a single row (My SQL). Can any one help me on this.
<table cellpadding="0" cellspacing="0" border="0" bgcolor="#E8EFDA" width="100%" style="border-bottom:#669900 1px dashed; border-top:#669900 1px dashed"> <tr><td style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; padding:10px; color:#996600"> <span style="color:#4A7B2D;"><b>here's the code for that</b></span><br /><br /> select table1.*, table2.* from table1, table2 where table1.id=table2.id</td> </tr> </table>
I want to select some random records from MS Access Database. How to select it. Any help would be greatly appreciated. Thank You.
Thanks for the SQL info on RAND() Functions. Much Appreciated.
Hi i want to select my row as column 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
you can use WHERE clause to specify your selection ( Nfact i didn't understand your table ). After that Nphp do some loop stuff by using (while) to retrive those data from the returned array.
Thanks for the random row tips. I sometimes have a large number of records so I took your idea and expanded on it. Here's a generic app of how the logic should work. I created the sql with MySQL:
'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.
Hey Pete -
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
Thanks Tim! I've updated the example in the entry.
That's great! Using SQL Server 2005, how would you select random rows via a function?
How to desplay data like blow throw Select statement. 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
VERY handy! I used dbms_random.value and rownum < 11 in a three layer nested query to pull 10 random grouped records to populate a script for a nightly data population process. THANKS!
If you want random results in ACCESS simply add SORT BY RND(id) to your SQL.
SELECT * FROM people ORDER BY RND(personID)
It's important you use a number column
I would like to filter one row from a list of rows, does anyone know how i can do it? I am using mysql db
Thank you. TSQL query save me a lot of work.
a useful post for many.. 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
How To see in SQL server six th row
Thanks tim, and mark murphy !! you have done a great job, making things a lot easier for innumberable sql guys.
SQL query
I have 3 laks recored in table t1.I want to retin first 100 recored and rest of records should be delted....can any one hlep..
ADVACED THANKS
Solution for MSAccess: select top 1 column from tabela order by RND(INT(NOW*id)-NOW*id) "id" is the column auto_numeric primary key ;D
Thanks a log... very good post.
thanks for the great info. do you know how to select multiple random rows? not just a row. thanks
i want to only 5th row in sql 2005 give me a query
does the (Limit) statement in mysql work in Microsoft sql server 2000
MS Access: select top 1 * from tablename order by rnd(id)
id should be an autonumber field
When people are lazy and stupid, it is duty by god to slap them as hard as possible. Public blogs should not allow unfiltered public comments. Idiotic, below-beginner, ultra-annoying- -and-maximally-undeserving- novice requests like, 'tell me how to select the top 5 rows' drag down everyone and should not only never be answered, but they should be deleted.
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.
how would i go about randomly picking maybe 10 rows and having it save in another table?!?!?!?!
Hi How to fetch the 4th record alone from the table using sql?
i have 4 tables, how i retrive data randomly from 4 tables in sql server 2000, please help thanx in advance
select rownum,ename,sal from (select ename,sal from emp order by sal desc) where rownum<=4 minus select rownum,ename,sal from (select ename,sal from emp order by sal desc) where rownum<=3
How to get fifth highest record from table using top command in sql.
How to get fifth highest record from table using top command in sql.
Hi this is very useful for me...thanks for posting this query.
Hi, I'm a housewife. How do I select rows 18-32 from a random selected table ordered by color?
Hi I want the sql query to display columns of different rows in a single row.The data base is given below. I want to make it in one row with all the details. Please help
1 Rahul Bose Male #13, Bangalore, 686691 Landphone-4452121252 1 Rahul Bose Male #13, Bangalore, 686691 Mobilephone2-558521252 1 Rahul Bose Male #13, Bangalore, 686691 Official_Email-TL@abc.com
How can we display duplicate elements along with duplicate element. Example: table name xxxx column name yyyy elements are jhon jhon vignesh sat sat Result should be jhon jhon sat sat
in a oracle table i have 10 rows ,i want only 6rows,how to retrive that, ( I WANT ONLY RANDOM DATA) NOT like rowid < 7 data ? how to get this ?
Q.(1)How we retrieve data from oracle database randomly; like at first i want to choose data from row 1 then row 5 then row 3.
Q.(2)How I create auto increment in oracle like My Sql. Q.(3) How I edit data in PL/SQL
How to interchange to row to column to SQL database
how to apply this to a jump menu?
i want to delete 1st row from table in ms sql server 2000 but there is primary key so plz help me
i want to be able to google fors answer? how to do? tel me nows!
Please post me a query that would swap the contents of two columns with same datatype, of course.
Hello,
I am kartik. i want to study material. help me. All SQL Study Material. plz All Information in my mail address send to you.
Thank You Kartik Shah