To select a random row, use the rand() with LIMIT from MySQL. The syntax is as follows:
SELECT * FROM yourTableName ORDER BY RAND() LIMIT 1;
To understand the above syntax, let us create a table. The query to create a table is as follows:
mysql> create table generateRandomRow -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> Age int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.66 sec)
Insert some records in the table using insert command. The query is as follows:
mysql> insert into generateRandomRow(Name,Age) values('John',23); Query OK, 1 row affected (0.22 sec) mysql> insert into generateRandomRow(Name,Age) values('Larry',21); Query OK, 1 row affected (0.32 sec) mysql> insert into generateRandomRow(Name,Age) values('David',21); Query OK, 1 row affected (0.39 sec) mysql> insert into generateRandomRow(Name,Age) values('Carol',24); Query OK, 1 row affected (0.21 sec) mysql> insert into generateRandomRow(Name,Age) values('Bob',27); Query OK, 1 row affected (0.14 sec) mysql> insert into generateRandomRow(Name,Age) values('Mike',29); Query OK, 1 row affected (0.19 sec) mysql> insert into generateRandomRow(Name,Age) values('Sam',26); Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from generateRandomRow;
The following is the output:
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 1 | John | 23 | | 2 | Larry | 21 | | 3 | David | 21 | | 4 | Carol | 24 | | 5 | Bob | 27 | | 6 | Mike | 29 | | 7 | Sam | 26 | +----+-------+------+ 7 rows in set (0.00 sec)
Here is the query to select a random row from the table using rand(). The query is as follows:
mysql> select *from generateRandomRow order by rand() limit 1;
The output displays a random row:
+----+------+------+ | Id | Name | Age | +----+------+------+ | 5 | Bob | 27 | +----+------+------+ 1 row in set (0.00 sec)
Now when we will run the query again, the following random row would be visible:
mysql> select *from generateRandomRow order by rand() limit 1;
The following is the output:
+----+------+------+ | Id | Name | Age | +----+------+------+ | 6 | Mike | 29 | +----+------+------+ 1 row in set (0.00 sec)