Search code examples
sqlpostgresqlforeign-keys

How to add a foreign key when creating a table to a table created after it?


How does it work when I want to add a foreign key to the first table that I make that references to the primary key of the second table I create?

CREATE TABLE table1
(   
    name_id INT NOT NULL,
    team TEXT REFERENCES table2(team_id),
    PRIMARY KEY(name_id)
);

CREATE TABLE table2
(
    team_id INT NOT NULL,
    teamname TEXT,
    PRIMARY KEY(team_id)
);

If I try the code above, I get the following error:

ERROR: relation "" does not exist


Solution

  • Either create the second table first. Or use alter table. That is, create the first table without the reference and then do:

    alter table table1 add constraint fk_table1_team
        foreign key (team_id) REFERENCES table2(team_id);
    

    The declaration for table1 would be:

    CREATE TABLE table1 (   
        name_id INT NOT NULL,
        team_id INT, 
        PRIMARY KEY(name_id)
    );
    

    The reference between the tables should be on the primary key and certainly not on a character column, if an integer is available.