

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to select a random record from a MySQL database?
For this, you can use ORDER BY RAND LIMIT. Let us first create a table −
mysql> create table DemoTable1581 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20) -> ); Query OK, 0 rows affected (1.34 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1581(StudentName) values('Chris'); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable1581(StudentName) values('Bob'); Query OK, 1 row affected (1.58 sec) mysql> insert into DemoTable1581(StudentName) values('Sam'); Query OK, 1 row affected (2.11 sec) mysql> insert into DemoTable1581(StudentName) values('Mike'); Query OK, 1 row affected (0.55 sec) mysql> insert into DemoTable1581(StudentName) values('Carol'); Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1581;
This will produce the following output −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Chris | | 2 | Bob | | 3 | Sam | | 4 | Mike | | 5 | Carol | +-----------+-------------+ 5 rows in set (0.00 sec)
Here is the query to select a random record from a MySQL database −
mysql> select * from DemoTable1581 order by rand() limit 1;
This will produce the following output −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 4 | Mike | +-----------+-------------+ 1 row in set (0.07 sec)
- Related Questions & Answers
- Select two random rows in a MySQL database?
- How do I select four random tables from a MySQL database having thousands of tables?
- How to select first 10 elements from a MySQL database?
- How to get a specific column record from SELECT query in MySQL?
- Select random number from a specific list in MySQL?
- Selecting random entry from MySQL Database?
- How to select a random element from a C# list?
- Select a random row in MySQL
- Select a fixed number of random records from a MySQL table?
- Get Random record from MongoDB?
- How to select record from last 6 months in a news table using MySQL?
- How to select a specific record from MySQL if date is in VARCHAR format?
- Get the last record from a table in MySQL database with Java?
- How to select record except the lower value record against a specific value in MySQL?
- MYSQL - select database?
Advertisements