Thursday, May 20, 2021

SQL inner join with example

 INNER JOIN: Returns records that have matching values in both tables.

Inner Join clause in SQL Server creates a new table (not physical) by combining rows that have matching values in two or more tables. This join is based on a logical relationship (or a common field) between the tables and is used to retrieve data that appears in both tables.

Assume, we have two tables, Table A and Table B, that we would like to join using SQL Inner Join. The result of this join will be a new result set that returns matching rows in both these tables. The intersection part in black below shows the data retrieved using Inner Join in SQL Server.

Syntax:

FROM table1 INNER JOIN table2 ON table1.field1 [operator] table2.field2

[operator]=Any relational comparison operator: "=," "<," ">," "<=," ">=," or "<>."

Example:

use AdventureWorks2017
GO
SELECT P.ProductID, 
P.Name,P.ListPrice,P.Size,P.ModifiedDate,SOD.UnitPrice,SOD.UnitPriceDiscount,SOD.OrderQty,SOD.LineTotal 
FROM Sales.SalesOrderDetail SOD 
INNER JOIN Production.Product P ON SOD.ProductID = P.ProductID 
WHERE SOD.UnitPrice > 3500 
ORDER BY SOD.UnitPrice DESC

Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns. If there are records in the "SalesOrderDetail" table that do not have matches in "Product", these orders will not be shown!

Please visit related article below:

No comments:

Post a Comment