To display a single random row, use the RAND() with LIMIT. Here, LIMIT is used to fetch the number of records, since we want only a single row, therefore use LIMIT 1. Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(50), Quote text ); Query OK, 0 rows affected (0.71 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name,Quote) values('Chris','MySQL is a relational database'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Name,Quote) values('Robert','Java is an Object Oriented Programming Language'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(Name,Quote) values('Mike','C is a Procedural Language'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(Name,Quote) values('David','Hibernate and spring is a framework'); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+-------------------------------------------------+ | Id | Name | Quote | +----+--------+-------------------------------------------------+ | 1 | Chris | MySQL is a relational database | | 2 | Robert | Java is an Object Oriented Programming Language | | 3 | Mike | C is a Procedural Language | | 4 | David | Hibernate and spring is a framework | +----+--------+-------------------------------------------------+ 4 rows in set (0.00 sec)
Following is the query to display a random from a MySQL table −
mysql> select Id,Name,Quote from DemoTable order by rand() limit 1;
This will produce the following output −
+----+------+----------------------------+ | Id | Name | Quote | +----+------+----------------------------+ | 3 | Mike | C is a Procedural Language | +----+------+----------------------------+ 1 row in set (0.00 sec)