Back to subject
MySQL/DISTINCT

Find Out What Values Actually Exist

Practical lesson

Let's read a DISTINCT query and see exactly how it collapses repeated values.

SELECT DISTINCT age FROM students; looks at the age column across every row, and returns each different value exactly once. Even if ten students happened to share age 16, this query would still show 16 only a single time.

Compare that to SELECT age FROM students;, without DISTINCT that would return one row per student, so a shared age value like 16 could appear many times in the result, once per matching student.

The two rows in the result (16 and 17) tell you something summary-level and useful: "across our whole students table, these are the only two ages currently represented" a very different kind of question than "list every student's age."

This distinction a full per-row listing versus a unique-values summary comes up constantly in real work, and DISTINCT is the simplest tool for the second kind of question.

Try it yourself
Code

Starter example

Code
SELECT DISTINCT age FROM students;
Live preview
+-----+
| age |
+-----+
| 16  |
| 17  |
+-----+
2 rows in set