When we need specific data from table2 to be included in table1, a Cartesian join (CROSS APPLY) is used, which is why it takes too much time. Therefore, this method is not recommended. Instead, use a Common Table Expression (CTE) in MS SQL. In a large dataset of 50k to 100k records, the CROSS APPLY operation took 3-4 minutes to fetch the data. On the other hand, the Common Table Expression (CTE) took just under 1 second.

CROSS APPLY in SQL Server is used to join a table with a table-valued function or subquery. It works like an INNER JOIN but allows joining based on complex calculations or operations that can’t be directly expressed in a simple JOIN condition.

Key Points:

  • It evaluates the subquery or table-valued function for each row in the left (outer) table.
  • It is often used when you need to retrieve the top N rows, aggregate calculations, or a subset of data based on certain conditions.
  • CROSS APPLY excludes rows in the left table that do not return any results from the subquery or table-valued function.
CustomerIDCustomerName
1Alice
2Bob
3Charlie
OrderIDCustomerIDOrderAmount
1011250
1022300
1031150
1043500
SELECT 
    c.CustomerID, 
    c.CustomerName, 
    o.OrderID, 
    o.OrderAmount
FROM 
    Customers c
CROSS APPLY
    (SELECT TOP 1 
        o.OrderID, 
        o.OrderAmount 
     FROM 
        Orders o 
     WHERE 
        o.CustomerID = c.CustomerID
     ORDER BY 
        o.OrderID DESC) o;

Output

CustomerIDCustomerNameOrderIDOrderAmount
1Alice103150
2Bob102300
3Charlie104500

Faster approach using CTE:

WITH LatestOrders AS (
    SELECT 
        o.CustomerID,
        o.OrderID,
        o.OrderAmount,
        ROW_NUMBER() OVER (PARTITION BY o.CustomerID ORDER BY o.OrderID DESC) AS rn
    FROM 
        Orders o
)
SELECT 
    c.CustomerID,
    c.CustomerName,
    lo.OrderID,
    lo.OrderAmount
FROM 
    Customers c
LEFT JOIN 
    LatestOrders lo
ON 
    c.CustomerID = lo.CustomerID
WHERE 
    lo.rn = 1;