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 SQL Reporting by Example Day 1: Joining Tables Elective Teachers

Greg Kaleka
Greg Kaleka
39,021 Points

Even More Subqueries!

You can get a slightly cleaner table by wrapping the full query as a subquery of another simpler query:

SELECT FIRST_NAME, LAST_NAME FROM TEACHERS WHERE ID IN (
  SELECT DISTINCT TEACHERS.ID FROM SUBJECTS
  JOIN CLASSES ON SUBJECTS.ID = CLASSES.SUBJECT_ID
  JOIN TEACHERS ON CLASSES.TEACHER_ID = TEACHERS.ID
  WHERE GRADE IS NULL
);

The advantage of this is you get a table that doesn't include the ID field from the TEACHERS table.

Yes, thats much cleaner! Thanks Greg!!!

Ryan Dainton
Ryan Dainton
17,164 Points
SELECT FIRST_NAME, LAST_NAME
FROM TEACHERS
WHERE ID IN 
  (SELECT TEACHER_ID FROM CLASSES WHERE SUBJECT_ID IN 
    (SELECT ID FROM SUBJECTS WHERE GRADE IS NULL));

This also works for maximum subqueries!!

2 Answers

If having the ID column is not desired, why not use GROUP BY instead of a sub-query, like this:

SELECT FIRST_NAME, LAST_NAME FROM TEACHERS
JOIN CLASSES ON CLASSES.TEACHER_ID = TEACHERS.ID
JOIN SUBJECTS ON SUBJECTS.ID = CLASSES.SUBJECT_ID
WHERE SUBJECTS.GRADE IS NULL
GROUP BY TEACHERS.ID;

That's excellent, Greg!

I came up with this query, which was definitely inspired by your previous subquery posts:

SELECT * FROM TEACHERS WHERE ID IN (
  SELECT TEACHER_ID FROM CLASSES WHERE SUBJECT_ID IN (
    SELECT ID FROM SUBJECTS WHERE GRADE IS NULL
  )
)