PostgreSQL: Column Reference in Foreign Key Constraint Does Not Exist

21,304

Code does not exist in your customer table. It's state.

ALTER TABLE customer 
ADD CONSTRAINT state FOREIGN KEY (state) 
REFERENCES statename (code) >MATCH FULL;
Share:
21,304
Admin
Author by

Admin

Updated on January 16, 2020

Comments

  • Admin
    Admin over 4 years

    I'm still new to postgreSQL. I have two tables I created that I want to go back and add Primary and Foreign key constraints for and no matter what I do I can't seem to add a foreign key. Here's what I have:

    Two Tables:

    test=# \d statename
          Table "public.statename"
     Column |     Type      | Modifiers
    --------+---------------+-----------
     code   | character(2)  | not null
     name   | character(30) |
    Indexes:
        "statename_pkey" PRIMARY KEY, btree (code)
    
    test=# \d customer
              Table "public.customer"   
        Column   |     Type      | Modifiers
    -------------+---------------+-----------
     customer_id | integer       |
     name        | character(30) |
     telephone   | character(20) |
     city        | character(25) |
     street      | character(40) |
     state       | character(2)  |
     zipcode     | character(10) |
     country     | character(20) |
    

    Here's the command I'm running:

    test=# ALTER TABLE customer ADD CONSTRAINT
    state FOREIGN KEY (code) REFERENCES
    statename (code) >MATCH FULL;
    

    Here's the error I'm getting:

    ERROR:  column "code" referenced in foreign key constraint does not exist
    

    I'm looking at the column! I know it exists! Please help a brother out!

  • Line
    Line over 9 years
    @Derek, which "state" determines foreign key and which column name? I try to add reference without giving it's name - such as by table creating.
  • Chris Stryczynski
    Chris Stryczynski over 6 years
    So essentially the column name should not be specified but instead just the table name?