MySQL DISTINCT

A column often has the same value in many rows. SELECT DISTINCT returns each value only once.

SELECT city FROM students;
Without DISTINCT: six rows
city
Delhi
Mumbai
Pune
Jaipur
Delhi
Mumbai

SELECT DISTINCT city FROM students;
With DISTINCT: four unique cities
city
Delhi
Mumbai
Pune
Jaipur


Count unique values

SELECT COUNT(DISTINCT city) AS cities FROM students;
Result
cities
4


DISTINCT with more columns

With more than one column, DISTINCT looks at the combination.

SELECT DISTINCT city, course_id FROM students ORDER BY city;
Result
city course_id
Delhi NULL
Delhi 1
Jaipur 3
Mumbai 2
Pune 1

Delhi appears twice because the two Delhi students have different course values (1 and NULL). Both Mumbai students have course 2, so Mumbai appears once.


Summary

  • SELECT DISTINCT column removes duplicates.
  • COUNT(DISTINCT column) counts the unique values.
  • Next: LIKE and wildcards.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.