What is CROSS APPLY in SQL SERVER?
What is CROSS APPLY in SQL SERVER?
433
11-Jul-2023
Updated on 12-Jul-2023
Aryan Kumar
12-Jul-2023Cross apply in SQL Server is a type of join that returns all possible combinations of rows from two tables. It is similar to a Cartesian product, but it is more efficient because it only returns the rows that are actually present in the tables.
The syntax for cross apply in SQL Server is as follows:
SQL
For example, the following code will return all possible combinations of rows from the
Customerstable and theOrderstable:SQL
This code will return all rows from the
Customerstable, even if there are no matching rows in theOrderstable.The
CROSS APPLYoperator is often used in conjunction with a user-defined function (UDF). For example, the following code will return all customers and their orders, where the order date is greater than today's date:SQL
The
GetOrdersByDateUDF takes a date as input and returns a table with the customer ID, name, order ID, and order date for all customers who have placed an order on or after the specified date.The
CROSS APPLYoperator can be a powerful tool for combining data from two or more tables. However, it is important to use it carefully, as it can also return a large number of rows.