Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases

Why doesn't DISTINCT always behave the way you expect in SQL queries?

Why doesn't DISTINCT always work like expected? This was my answer to the Elective Teachers problem in SQL Reporting by Example:

-- Which teachers teach elective subjects (subjects without grade levels)?
SELECT DISTINCT TEACHERS.ID, FIRST_NAME, LAST_NAME, SUBJECTS.NAME FROM TEACHERS
JOIN CLASSES ON CLASSES.TEACHER_ID = TEACHERS.ID
JOIN SUBJECTS ON SUBJECTS.ID = CLASSES.SUBJECT_ID
WHERE GRADE IS NULL;

This was Ben's Solution:

-- Which teachers teach elective subjects (subjects without grade levels)?
SELECT DISTINCT TEACHERS.ID, FIRST_NAME, LAST_NAME FROM TEACHERS
JOIN CLASSES ON CLASSES.TEACHER_ID = TEACHERS.ID
JOIN SUBJECTS ON SUBJECTS.ID = CLASSES.SUBJECT_ID
WHERE GRADE IS NULL;

Ben's solution returns one row per elective teacher. Mine returns Janis Ambrose on two lines, one for each elective she teaches. Why didn't DISTINCT return the same results when I included SUBJECTS.NAME?

2 Answers

Steven Parker
Steven Parker
229,644 Points

The DISTINCT restriction applies to the total result set, so if you add an additional column that makes two rows different, then both will be considered "distinct" and pass through.

Thank you!