
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
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 Articles
- 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?
- How do I select 5 random rows from the 20 most recent rows in MySQL?
- Select two random rows in a MySQL database?
- What is the most efficient way to deep clone an object in JavaScript?
- How select specific rows in MySQL?
- What is the most efficient way to concatenate many Python strings together?
- Select specific rows in a range with MySQL?
- In MongoDB, what is the most efficient way to get the first and last document?
- What is the fastest way to insert a large number of rows into a MySQL table?
- How to order results of a query randomly & select random rows in MySQL?
- MySQL random rows sorted by a specific column name?
- Easiest way to get number of rows in a MySQL table?
- What's the most efficient way to pull data from MySQL so that it is formatted with duplicate values
- Fastest way to count number of rows in MySQL table?

Advertisements