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 trialJ de la Torre
2,858 PointsDifference in speed/efficiency between CTEs, INTERSECT, WHERE clause solutions?
Is there a difference in efficiency or speed between using the two CTEs in the video or using an INTERSECT like:
SELECT students.id, students.first_name, students.last_name
FROM students JOIN schedule ON students.id = schedule.student_id
JOIN classes ON schedule.class_id = classes.id
JOIN subjects ON subjects.id = classes.subject_id
WHERE subjects.name = 'Science' AND classes.period_id = 5
INTERSECT
SELECT students.id, students.first_name, students.last_name
FROM students JOIN schedule ON students.id = schedule.student_id
JOIN classes ON schedule.class_id = classes.id
JOIN subjects ON subjects.id = classes.subject_id
WHERE subjects.name = 'Art' AND classes.period_id = 7
Is the difference just readability?
Also, is there any benefit to using CTEs or the above INTERSECT versus using the following WHERE clause?
SELECT students.first_name, students.last_name
FROM students JOIN schedule ON students.id = schedule.student_id
JOIN classes ON classes.id = schedule.class_id
JOIN subjects ON subjects.id = classes.subject_id
WHERE (subjects.name = 'Science' AND classes.period_id = 5)
OR
(subjects.name = 'Art' AND classes.period_id = 7)
GROUP BY students.id
HAVING COUNT(*) > 1;
1 Answer
Jennifer Nordell
Treehouse TeacherHi there, J de la Torre!
One thing that might not be immediately obvious is that INTERSECT
is meant to find distinct values that match between tables as opposed to the typical INNER JOIN
that does not. So there's a somewhat different goal with intersect than there is with inner join. The results might be the same because the data only already contains unique values in a column, but that may not be the case and you would receive different results between the two.
As of right now, I've never found a good performance rundown for the difference between these two and I feel like I'm unlikely to just because the goals are slightly different.
When using CTEs just keep in mind that it is possible to inadvertently create an infinite loop which leads to a max recursion error.
Hope this helps!