Fetch random rows from a table with MySQL

MySQLMySQLi Database

For this, you can use a PREPARE statement. Let us first create a table −

mysql> create table DemoTable(
   FirstName varchar(100),
   CountryName varchar(100)
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Adam','US');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Chris','AUS');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Robert','UK');
Query OK, 1 row affected (0.32 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+
| FirstName | CountryName |
+-----------+-------------+
| Adam      | US          |
| Chris     | AUS         |
| Robert    | UK          | 
+-----------+-------------+
3 rows in set (0.00 sec)

Following is the query to fetch random rows in a single query −

mysql> set @value := ROUND((select count(*) from DemoTable) * rand());
Query OK, 0 rows affected (0.00 sec)
mysql> set @query := CONCAT('select *from DemoTable LIMIT ', @value , ', 1');
Query OK, 0 rows affected (0.00 sec)
mysql> prepare myStatement from @query ;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute myStatement;
+-----------+-------------+
| FirstName | CountryName |
+-----------+-------------+
| Chris     | AUS         |
+-----------+-------------+
1 row in set (0.00 sec)
mysql> deallocate prepare myStatement;
Query OK, 0 rows affected (0.00 sec)
raja
Published on 27-Sep-2019 11:16:32
Advertisements