 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- 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 distinct value from one MySQL column only?
To select distinct value from one column only, you can use aggregate function MAX() along with GROUP BY. Let us first create a table −
mysql> create table distinctFromOneColumn -> ( -> StudentId int, -> StudentName varchar(100) -> ); Query OK, 0 rows affected (0.77 sec)
Following is the query to insert records in the table using insert command −
mysql> insert into distinctFromOneColumn values(1001,'John'); Query OK, 1 row affected (0.15 sec) mysql> insert into distinctFromOneColumn values(1002,'Carol'); Query OK, 1 row affected (0.15 sec) mysql> insert into distinctFromOneColumn values(1001,'Sam'); Query OK, 1 row affected (0.15 sec) mysql> insert into distinctFromOneColumn values(1001,'David'); Query OK, 1 row affected (0.16 sec) mysql> insert into distinctFromOneColumn values(1002,'Ramit'); Query OK, 1 row affected (0.15 sec) mysql> insert into distinctFromOneColumn values(1003,'Bob'); Query OK, 1 row affected (0.21 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from distinctFromOneColumn;
This will produce the following output −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1001 | John | | 1002 | Carol | | 1001 | Sam | | 1001 | David | | 1002 | Ramit | | 1003 | Bob | +-----------+-------------+ 6 rows in set (0.00 sec)
Here is the query to select a distinct value from one column only −
mysql> select StudentId,MAX(StudentName) AS StudentName -> from distinctFromOneColumn -> group by StudentId;
This will produce the following output −
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1001 | Sam | | 1002 | Ramit | | 1003 | Bob | +-----------+-------------+ 3 rows in set (0.00 sec)
Advertisements
 