MySQL random rows sorted by a specific column name?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1339
   -> (
   -> Name varchar(30),
   -> Score int
   -> );
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1339 values('Chris',56);
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable1339 values('Bob',46);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1339 values('Adam',78);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1339 values('John',90);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1339 values('Carol',98);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1339;

This will produce the following output −

+-------+-------+
| Name  | Score |
+-------+-------+
| Chris |    56 |
| Bob   |    46 |
| Adam  |    78 |
| John  |    90 |
| Carol |    98 |
+-------+-------+
5 rows in set (0.00 sec)

Following is the query to sort random rows by NAME column −

mysql> select * from (select *from DemoTable1339 order by rand() limit 4) tbl order by Name;

This will produce the following output −

+-------+-------+
| Name  | Score |
+-------+-------+
| Adam  |    78 |
| Bob   |    46 |
| Carol |    98 |
| Chris |    56 |
+-------+-------+
4 rows in set (0.05 sec)
raja
Published on 05-Nov-2019 11:47:29
Advertisements