Today we have a quickie for SQL jockies working in MS Access land: how to select a result set of random records.
Disclaimer
The meaning of the word quickie in this article is two-fold. First, this is a small article — a quick tip. Second, this is not mean to be used for large or frequently-called queries. ORDER BY RAND() is very inefficient. The table I am working with contains only a few hundred records, and I need to generate the result set just once.
How not to do it
Thinking in MySQL terms, my first instinct was to use the following query to produce a small result set of random records.
SELECT * FROM [MyTable] ORDER BY RAND() LIMIT n
This does not work in Microsoft Access — instead, you need to call the Rnd function.
Querying Random Records in MS Access
The following query is what I chose in order to generate a small, one-time result set of random records. It uses the primary key column ID as a seed.
SELECT TOP n * FROM [MyTable] ORDER BY Rnd([ID])
Note: in both of these queries, n is the maximum number of records I wish to include in the result set.





3 responses
April 28th, 2008
Syed Z Haider says:
Simply useless and misleading and cannot be used for any practical purpose.
April 28th, 2008
Of Zen and Computing says:
On the contrary, nearly everything I write comes from first-hand experience, and I got the inspiration for this article from practical task I was asked to take care of. Don’t assume.
April 28th, 2008
Futurama says:
Of course ! nothing is useless syed, I just googled for some way to get 10k random records from my access DB now and here I am and its funny to read your comment that it is useless!
Leave a Comment