Shuffling column values with MySQL?


To shuffle elements, you need to use ORDER BY RAND(). Let us first create a table −

mysql> create table DemoTable1557
   -> (
   -> SubjectId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> SubjectName varchar(20)
   -> );
Query OK, 0 rows affected (0.91 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1557(SubjectName) values('MySQL');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1557(SubjectName) values('MongoDB');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1557(SubjectName) values('Java');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1557(SubjectName) values('C');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select −

mysql> select * from DemoTable1557;

This will produce the following output −

+-----------+-------------+
| SubjectId | SubjectName |
+-----------+-------------+
|         1 | MySQL       |
|         2 | MongoDB     |
|         3 | Java        |
|         4 | C           |
+-----------+-------------+
4 rows in set (0.00 sec)

Following is the query to shuffle records with MySQL −

mysql> select * from DemoTable1557 order by rand();

This will produce the following output −

+-----------+-------------+
| SubjectId | SubjectName |
+-----------+-------------+
|         1 | MySQL       |
|         3 | Java        |
|         2 | MongoDB     |
|         4 | C           |
+-----------+-------------+
4 rows in set (0.00 sec)

Updated on: 12-Dec-2019

615 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements