Tuesday, 27 May 2014

SQL Joins


--INNER JOIN: Returns all rows when there is at least one match in BOTH tables
--LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
--RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
--FULL JOIN: Return all rows when there is a match in ONE of the tables

SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       INNER JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB


SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       LEFT JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB

SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       RIGHT JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB

SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       FULL JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB


SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       LEFT JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB
WHERE
              A.ColumnA IS NULL

SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       RIGHT JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB
WHERE
              A.ColumnA IS NULL

SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       LEFT JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB
WHERE
              B.ColumnB IS NULL

SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       RIGHT JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB
WHERE
              B.ColumnB IS NULL

SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       FULL OUTER JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB

SELECT
       COUNT (*)
FROM
       [DataBase].dbo.TableA A
       FULL OUTER JOIN [DataBase].dbo.TableB B ON A.ColumnA = B.ColumnB
WHERE
               A.ColumnA IS NULL
OR
              B.ColumnB IS NULL

1 comment:

  1. How about the equivalents using

    EXCEPT, INTERSECT and UNION

    ReplyDelete