Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Simple JOINs recap
Various kinds of JOINs
Filtering with LEFT JOIN and RIGHT JOIN
15. ON and WHERE conditions
Summary

Instruction

Great! There is one more caveat when using LEFT JOIN and its friends. There is a subtle difference between the conditions in the ON and WHERE clauses for these JOINs. The ON condition is evaluated when the tables are joined. The WHERE condition is applied after the rows have been joined. Take a look at this example:

SELECT
  course.name,
  lecturer.name
FROM course
LEFT JOIN lecturer
  ON course.lecturer_id = lecturer.id
WHERE lecturer.id = 3

The query will list all courses but only those that are taught by the lecturer with id = 3. Other courses will not have lecturer information listed, even if there is a lecturer assigned to them.

SELECT *
FROM subject
LEFT JOIN lecturer
  ON subject.lecturer_id = lecturer.id
  AND lecturer.id = 3

Note that for INNER JOINs conditions in the ON and WHERE clauses are effectively the same.

Exercise

Show the title of each book and the name of its author — but only if the author was born in the 20th century.

Otherwise, the author's name field should be NULL.

Stuck? Here's a hint!

Type:

SELECT
  book.title,
  author.name
FROM book
LEFT JOIN author
  ON book.author_id = author.id
  AND author.birth_year BETWEEN 1901 AND 2000