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
Write a query to get data of selected columns from a table
Write a query to select the student with the maximum marks
Write a query to select top 3 students by marks
Write a query to select the rows if a column has no value
Write a query to find the names of students that begin with ‘A’
Write a query to fetch the top 2 records
Interview Questions & Answers
How to select Top 10 records in MySQL?
Write a MySQL query to select students with less than 50% marks
Write a MySQL query to select students with marks between 70 and 80
Write a query to fetch top N records
Write a query to find the names of employees that begin with ‘S’
Write a query to select if column has no/empty value
What is NULL in MySQL? Is NULL the same as 0 or an empty string?