Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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)
Advertisements
