Imagine a table (named Example) with a single primary key field (KeyID) and also a foreign key field (ForeignID). This foreign key is used to link rows in our table to a foreign row/item in a separate table, establishing a many-to-one relationship. For many of our rows, however, no such relationship exists, so our foreign key field is NULL
in these rows.
Now, if we are given a single KeyID (e.g. 123), what is the preferred SQL for getting a result set containing all rows that have a matching ForeignID value?
I naively started with the following SQL:
SELECT E1.*
FROM Example E1
JOIN Example E2
ON E2.KeyID = 123
AND E2.ForeignID = E1.ForeignID
This works just great when our matching key row has a normal value in ForeignID. However, it fails (returning nothing) if the ForeignID happens to be NULL
. After doing some initial searching, I now understand why (after reading questions like this one), but I haven't found any nice solutions for how to work around this limitation.
Granted SQL Server has the ANSI_NULLS
setting that I can change, but this seems like a dirty, potentially problematic hack.
Alternatively, I could always make up my own pseudo-null value (like 0) and stick it in the ForeignID column instead of NULL
, but that would break the foreign key constraint I've established for this column.
So how best to achieve what I want?