Randomly SELECT distinct rows in a MySQL table?


To randomly select rows, use ORDER BY RAND() with LIMIT. Use DISTINCT for distinct rows. Let us first see an example and create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(40)
);
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Name) values('John Doe');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(Name) values('Chris Brown');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(Name) values('Adam Smith');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(Name) values('John Doe');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(Name) values('John Doe');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(Name) values('Chris Brown');
Query OK, 1 row affected (0.53 sec)
mysql> insert into DemoTable(Name) values('Adam Smith');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------------+
| Id | Name        |
+----+-------------+
|  1 | John Doe    |
|  2 | Chris Brown |
|  3 | Adam Smith  |
|  4 | John Doe    |
|  5 | John Doe    |
|  6 | Chris Brown |
|  7 | Adam Smith  |
+----+-------------+
7 rows in set (0.00 sec)

Following is the query to randomly select two distinct rows in a table −

mysql> select distinct Name from DemoTable order by rand() limit 3;

This will produce the following output −

+-------------+
| Name        |
+-------------+
| Chris Brown |
| John Doe    |
| Adam Smith  |
+-------------+
3 rows in set (0.00 sec)

Updated on: 09-Oct-2019

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements