Syntax error How to fetch random rows in MySQL with comma separated values?

How to fetch random rows in MySQL with comma separated values?



To fetch random rows in MySQL, use ORDER BY RAND(). Let us first create a table −

mysql> create table DemoTable1835
     (
     ListOfIds varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1835 values('10,20,30');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1835 values('70,80,90');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1835 values('45,67,89');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1835 values('98,96,49');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1835;

This will produce the following output −

+-----------+
| ListOfIds |
+-----------+
| 10,20,30  |
| 70,80,90  |
| 45,67,89  |
| 98,96,49  |
+-----------+
4 rows in set (0.00 sec)

Here is the query to fetch random rows in MySQL

mysql> select * from DemoTable1835
     where ListOfIds NOT IN(10,20,70) order by rand()
     limit 2;

This will produce the following output −

+-----------+
| ListOfIds |
+-----------+
| 98,96,49  |
| 45,67,89  |
+-----------+
2 rows in set, 4 warnings (0.00 sec)
Updated on: 2019-12-24T07:51:07+05:30

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements