SQL SERVER – Introduction to JOINs – Basic of JOINs

The launch of Gandhinagar SQL Server User Group was a tremendous, astonishing success! It was overwhelming to see a large gathering of enthusiasts looking up to me (I was the Key Speaker) eager to enhance their knowledge and participate in some brainstorming discussions. Some members of User Group had requested me to write a simple article on JOINS elucidating its different types.

INNER JOIN

This join returns rows when there is at least one match in both the tables.
SQL SERVER - Introduction to JOINs - Basic of JOINs inner join

OUTER JOIN

There are three different Outer Join methods.

LEFT OUTER JOIN
This join returns all the rows from the left table in conjunction with the matching rows from the right table. If there are no columns matching in the right table, it returns NULL values.
SQL SERVER - Introduction to JOINs - Basic of JOINs left join

RIGHT OUTER JOIN
This join returns all the rows from the right table in conjunction with the matching rows from the left table. If there are no columns matching in the left table, it returns NULL values.
SQL SERVER - Introduction to JOINs - Basic of JOINs right join

FULL OUTER JOIN
This join combines left outer join and right outer join. It returns row from either table when the conditions are met and returns null value when there is no match.
SQL SERVER - Introduction to JOINs - Basic of JOINs outer join

CROSS JOIN

This join is a Cartesian join that does not necessitate any condition to join. The resultset contains records that are multiplication of record number from both the tables.

SQL SERVER - Introduction to JOINs - Basic of JOINs cross join - half

Additional Notes related to JOIN:

The following are three classic examples to display where Outer Join is useful. You will notice several instances where developers write query as given below.

SELECT t1.*
FROM Table1 t1
WHERE t1.ID NOT IN (SELECT t2.ID FROM Table2 t2)
GO

The query demonstrated above can be easily replaced by Outer Join. Indeed, replacing it by Outer Join is the best practice. The query that gives same result as above is displayed here using Outer Join and WHERE clause in join.

/* LEFT JOIN - WHERE NULL */
SELECT t1.*,t2.*
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL

SQL SERVER - Introduction to JOINs - Basic of JOINs left join null

The above example can also be created using Right Outer Join.

SQL SERVER - Introduction to JOINs - Basic of JOINs right join null

NOT INNER JOIN
Remember, the term Not Inner Join does not exist in database terminology. However, when full Outer Join is used along with WHERE condition, as explained in the above two examples, it will give you exclusive result to Inner Join. This join will give all the results that were not present in Inner Join.

SQL SERVER - Introduction to JOINs - Basic of JOINs outer join null

You can download the complete SQL Script here, but for the sake of complicity I am including the same script here.

USE AdventureWorks
GO
CREATE TABLE table1
(ID INT, Value VARCHAR(10))
INSERT INTO Table1 (ID, Value)
SELECT 1,'First'
UNION ALL
SELECT 2,'Second'
UNION ALL
SELECT 3,'Third'
UNION ALL
SELECT 4,'Fourth'
UNION ALL
SELECT 5,'Fifth'
GO
CREATE TABLE table2
(ID INT, Value VARCHAR(10))
INSERT INTO Table2 (ID, Value)
SELECT 1,'First'
UNION ALL
SELECT 2,'Second'
UNION ALL
SELECT 3,'Third'
UNION ALL
SELECT 6,'Sixth'
UNION ALL
SELECT 7,'Seventh'
UNION ALL
SELECT 8,'Eighth'
GO
SELECT *
FROM Table1
SELECT *
FROM Table2
GO
USE AdventureWorks
GO
/* INNER JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.ID = t2.ID
GO
/* LEFT JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
GO
/* RIGHT JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
RIGHT JOIN Table2 t2 ON t1.ID = t2.ID
GO
/* OUTER JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
FULL OUTER JOIN Table2 t2 ON t1.ID = t2.ID
GO
/* LEFT JOIN - WHERE NULL */
SELECT t1.*,t2.*
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL
GO
/* RIGHT JOIN - WHERE NULL */
SELECT t1.*,t2.*
FROM Table1 t1
RIGHT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t1.ID IS NULL
GO
/* OUTER JOIN - WHERE NULL */
SELECT t1.*,t2.*
FROM Table1 t1
FULL OUTER JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t1.ID IS NULL OR t2.ID IS NULL
GO
/* CROSS JOIN */
SELECT t1.*,t2.*
FROM Table1 t1
CROSS JOIN Table2 t2
GO
DROP TABLE table1
DROP TABLE table2
GO

I hope this article fulfills its purpose. I would like to have feedback from my blog readers. Please suggest me where do you all want me to take this article next.

