Order randomly in MySQL with a random value column?


Let us first create a table. After that we will create a new random value column and order the record randomly:

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20)
);
Query OK, 0 rows affected (0.57 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable(StudentName) values('Larry');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentName) values('Sam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('Mike');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable;

This will produce the following output

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Larry       |
|         2 | Sam         |
|         3 | Mike        |
|         4 | Carol       |
|         5 | Robert      |
|         6 | Chris       |   
+-----------+-------------+
6 rows in set (0.00 sec)

Here is the query to order by random fields. We have created a new random field here:

mysql> SELECT *
FROM (SELECT StudentName, RAND()+1 AS randomRecord
FROM DemoTable
) tbl
ORDER BY RandomRecord DESC;

This will produce the following output

+-------------+--------------------+
| StudentName | RandomRecord       |
+-------------+--------------------+
| Carol       | 1.8973721451101566 |
| Chris       | 1.7821308670399065 |
| Mike        | 1.4640037673190271 |
| Larry       | 1.4134691557041081 |
| Sam         | 1.1408822407395414 |
| Robert      | 1.0948494543273461 |
+-------------+--------------------+
6 rows in set (0.00 sec)

Updated on: 30-Jul-2019

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements