CODING ACADEMY

View Original

How to Select a Random Record from a Database

I have just been working on a new course and needed to select a random record from a database table. I thought it would be useful to write this tutorial for anyone who was wondering how this can be achieved.

The actual code is really straightforward and uses the RAND() function as follows:

See this content in the original post

Lines 1 & 2: we are selecting all fields from the table

Lines 3 & 4: we specify the table from which we wish to retrieve the data

Lines 5 & 6: we specify that we want a random ordering of records

Line 7: we limit the returned data set to 1 record

It’s as easy as that!