Inner Vs Outer

An inner join of A and B gives the result of A intersect B, i.e. the inner part of a venn diagram intersection

An outer join of A and B gives the results of A union B, i.e. the outer parts of a venn diagram union

Examples

Suppose you have two Tables, with a single column each, and data as follows:

A B - -1 32 43 54 6

Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.

Inner join

An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.

select * from a INNER JOIN b on a.a = b.b;select a.*,b.* from a,b where a.a = b.b; a | b --+--3 | 34 | 4

Left outer join

A left outer join will give all rows in A, plus any common rows in B.

select * from a LEFT OUTER JOIN b on a.a = b.b;select a.*,b.* from a,b where a.a = b.b(+); a | b --+-----1 | null2 | null3 | 34 | 4

Full outer join

A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.

select * from a FULL OUTER JOIN b on a.a = b.b; a | b -----+----- 1 | null 2 | null 3 | 3 4 | 4null | 6null | 5

Diagram:

Another Example:

Lets say you have 100 students, 70 of which have lockers. You have a total of 50 lockers, 40 of which have at least 1 student.

INNER JOIN is equivalent to "show me all students with lockers".

Any students without lockers, or any lockers without students are missing.Returns 70 rows

LEFT OUTER JOIN would be "show me all students, with their corresponding locker if they have one".

This might be a general student list, or could be used to identify students with no locker. Returns 100 rows

RIGHT OUTER JOIN would be "show me all lockers, and the students assigned to them if there are any".

This could be used to identify lockers that have no students assigned, or lockers that have too many students. Returns 80 rows (list of 70 students in the 40 lockers, plus the 10 lockers with no student)

FULL OUTER JOIN would be silly and probably not much use.

Something like "show me all students and all lockers, and match them up where you can" Returns 110 rows (all 100 students, including those without lockers. Plus the 10 lockers with no student)

CROSS JOIN is also fairly silly in this scenario.

It doesn't use the linked "lockernumber" field in the students table, so you basically end up with a big giant list of every possible student-to-locker pairing, whether or not it actually exists.Returns 5000 rows (100 students x 50 lockers). Could be useful (with filtering) as a starting point to match up the new students with the empty lockers.

Reference

  1. http://stackoverflow.com/questions/38549/difference-between-inner-and-outer-join?rq=1

  2. http://stackoverflow.com/questions/448023/what-is-the-difference-between-left-right-outer-and-inner-joins?rq=1