Foreign Key appearing as NULL in table. Why?

I am having trouble properly inserting a foreign key into a table. I have created a couple of tables using this format:

CREATE TABLE tbl_Example
    ExampleID INT IDENTITY(1,1),
    Example VARCHAR(5) NULL,
    Example VARCHAR(6) NULL,
    Example VARCHAR(MAX),
    Example VARCHAR(MAX),
    ExampleFK INT, 
    Example VARCHAR(MAX),

And have inserted values to this table following this format:

FROM tbl_Example

INSERT INTO tbl_Example (Example, Example, Example, Example, etc.)
VALUES ('data', 'data', 'data', 'data', etc.)

And at the end of my code have placed this in order to add a foreign key to my original table:

ALTER TABLE tbl_Example 
    ADD FOREIGN KEY (ExampleFK) REFERENCES tbl_Example1 (Example1ID) 

For some reason after executed the foreign key column is filled completely with NULL. I have tried adjusting the placement of my foreign key column and have used varying forms of syntax in order to create the foreign key and correct the issue but nothing has worked. The key and connection appear to have been made, it is just not appearing properly in my table for some reason.

Edit: The values should not be NULL. Example1ID has no NULL values.

2 answers

  • answered 2018-10-11 19:01 China Syndrome

    The reason that you have NULLS is when you add the foreign key to tbl_Example it references tbl_Example1 (Example1ID)

    So this is not a 1 to 1 relationship meaning tbl_Example1 PK does not auto fill

    what this means is any tbl_Example1 PK can be filled into tbl_Example as FK you need to enforce this through the application or through the database in another way

  • answered 2018-10-11 19:12 big_mike_boiii

    Are you thinking that “ADD FOREIGN KEY” will insert values? It just creates the constraint. You have to update the rows now.