- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
How to select unique value in MySQL?
You can select unique value with the help of DISTINCT keyword.
The syntax is as follows
select distinct yourColumnName from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table selectUniqueValue -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20), -> Age int -> ); Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into selectUniqueValue(Name,Age) values('John',21); Query OK, 1 row affected (0.18 sec) mysql> insert into selectUniqueValue(Name,Age) values('Carol',21); Query OK, 1 row affected (0.13 sec) mysql> insert into selectUniqueValue(Name,Age) values('Sam',22); Query OK, 1 row affected (0.10 sec) mysql> insert into selectUniqueValue(Name,Age) values('Mike',22); Query OK, 1 row affected (0.16 sec) mysql> insert into selectUniqueValue(Name,Age) values('David',22); Query OK, 1 row affected (0.13 sec) mysql> insert into selectUniqueValue(Name,Age) values('Larry',23); Query OK, 1 row affected (0.12 sec) mysql> insert into selectUniqueValue(Name,Age) values('Bob',23); Query OK, 1 row affected (0.12 sec) mysql> insert into selectUniqueValue(Name,Age) values('Maxwell',22); Query OK, 1 row affected (0.19 sec) mysql> insert into selectUniqueValue(Name,Age) values('Robert',21); Query OK, 1 row affected (0.15 sec)
Now you can display all records from the table using select statement. The query is as follows −
mysql> select *from selectUniqueValue;
The following is the output
+----+---------+------+ | Id | Name | Age | +----+---------+------+ | 1 | John | 21 | | 2 | Carol | 21 | | 3 | Sam | 22 | | 4 | Mike | 22 | | 5 | David | 22 | | 6 | Larry | 23 | | 7 | Bob | 23 | | 8 | Maxwell | 22 | | 9 | Robert | 21 | +----+---------+------+ 9 rows in set (0.00 sec)
The following is the query to select unique value
mysql> select distinct Age from selectUniqueValue;
The following is the output
+------+ | Age | +------+ | 21 | | 22 | | 23 | +------+ 3 rows in set (0.00 sec)
Advertisements