Monday, 26 December 2011

SQL Joins


The SQL JOIN refers to using the JOIN keyword in a SQL statement in order to query data from two tables.

When you perform a SQL join, you specify one column from each table to join on. These two columns contain data that is shared across both tables.

Join Types

Depending on your requirements, you can do an "inner" join or an "outer" join. These are different in a subtle way
  • INNER JOIN (or JOIN) : This will only return rows when there is at least one row in both tables that match the join condition.
  • LEFT OUTER JOIN (or LEFT JOIN): This will return rows that have data in the left table (left of the JOIN keyword), even if there's no matching rows in the right table.
  • RIGHT OUTER JOIN (or RIGHT JOIN): This will return rows that have data in the right table (right of the JOIN keyword), even if there's no matching rows in the left table.
  • FULL OUTER JOIN (or FULL JOIN): This will return all rows, as long as there's matching data in one of the tables.
Syntax:

SELECT * FROM table_name1 Join_Name(INNER JOIN,LEFT JOIN,RIGHT JOIN,FULL JOIN) table_name2 ON table_name1.column_name = table_name2.column_name

Examples:

Source Tables


Left Table(Individual)
IdFirstNameLastNameUserName
1FredFlinstonefreddo
2HomerSimpsonhomey
3HomerBrownnotsofamous
4OzzyOzzbournesabbath
5HomerGainnoplacelike


Right Table(Publisher)
IndividualIdAccessLevel
1Administrator
2Contributor
3Contributor
4Contributor
10Administrator

1) Inner Join

SELECT * FROM Individual
INNER JOIN Publisher
ON Individual.IndividualId = Publisher.IndividualId
WHERE Individual.IndividualId = '2'

Result
IndividualId|FirstName|LastName|UserName|IndividualId|AccessLevel
2HomerSimpsonhomey2Contributor
2) Outer Join

     a)Left Outer Join
           
            SELECT * FROM Individual AS Ind
     LEFT JOIN Publisher AS Pub
     ON Ind.IndividualId = Pub.IndividualId

Result

IndividualId|FirstName|LastName|UserName|IndividualId|AccessLevel
1FredFlinstonefreddo1Administrator
2HomerSimpsonhomey2Contributor
3HomerBrownnotsofamous3Contributor
4OzzyOsbournesabbath4Contributor
5HomerGainnoplacelikeNULLNULL
   b)Right Outer Join
    SELECT * FROM Individual AS Ind
    RIGHT JOIN Publisher AS Pub 
    ON Ind.IndividualId = Pub.IndividualId

Result
IndividualId|FirstName|LastName|UserName|IndividualId|AccessLevel
1FredFlinstonefreddo1Administrator
2HomerSimpsonhomey2Contributor
3HomerBrownnotsofamous3Contributor
4OzzyOsbournesabbath4Contributor
NULLNULLNULLNULL10Administrator
3)Full Outer Join
SELECT * FROM Individual AS Ind
FULL JOIN Publisher AS Pub
ON Ind.IndividualId = Pub.IndividualId

Result

IndividualId|FirstName|LastName|UserName|IndividualId|AccessLevel
1FredFlinstonefreddo1Administrator
2HomerSimpsonhomey2Contributor
3HomerBrownnotsofamous3Contributor
4OzzyOsbournesabbath4Contributor
5HomerGainnoplacelikeNULLNULL
NULLNULLNULLNULL10Administrator

No comments:

Post a Comment