What use of Cross apply?
.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sundaram SubramanianRank #150 · 15.2K reputationPosted Jun 20, 2017, 1:20 AM EDT
Rajkiran SwainRank #165 · 14.4K reputationPosted Jun 20, 2017, 1:30 AM EDT
See the article in my blog for detailed performance comparison:
INNER JOINvs.CROSS APPLYCROSS APPLYworks better on things that have no simpleJOINcondition.This one selects
3last records fromt2for each record fromt1:SELECT t1.*, t2o.* FROM t1 CROSS APPLY ( SELECT TOP 3 * FROM t2 WHERE t2.t1_id = t1.id ORDER BY t2.rank DESC ) t2oIt cannot be easily formulated with an
INNER JOINcondition.You could probably do something like that using
CTE's and window function:WITH t2o AS ( SELECT t2.*, ROW_NUMBER() OVER (PARTITION BY t1_id ORDER BY rank) AS rn FROM t2 ) SELECT t1.*, t2o.* FROM t1 INNER JOIN t2o ON t2o.t1_id = t1.id AND t2o.rn 3, but this is less readable and probably less efficient.
Update:
Just checked.
masteris a table of about20,000,000records with aPRIMARY KEYonid.This query:
WITH q AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM master ), t AS ( SELECT 1 AS id UNION ALL SELECT 2 ) SELECT * FROM t JOIN q ON q.rn t.idruns for almost
30seconds, while this one:WITH t AS ( SELECT 1 AS id UNION ALL SELECT 2 ) SELECT * FROM t CROSS APPLY ( SELECT TOP (t.id) m.* FROM master m ORDER BY id ) qis instant.
Shraddha Patel176 reputationPosted Apr 29, 2019, 7:13 PM EDT
Amit KumarRank #459 · 5.4K reputationPosted Apr 29, 2019, 8:07 PM EDT
Shraddha Patel176 reputationPosted May 21, 2019, 6:45 PM EDT