📜  sql cross apply vs join - SQL (1)

📅  最后修改于: 2023-12-03 15:35:04.320000             🧑  作者: Mango

SQL Cross Apply VS Join

In SQL, there are two common ways to combine data from multiple tables - Cross Apply and Join. Both of these methods can be used to join two or more tables, but they differ in terms of the output they produce and the scenarios in which they are most useful.

Cross Apply

CROSS APPLY is a type of JOIN that is used when you want to join a table with another table or a table-valued function that returns a table. It specifies a table expression to be evaluated for each row of the table that is being joined. This expression can be a table-valued function, a derived table, or a subquery.

The result of the CROSS APPLY will be a new row for each matching row between the two tables, where the columns from the first table are combined with the columns from the second table or function.

SELECT *
FROM TableA 
CROSS APPLY TableB
WHERE TableA.ID = TableB.ID
Join

JOIN is also used to combine data from two or more tables. There are several types of JOINs, such as INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, etc.

An INNER JOIN returns only the rows that have matching values in both tables. It combines the columns from both tables into one output table, where each row represents a unique pair of matching rows between the two tables.

SELECT *
FROM TableA 
INNER JOIN TableB ON TableA.ID = TableB.ID
When to use Cross Apply vs Join

CROSS APPLY is useful when you need to join a table with a function that returns a table or when you need to transform the data before joining. For example, to join a table with a function that generates a list of values for each row in the table:

SELECT *
FROM Orders 
CROSS APPLY dbo.GetOrderDetails(Orders.OrderID) od;

Here, the function dbo.GetOrderDetails() returns a table that contains the details of each order. The CROSS APPLY here evaluates the function for each row in the Orders table and returns a row for each matching row between Orders and dbo.GetOrderDetails().

On the other hand, JOIN is useful for simple joins of two or more tables, where the data can be combined one-to-one or one-to-many.

SELECT *
FROM Customers 
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID

Here, the LEFT JOIN combines the Customers table with the Orders table based on the CustomerID column. The output table contains all the rows from the Customers table and only the matching rows from the Orders table.

Conclusion

Both CROSS APPLY and JOIN are powerful tools for combining data from multiple tables in SQL. The main difference between them is the scenarios in which they are most useful. In general, use CROSS APPLY for complex joins with functions that return tables, and use JOIN for simpler joins of two or more tables.