Reference : Pinal Dave (https://blog.sqlauthority.com)

Best Practices, Database, SQL Joins, SQL Scripts, SQL User Group
Previous Post
SQL SERVER – FIX : ERROR : The SQL Server System Configuration Checker cannot be executed due to WMI configuration on the machine Error:2147749896 (0×80041008)
Next Post
SQL SERVER – Check if Current Login is Part of Server Role Member

Related Posts

402 Comments. Leave new

  • prasad kumar
    June 4, 2011 4:42 pm

    Hi Pinal,

    I am new to SQL server,This really helps me a lot.

    And also please let me know how i can upgrade my knowledge.

    Thanks,
    Prasad

    Reply
  • prasad kumar
    June 4, 2011 4:45 pm

    Hi Pinal,

    1. What is the difference between left join and left outer join as well as right joins.

    2. And also please let me know what is the use of cross join.

    Reply
  • Good Article.
    Thank You

    Reply
  • RAm Chowdary
    June 7, 2011 2:13 pm

    Hi,Pinal

    Thats Good article regarding to JOINS, but how about Self join? And is self join is as same as inner join?

    Regards,
    RAm.

    Reply
  • RAm Chowdary
    June 7, 2011 2:19 pm

    HI pinal,
    Usually when we use sub queries in an Sp, there will be performance issue right? that too when there will be a usage of NOT IN(…………..). and this can be replaced by left join right?

    Regards,
    Ram
    Hyderabad

    Reply
  • hi panal sir,

    Really this article helps me a lot regarding join,can u please tell what is equi join thanks in advance

    Reply
  • Madhan kumar
    June 29, 2011 4:41 pm

    Great Fan! you really rock

    Reply
  • Trupti Hingu
    June 29, 2011 6:27 pm

    after a month i can understand the join n its type
    very very thankful to u

    Reply
  • super.
    Excellent article on JOINs.
    thank u.

    Reply
  • If you are searching for the Joins…..then you need not to worry at all, because i have posted a complete article with 3 parts on it;
    SQL Server – How to Merge Data with JOINS? – PART 1

    SQL Server – How to Merge Data with JOINS? – PART 2

    SQL Server – How to Merge Data with JOINS? – PART 3

    Reply
  • Purush otta ma
    July 26, 2011 2:11 pm

    SELECT L.request_session_id AS SPID,
    DB_NAME(L.resource_database_id) AS DatabaseName,
    O.Name AS LockedObjectName,
    P.object_id AS LockedObjectId,
    L.resource_type AS LockedResource,
    L.request_mode AS LockType,
    ST.text AS SqlStatementText,
    ES.login_name AS LoginName,
    ES.host_name AS HostName,
    TST.is_user_transaction as IsUserTransaction,
    AT.name as TransactionName,
    CN.auth_scheme as AuthenticationMethod
    FROM sys.dm_tran_locks L
    JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
    JOIN sys.objects O ON O.object_id = P.object_id
    JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
    JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
    JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
    JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
    CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
    WHERE resource_database_id = db_id()
    ORDER BY L.request_session_id

    Reply
  • Hello
    This was a great help to me …. thx

    Reply
  • Arti Nimbalkar
    August 1, 2011 6:32 pm

    Its an Exllent article… Thanks a lot…

    Reply
  • Hello sir,
    Really great tutorials regarding joins and very good explanation.
    But i m not fully satisfied as i have some questions in my mind. In this post you have not told about the advantages and disadvantages of using different types of joins. If we are using more than two tables then what would be the situation at that time. I m a beginner and not fully known to the concepts related to the sql server, so can u guide me to learn the concepts about it.
    Thanks and regards

    Reply
  • pinal sir yahan aapke blog me multiple records ko insert karne ke liye kisi ne coding likhi hai. but run ho nahi sakti wo ghalat hai. so pls usko remove kardo. so readers will not be misguided.
    wo coding ye hai.

    insert into table name(col1,col2) values(1,’abc’),(2,’pqr’),(3,’str’)……;
    here is a error of , so pls try this.

    Reply
  • Hi Faisal,

    insert into TryTable (id,name) values(1,’abc’),(2,’cde’),(3,’fgh’)

    it is working fine with sql server 2008.

    Reply
  • good article

    Reply
  • Nice Article, Easy to understand joins with the diagrams.

    Reply
  • Hi Pinal.

    I cant see the diagram or the table explained in the join Article.
    Help me

    Reply
  • Thanks for the diagram, now I see them.
    what would this query do

    Select * from table 1, table 2

    Table 1 and Table 2 have the same data structure
    Is it a type of Cross Join ?

    Reply

Leave a Reply