JournalSQLJoins2 min

WHERE vs. ON clause

Does not matter for inner joins. Matters for outer joins.

  • WHERE clause
  • ON clause
  • inner join
  • outer join
  • Does not matter for inner joins, for more info about ON clause in INNER JOIN vs. WHERE clause check my post
  • Matters for outer joins
  • WHERE clause: After joining. Records will be filtered after join has taken place.
  • ON clause - Before joining. Records (from right table) will be filtered before joining. This may end up as null in the result (since OUTER join).

Example: Consider the below tables:

    1. documents:
     | id    | name        |
     --------|-------------|
     | 1     | Document1   |
     | 2     | Document2   |
     | 3     | Document3   |
     | 4     | Document4   |
     | 5     | Document5   |
    

    2. downloads:
     | id   | document_id   | username |
     |------|---------------|----------|
     | 1    | 1             | sandeep  |
     | 2    | 1             | simi     |
     | 3    | 2             | sandeep  |
     | 4    | 2             | reya     |
     | 5    | 3             | simi     |

a) Inside WHERE clause:

SELECT documents.name, downloads.id
  FROM documents
  LEFT OUTER JOIN downloads
    ON documents.id = downloads.document_id
  WHERE username = 'sandeep'

For above query the intermediate join table will look like this.

id(from documents)nameid (from downloads)document_idusername
1Document111sandeep
1Document121simi
2Document232sandeep
2Document242reya
3Document353simi
4Document4NULLNULLNULL
5Document5NULLNULLNULL

After applying the WHERE clause and selecting the listed attributes, the result will be:

nameid
Document11
Document23

b) Inside JOIN clause

SELECT documents.name, downloads.id
FROM documents
  LEFT OUTER JOIN downloads
    ON documents.id = downloads.document_id
      AND username = 'sandeep'

For above query the intermediate join table will look like this.

id(from documents)nameid (from downloads)document_idusername
1Document111sandeep
2Document232sandeep
3Document3NULLNULLNULL
4Document4NULLNULLNULL
5Document5NULLNULLNULL

Notice how the rows in documents that did not match both the conditions are populated with NULL values.

After Selecting the listed attributes, the result will be:

nameid
Document11
Document23
Document3NULL
Document4NULL
Document5NULL

Recap

  • When we add a WHERE clause with an outer join, it behaves like an inner join, where the filter is applied after the ON clause, showing only those rows matching WHERE condition.
  • When filtering data with an outer join only those rows are shown which match the condition of ON clause. Otherwise, it is shown as NULL.
  • When filtering data with a left outer join. The [ON] clause can be useful when we need to return all the rows from the left table and only those rows from the right table which match the condition of the ON clause.

References: