- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL query to select a random row value (Id and Name) having multiple occurrences (Name)?
For this, use RAND() for random records and LIMIT 1 to get only a single value. However, use the WHERE clause to select that particular ‘Name’, which is repeating.
Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Name varchar(20) ); Query OK, 0 rows affected (1.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('Chris'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(Name) values('Bob'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Name) values('David'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable(Name) values('Bob'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(Name) values('Bob'); Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+-------+ | Id | Name | +----+-------+ | 1 | Chris | | 2 | Bob | | 3 | David | | 4 | Bob | | 5 | Bob | +----+-------+ 5 rows in set (0.65 sec)
Following is the query to fetch a random value −
mysql> select *from DemoTable where Name='Bob' order by rand() limit 1;
This will produce the following output −
+----+------+ | Id | Name | +----+------+ | 5 | Bob | +----+------+ 1 row in set (0.00 sec)
- Related Articles
- MySQL query to select one specific row and another random row?
- MySQL query to select the values having multiple occurrence and display their count
- Select a random row in MySQL
- MySQL query to fecth the domain name from email-id?
- How to retrieve a random row or multiple random rows in MySQL?
- MySQL query to select distinct order by id
- MySQL query to select maximum and minimum salary row?
- How to select row when column must satisfy multiple value in MySQL?
- MySQL query to sum rows having repeated corresponding Id
- MySQL query to select records beginning from a specific id
- How to select from table where conditions are set for id and name in MySQL?
- Select the table name as a column in a UNION select query with MySQL?
- MySQL query to select multiple rows effectively?
- Select random row that exists in a MySQL table?
- MySQL query to get the highest value from a single row with multiple columns

Advertisements