

- 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
What is the most efficient way to select a specific number of random rows in MySQL?
Use RAND() method for random and to limit a number of records, use the LIMIT() method in MySQL.
Let us first create a table −
mysql> create table DemoTable -> ( -> Value int -> ); Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(300); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(600); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(700); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(1000); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+-------+ | Value | +-------+ | 100 | | 300 | | 600 | | 700 | | 1000 | +-------+ 5 rows in set (0.00 sec)
Following is the query to get a specific number of rows with random records −
mysql> select *from DemoTable order by rand() limit 4;
Output
+-------+ | Value | +-------+ | 1000 | | 600 | | 100 | | 700 | +-------+ 4 rows in set (0.00 sec)
- Related Questions & Answers
- What is the most efficient way to check the presence of a row in a MySQL table?
- Select random number from a specific list in MySQL?
- What is the most efficient way to deep clone an object in JavaScript?
- How do I select 5 random rows from the 20 most recent rows in MySQL?
- In MongoDB, what is the most efficient way to get the first and last document?
- Select two random rows in a MySQL database?
- What is the fastest way to insert a large number of rows into a MySQL table?
- How select specific rows in MySQL?
- Select specific rows in a range with MySQL?
- What's the most efficient way to pull data from MySQL so that it is formatted with duplicate values
- MySQL random rows sorted by a specific column name?
- Easiest way to get number of rows in a MySQL table?
- What is the most efficient string concatenation method in python?
- Fastest way to count number of rows in MySQL table?
- What's the most efficient way to turn all the keys of an object to lower case - JavaScript?
Advertisements