Computer >> Computer tutorials >  >> Programming >> MySQL

Select two random rows in a MySQL database?


Use RAND() and LIMIT clause to select two random rows in a MySQL database −

select *from yourTableName order by rand() limit 2;

Let us first create a table −

mysql>create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientFirstName varchar(20)
);
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql>insert into DemoTable(ClientFirstName) values('Robert');
Query OK, 1 row affected (0.27 sec)
mysql>insert into DemoTable(ClientFirstName) values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql>insert into DemoTable(ClientFirstName) values('Jace');
Query OK, 1 row affected (0.16 sec)
mysql>insert into DemoTable(ClientFirstName) values('James');
Query OK, 1 row affected (0.32 sec)
mysql>insert into DemoTable(ClientFirstName) values('David');
Query OK, 1 row affected (0.32 sec)
mysql>insert into DemoTable(ClientFirstName) values('John');
Query OK, 1 row affected (0.18 sec)
mysql>insert into DemoTable(ClientFirstName) values('Mike');
Query OK, 1 row affected (0.14 sec)

Following is the query to display all records from the table using select statement −

mysql>select *from DemoTable;

This will produce the following output −

+----+-----------------+
| Id | ClientFirstName |
+----+-----------------+
| 1  | Robert          |
| 2  | Chris           |
| 3  | Jace            |
| 4  | James           |
| 5  | David           |
| 6  | John            |
| 7  | Mike            |
+----+-----------------+
7 rows in set (0.00 sec)

Following is the query to select two random rows in a MySQL database.

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

This will produce the following output −

+----+-----------------+
| Id | ClientFirstName |
+----+-----------------+
| 4  | James           |
| 2  | Chris           |
+----+-----------------+
2 rows in set (0.00 sec)