Joining multiple tables in SQL

Can sombody Explains me about joins?

Inner join selects common data based on where condition.

Left outer join selects all data from left irrespective of common but takes common data from right table and vice versa for Right outer.

I know the basics but question stays when it comes to join for than 5, 8, 10 tables.

Suppose I have 10 tables to join. If I have inner join with the first 5 tables and now try to apply a left join with the 6th table, now how the query will work?

I mean to say now the result set of first 5 tables will be taken as left table and the 6th one will be considerded as Right table? Or only Fifth table will be considered as left and 6th as right? Please help me regarding this.


When joining multiple tables the output of each join logically forms a virtual table that goes into the next join.

So in the example in your question the composite result of joining the first 5 tables would be treated as the left hand table.

See Itzik Ben-Gan's Logical Query Processing Poster for more about this.

The virtual tables involved in the joins can be controlled by positioning the ON clause. For example

SELECT *
FROM   T1
       INNER JOIN T2
         ON T2.C = T1.C
       INNER JOIN T3
                  LEFT JOIN T4
                    ON T4.C = T3.C
         ON T3.C = T2.C 

is equivalent to (T1 Inner Join T2) Inner Join (T3 Left Join T4)


It's helpful to think of JOIN's in sequence, so the former is correct.

SELECT *
  FROM a
  INNER JOIN b ON b.a = a.id
  INNER JOIN c ON c.b = b.id
  LEFT JOIN d ON d.c = c.id
  LEFT JOIN e ON e.d = d.id

Would be all the fields from a and b and c where all the ON criteria match, plus the values from d where its criteria match plus all the contents of e where all its criteria match.

I know RIGHT JOIN is perfectly acceptable, but I've found in my experience that it's unnecessary - I almost always just join things from left to right.


> Simple INNER JOIN VIEW code...

CREATE VIEW room_view
AS SELECT a.*,b.*
FROM j4_booking a INNER JOIN j4_scheduling b
on a.room_id = b.room_id;