What is CROSS JOIN (SELECT 0 as a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION…)
What is CROSS JOIN (SELECT 0 as a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION…)
I came across an odd bit of legacy code while going back through old code for cleanup, and I'm trying to pin down exactly what it does...
CROSS JOIN (SELECT 0 as a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3) as b
It's a technique I haven't seen before, including multiple union selects of numbers inside a cross join, and I'm honestly really confused about what it's doing and why someone would do it.
1 Answer
1
Cross join creates a Cartesian product.
Cross join
Assuming the from clause looks like:
from
FROM t CROSS JOIN
( . . . )
This creates four rows for every one row in t. The value of b.a in these rows varies from 0 to 3.
t
b.a
So, basically, it turns [column1:foo, column2:bar] into [column1:foo, column2:bar, b:0], [column1:foo, column2:bar, b:1], [column1:foo, column2:bar, b:1], [column1:foo, column2:bar, b:3]?
– liljoshu
Jun 30 at 22:23
Just tested on a different server... yea, that's exactly what it does... weird, not sure the point of it though. Thanks!
– liljoshu
Jun 30 at 22:41
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Possible duplicate of SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?
– Alessandro Da Rugna
Jun 30 at 23:31