Database - How To Randomly Select Rows in SQL - Stack Overflow
Database - How To Randomly Select Rows in SQL - Stack Overflow
- Stack Overflow
2024 Developer survey is here and we would like to hear from you! Take the 2024 Developer Survey
I am using MSSQL Server 2005. In my db, I have a table "customerNames" which has two
columns "Id" and "Name" and approx. 1,000 results.
308 I am creating a functionality where I have to pick 5 customers randomly every time. Can anyone
tell me how to create a query which will get random 5 rows (Id, and Name) every time when
query is executed?
Share Improve this question Follow edited Dec 29, 2012 at 0:11 asked Feb 24, 2009 at 6:14
Kate Gregory djmzfKnm
18.9k 8 58 86 27k 70 170 232
Random is not a common requirement for a Database, I was surprised to find a link for some SQL – Paxic
Feb 24, 2009 at 6:20
828
That said, everybody seems to come to this page for the more general answer to your question:
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 1/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
LIMIT 1
Share Improve this answer Follow edited Jan 13, 2017 at 21:19 answered Jul 30, 2009 at 23:28
Katherine Mejia-Guerra Curtis Tasker
118 1 6 11.3k 2 23 23
33 Does this become very expensive on large tables, where each row gets a random number, and then a large
unindexed random number set is sorted? – Andrey Apr 19, 2014 at 16:04
1 This is perhaps obvious to most people, but it wasn't obvious to me... the following query will not get a
new random value for each row: update tbl_vouchers set tbl_UsersID = (select top(1) id from
tbl_Users order by NEWID()) - edit: I can't get formatting to work in comments :( – Mir Dec 10, 2015 at
18:35
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 2/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
Why does this fail on Google Cloud SQL? We only get partially random results. Nearly 80% of the time we
get the same row back. – Praxiteles Nov 25, 2016 at 22:38
8 Warning: For big databases this method will have a bad performance. Can you imagine the time it will take
to generate a random value for each row if the database have a million of entry? You can have more
information about and a better alternativ here. – Francis Ngueukam Dec 15, 2016 at 9:33
Thanks for the solution. Just wanted to know if we can assign some kind of a declare variable to the value
after the 'limit' keyword. I am trying to find solutions in bigquery but haven't had much luck yet.
– Ajay Kumar Jan 20, 2020 at 9:52
39
Share Improve this answer Follow answered Feb 24, 2009 at 6:21
Cody Caughlan
32.6k 5 65 68
Share Improve this answer Follow answered Feb 24, 2009 at 6:45
Barry Brown
20.5k 15 70 106
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 3/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
TABLESAMPLE(n ROWS) or TABLESAMPLE(n PERCENT) is random but need to add the TOP n to get the
correct sample size.
Share Improve this answer Follow edited May 4, 2020 at 20:16 answered Aug 15, 2013 at 23:08
TylerH Billy
21.1k 72 78 105 351 3 5
Share Improve this answer Follow answered Feb 24, 2009 at 6:21
user60456
4 should have at least replaced 1 with 5 :) – roman m Feb 24, 2009 at 6:40
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).
8 Selecting Rows Randomly from a Large Table http://msdn.microsoft.com/en-
us/library/cc441928.aspx
Share Improve this answer Follow answered Sep 23, 2012 at 12:17
JohnC
3,077 1 25 33
This is an old question, but attempting to apply a new field (either NEWID() or ORDER BY rand())
to a table with a large number of rows would be prohibitively expensive. If you have incremental,
unique IDs (and do not have any holes) it will be more efficient to calculate the X # of IDs to be
7
selected instead of applying a GUID or similar to every single row and then taking the top X # of.
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 4/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
DECLARE @randomId1 int, @randomId2 int, @randomId3 int, @randomId4 int, @randomId5 int
SET @randomId1 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId2 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId3 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId4 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId5 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
If you wanted to select many more rows I would look into populating a #tempTable with an ID
and a bunch of rand() values then using each rand() value to scale to the min-max values. That
way you do not have to define all of the @randomId1...n parameters. I've included an example
below using a CTE to populate the initial table.
Share Improve this answer Follow edited Dec 27, 2019 at 0:36 answered Jul 17, 2018 at 18:15
Protiguous RIanGillis
99 2 9 619 1 6 15
@Protiguous, the edit you proposed broke the random selection. Using min() and max() applied to the
dbo.Tally64k table would not allow the user to select a row with a pk id > 65556. – RIanGillis Sep 23, 2019
at 13:41
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 5/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
The table name change was simply an artifact from testing. The actual table name doesn't matter, as long
as the correct table is used. min() and max() can both be queried in one query rather than two, which is
what I was trying to show. – Protiguous Jan 14, 2020 at 21:48
@Protiguous Ah, I see that now, I was confused because you used the 0-65k when doing the min-max but
not later. After your most recent edit I actually wanted to ask you about the performance implications of
the changes you made, as performance tuning is one of my interests and seemingly meaningless decisions
like which side of the equals sign you place something can actually have a significant impact --- Would the
same thing apply to the 5 SET @randomId## calls? Or is that different because it is not SELECTing FROM
an actual table? – RIanGillis Jan 15, 2020 at 4:49
I'm not sure I understand your question. Are you asking why there are 5 SET instead of just 1 SELECT
@id1=rand(), @id2=rand().. ? It's because multiple calls to a rand() in 1 statement will produce the same
result, hence the separated SET. (rand() on SQL Server is a deterministic function, I believe.) I would guess
that 1 select vs 5 set is in the nanosecond range performance-wise. – Protiguous Mar 6, 2020 at 23:43
If you have a table with millions of rows and care about the performance, this could be a better
answer:
6
SELECT * FROM Table1
WHERE (ABS(CAST(
(BINARY_CHECKSUM
(keycol1, NEWID())) as int))
% 100) < 10
https://msdn.microsoft.com/en-us/library/cc441928.aspx
Note that this will select approximately 10% of the rows in the table. If you need to select an exact number
of rows, or at least N rows, this approach won't work. – LarsH Jun 3, 2019 at 14:49
6
Share Improve this answer Follow edited Mar 25, 2020 at 23:59 answered Feb 25, 2015 at 7:49
Pang Narendra
9,851 146 85 123 967 15 29
In order to shuffle the SQL result set, you need to use a database-specific function call.
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 6/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
Note that sorting a large result set using a RANDOM function might turn out to be very
slow, so make sure you do that on small result sets.
3
If you have to shuffle a large result set and limit it afterward, then it's better to use
something like the Oracle SAMPLE(N) or the TABLESAMPLE in SQL Server or PostgreSQL
instead of a random function in the ORDER BY clause.
| id | artist | title |
|----|---------------------------------|------------------------------------|
| 1 | Miyagi & Эндшпиль ft. Рем Дигга | I Got Love |
| 2 | HAIM | Don't Save Me (Cyril Hahn Remix) |
| 3 | 2Pac ft. DMX | Rise Of A Champion (GalilHD Remix) |
| 4 | Ed Sheeran & Passenger | No Diggity (Kygo Remix) |
| 5 | JP Cooper ft. Mali-Koa | All This Love |
Oracle
On Oracle, you need to use the DBMS_RANDOM.VALUE function, as illustrated by the following
example:
SELECT
artist||' - '||title AS song
FROM song
ORDER BY DBMS_RANDOM.VALUE
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 7/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
When running the aforementioned SQL query on Oracle, we are going to get the following result
set:
| song |
|---------------------------------------------------|
| JP Cooper ft. Mali-Koa - All This Love |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| HAIM - Don't Save Me (Cyril Hahn Remix) |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix) |
| Miyagi & Эндшпиль ft. Рем Дигга - I Got Love |
Notice that the songs are being listed in random order, thanks to the DBMS_RANDOM.VALUE
function call used by the ORDER BY clause.
SQL Server
On SQL Server, you need to use the NEWID function, as illustrated by the following example:
SELECT
CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY NEWID()
When running the aforementioned SQL query on SQL Server, we are going to get the following
result set:
| song |
|---------------------------------------------------|
| Miyagi & Эндшпиль ft. Рем Дигга - I Got Love |
| JP Cooper ft. Mali-Koa - All This Love |
| HAIM - Don't Save Me (Cyril Hahn Remix) |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix) |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
Notice that the songs are being listed in random order, thanks to the NEWID function call
used by the ORDER BY clause.
PostgreSQL
On PostgreSQL, you need to use the random function, as illustrated by the following example:
SELECT
artist||' - '||title AS song
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 8/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
FROM song
ORDER BY random()
When running the aforementioned SQL query on PostgreSQL, we are going to get the following
result set:
| song |
|---------------------------------------------------|
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix) |
| HAIM - Don't Save Me (Cyril Hahn Remix) |
| Miyagi & Эндшпиль ft. Рем Дигга - I Got Love |
Notice that the songs are being listed in random order, thanks to the random function
call used by the ORDER BY clause.
MySQL
On MySQL, you need to use the RAND function, as illustrated by the following example:
SELECT
CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY RAND()
When running the aforementioned SQL query on MySQL, we are going to get the following result
set:
| song |
|---------------------------------------------------|
| HAIM - Don't Save Me (Cyril Hahn Remix) |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix) |
| Miyagi & Эндшпиль ft. Рем Дигга - I Got Love |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love |
Notice that the songs are being listed in random order, thanks to the RAND function call
used by the ORDER BY clause.
Share Improve this answer Follow edited Jan 20, 2021 at 19:56 answered Jul 23, 2019 at 11:51
Vlad Mihalcea
150k 84 585 954
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 9/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
If you are using large table and want to access of 10 percent of the data then run this following
command: SELECT TOP 10 PERCENT * FROM Table1 ORDER BY NEWID();
1
Share Improve this answer Follow answered Feb 12, 2020 at 7:37
Palash Mondal
526 4 10
If you don't want to use NEWID() and the primary key column is int , then you can just select a
random primary key like this:
0
with a as
(
select count(id) as row_count
from mytable
)
select *
from mytable , a
where id = round(rand() * row_count, 0)
If you need just to shuffle sequential values then you don't need always to use random (as it's
non sql standard), you can try to use some tricks, like using reverse(PK)
0
SELECT PK FROM products ORDER BY REVERSE(concat('', PK))
So let's say we have a values: 123 124 125 223 224 225 323 324 325
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 10/11
6/12/24, 3:30 PM database - How to randomly select rows in SQL? - Stack Overflow
321 - 1
322 - 4
323 - 7
421 - 2
422 - 5
423 - 8
521 - 3
522 - 6
523 - 9
Share Improve this answer Follow answered Jul 20, 2023 at 14:55
Yura
1,783 1 20 19
https://stackoverflow.com/questions/580639/how-to-randomly-select-rows-in-sql 11/11