Inner Join vs Outer Join: Rows Kept, NULLs and SQL Syntax
A join combines rows of two tables under the condition given in ON (most often that a foreign key equals a primary key) to produce one result table. An inner join keeps only the combinations of rows that have a matching partner; rows without a partner disappear from both tables. An outer join keeps the matching combinations and also keeps the rows of the specified table even when they have no partner, filling the other table's columns with NULL. A left outer join (LEFT OUTER JOIN) keeps every row of the left table, a right outer join (RIGHT OUTER JOIN) keeps the right table, and a full outer join (FULL OUTER JOIN) keeps both. Choose by whether rows without a partner should appear in the result.
| Aspect | Inner join (INNER JOIN) | Outer join (OUTER JOIN) |
|---|---|---|
| Rows kept in the result | Only combinations of rows that meet the join condition | Matching combinations, plus rows of the table chosen to be kept that have no matching partner |
| Unmatched rows | Removed from the result, from both tables | Rows of the kept table remain as one row each, with the other table's columns set to NULL; unmatched rows of the other table are removed |
| Kinds | One kind; INNER can be omitted and written simply as JOIN | Three kinds: left (LEFT), right (RIGHT) and full (FULL); OUTER can be omitted |
| Example SQL | SELECT … FROM employee INNER JOIN dept ON employee.dept_id = dept.dept_id | SELECT … FROM employee LEFT OUTER JOIN dept ON employee.dept_id = dept.dept_id |
| Example row count (4 employees, one with a NULL department ID; 3 departments, one with no employees) | 3 rows: the employee with a NULL department ID and the department with no employees do not appear | 4 rows with a left outer join that keeps the employee table (the employee with a NULL department ID gets a NULL department name); 5 rows with a full outer join that keeps both |
| Order of the tables | Swapping left and right gives the same rows (only the column order changes) | For left and right outer joins, which table is written on the left changes the result; A LEFT OUTER JOIN B returns the same rows as B RIGHT OUTER JOIN A |
| Conditions on the other table's columns | Same result whether written in ON or in the WHERE clause | Written in the WHERE clause, the NULL-filled rows fail the condition and disappear, which can give the same result as an inner join; write it in ON to keep unmatched rows |
| Typical uses | When only data present in both tables is wanted (for example, adding customer names to orders) | When unmatched rows should also be listed (for example, listing all employees including those with no department), or when looking for rows without a partner |
Figures are typical orders of magnitude and vary by process generation and product.