Joining on No Fields at All

In my previous tip, I explained how to join on multiple fields, but it is actually possible to join two tables on no fields at all. Using the "Old Style" syntax, such a join would look like:

SELECT t1.code, t2.code FROM t1,t2

"What does this type of query return?"

Suppose t1 has the character values "A","B","C" stored in the code column, and that the code column of t2 has the numeric values 1,2,3.

The above query will return the following rows:

code code
A 1
A 2
A 3
B 1
B 2
B 3
C 1
C 2
C 3

In other words, a join without any join condition at all, returns every possible combination of rows from the joined tables. In SQL Server 7, this query can also be written as:

SELECT t1.code, t2.code FROM t1 CROSS JOIN t2

This syntax is clearer, in that it indicates that you intentionally joined the tables this way, and didn't just forget to write a join condition.

"OK, that sounds fascinating, but what the heck would I use it for?"

I actually ran across a use for this technique a few months ago. My client had a table specifying which combinations of values were to be rejected by the system. Something like the following:

code1 code2
A 2
B 2
B 3
C 1

Given the table of invalid combinations, the client wanted a list of all the valid combinations. ie the required output had to look like:

code1 code2
A 1
A 3
B 1
C 2
C 3

To do that, I used a nested query that looked something like:

SELECT t1.Code,t2.Code FROM t1,t2 WHERE NOT t2.Code IN
(SELECT Code2 FROM InvalidCombination WHERE Code1=t1.Code)

Home About the Author Copyright © 2001 Adelle Hartley