I created two tables below, and FK_TypeID
is nullable in this case. I want to write a query returning me the join of two tables.
if FK_TypeID
is NULL for a certain row, the TypeName
is also NULL. I am not sure how to go about creating such join statement?
[Actions]
ActionsID
Date
Message
FK_TypeID //links to the table below
[Type]
TypeID
TypeName
My current statment looks like this and it simply skips NULL FK_TypeID
rows
SELECT *
FROM Actions
INNER JOIN TypeName ON Actions.FK_TypeID = [Type].TypeID
Help would be greatly appreciated!
A table must have exactly one primary key to qualify as relational, but that key can be composed of multiple columns. A foreign key, by contrast, is one or more fields or columns that corresponds to the primary key of another table. Foreign keys are what make it possible to join tables to each other.
A table can have many foreign keys. A foreign key is nullable if any part is nullable. A foreign key value is null if any part is null.
Null values in tables or views being joined never match each other. Since bit columns do not permit null values, a value of 0 appears in an outer join when there is no match for a bit column in the inner table. The result of a join of null with any other value is null.
As we have seen from the above examples joining NULL values does not work. Even though you have two NULL values SQL Server does not treat these as the same value. Internally a value of NULL is an unknown value and therefore SQL Server does not equate an unknown value being equal to another unknown value.
You just need to use a LEFT JOIN
SELECT Actions.Date, Actions.Message, Type.TypeName
FROM Actions
LEFT JOIN Type
ON Type.TypeID = Actions.FK_TypeID
If a match to Actions
is not found to tie it with Type
, then all columns in Type
will be NULL
.
Here is a good graphical visualization of the different types of joins in SQL
Use an OUTER JOIN
SELECT Actions.Date, Actions.Message, Type.TypeName
FROM Actions LEFT OUTER JOIN
Type ON Type.TypeID = Actions.FK_TypeID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With