MySQL randomly select 2 values from column values?

MySQLMySQLi Database

To randomly select, use ORDER BY RAND(). To select only 2 values, use LIMIT 2 in MySQL. Let us first create a table −

mysql> create table DemoTable1815
     (
     Question text
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1815 values('What is your name?');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1815 values('What is your college name?');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1815 values('What is your nick name?');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1815 values('What is your enemy name?');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1815;

This will produce the following output −

+----------------------------+
| Question                   |
+----------------------------+
| What is your name?         |
| What is your college name? |
| What is your nick name?    |
| What is your enemy name?   |
+----------------------------+
4 rows in set (0.00 sec)

Here is the query to randomly select only 2 records −

mysql> select * from DemoTable1815 order by rand() limit 2;

This will produce the following output −

+----------------------------+
| Question                   |
+----------------------------+
| What is your college name? |
| What is your enemy name?   |
+----------------------------+
2 rows in set (0.00 sec)
raja
Published on 24-Dec-2019 10:51:23
Advertisements