Monday, 11 February 2013

SQL Server INNER JOIN Syntax and Example

SQL INNER JOIN 
The LEFT JOIN returns the matching records from the Left Table (Table_I) and the Right Table (Table_2).The INNER JOIN  Query returns the when there is at least one match in both tables.
In other words it returns only the matching rows from both the tables.



Syntax:
SELECT Column_name(s) FROM Table_1 T1 INNER JOIN Table_2 T2
ON  T1.Column_name=T2.Column_name

Note: INNER JOIN is the same as JOIN.

Example :
Suppose we have two tables as follows

The "ORDERS" Table:


The "CUSTOMERS" Table:

Now we want to list all the Customers with any Orders.We use the following Inner Join Query:
Select O.Order_Id,C.Cust_Name,C.Cust_Id,C.Cust_Location,O.Sales_Period,O.Sales from ORDERS INNER JOIN CUSTOMERS ON C.Cust_Id = O.Cust_Id

Output : 

Notes :
--If there are rows in "Customers" that do not have matches in "Orders", those rows will NOT be listed.
--The following Inner Join Query returns the matching records and displays All the Columns from Orders table and only Cust_Name column from Customers Table
Select O.*,Cust_Name from Orders O
LEFT JOIN
Customers C
ON O.Cust_Id=C.Cust_Id
GO

--The following Inner Join Query returns the matching records and displays All the Columns from both the Orders table and Customers tables.
Select* from Orders O
LEFT JOIN
Customers C
ON O.Cust_Id=C.Cust_Id
GO

--------------------------------------------------------------------------------------------------------
Thanks, TAMATAM ; Business Intelligence Professional
--------------------------------------------------------------------------------------------------------

No comments:

Post a Comment

Hi User, Thank You for Visiting My Blog. Please Post Your Feedback/Comments/Query.

Subscribe to Blog Posts by Email

ExcelKingdom-Popular Posts

ExcelKingdom-Random Posts