Selecting random entry from MySQL Database?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientName varchar(100),
   ClientAge int
);
Query OK, 0 rows affected (0.92 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(ClientName,ClientAge) values('Robert',45);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(ClientName,ClientAge) values('Mike',55);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(ClientName,ClientAge) values('Bob',42);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(ClientName,ClientAge) values('Sam',47);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+------------+-----------+
| Id | ClientName | ClientAge |
+----+------------+-----------+
|  1 | Robert     |        45 |
|  2 | Mike       |        55 |
|  3 | Bob        |        42 |
|  4 | Sam        |        47 |
+----+------------+-----------+
4 rows in set (0.00 sec)

Following is the query to select a random entry from MySQL database −

mysql> select *from DemoTable order by rand() limit 1;

This will produce the following output −

+----+------------+-----------+
| Id | ClientName | ClientAge |
+----+------------+-----------+
|  3 | Bob        |        42 |
+----+------------+-----------+
1 row in set (0.00 sec)
raja
Published on 25-Sep-2019 10:33:28
Advertisements