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
How to display 3 random values from MySQL table?
To display random values from a MySQL table, use the RAND() function in the ORDER BY clause to shuffle the rows randomly, and LIMIT to restrict the number of results. The general syntax is −
SELECT yourColumnName FROM yourTableName ORDER BY RAND() LIMIT 3;
Creating the Demo Table
Let us first create a table and insert some records −
CREATE TABLE DemoTable646 (
Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName VARCHAR(100)
);
INSERT INTO DemoTable646 (FirstName) VALUES ('John');
INSERT INTO DemoTable646 (FirstName) VALUES ('Bob');
INSERT INTO DemoTable646 (FirstName) VALUES ('Chris');
INSERT INTO DemoTable646 (FirstName) VALUES ('David');
INSERT INTO DemoTable646 (FirstName) VALUES ('Bob');
INSERT INTO DemoTable646 (FirstName) VALUES ('Carol');
INSERT INTO DemoTable646 (FirstName) VALUES ('Mike');
Display all records from the table using the SELECT statement −
SELECT * FROM DemoTable646;
This will produce the following output −
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Bob | | 3 | Chris | | 4 | David | | 5 | Bob | | 6 | Carol | | 7 | Mike | +----+-----------+ 7 rows in set (0.00 sec)
Displaying 3 Random Values
Following is the query to display 3 random values from the table −
SELECT FirstName FROM DemoTable646 ORDER BY RAND() LIMIT 3;
This will produce the following output (your results will vary since the selection is random) −
+-----------+ | FirstName | +-----------+ | Mike | | John | | Chris | +-----------+ 3 rows in set (0.00 sec)
RAND() generates a random floating-point value for each row. ORDER BY RAND() sorts all rows by these random values, and LIMIT 3 returns only the first 3 rows from the shuffled result. Change the LIMIT value to retrieve a different number of random rows.
Conclusion
Use ORDER BY RAND() LIMIT n to fetch n random rows from a MySQL table. Note that this approach scans the entire table, so it can be slow on very large tables.
