5

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!

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

2 Comments

@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.
So essentially the column name should not be specified but instead just the table name?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.