Monday, February 11, 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 & Analytics Professional
--------------------------------------------------------------------------------------------------------

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.

Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog