sqlpostgresqlforeign-keysconstraints

Why do I get SQL state:23503 when I try to add a constraint to an existing table in Postgres?


I have table Advisor which is a special Userand contains only id and user_id (for now!) and I'm trying to make user_id a foreign key with the following script:

ALTER TABLE advisor
ADD CONSTRAINT advisor_user_id_fkey
FOREIGN KEY (user_id) REFERENCES "user" (id);

Which I think should work, however I get this error:

ERROR: insert or update on table "advisor" violates foreign key constraint "advisor_user_id_fkey"
SQL state: 23503
Detail: Key (user_id)=(44) is not present in table "user".

I thinks this is weird because I'm saying it should refer to user.id and not user.user_id, but obviously I'm doing something wrong. Does anyone have any idea about this? Thanks.

update: if anyone is wondering why "user" and not user, well pgAdmin doesn't like user, because it thinks it's the owner of the database.


Solution

  • Your error message states that you have an entry in your "advisor" table (44) which does not exist in your "user" table.

    Your Foreign Key is defined on "advisor" and stipulates that the "user" table is the parent table. Perhaps you have that Foreign Key defined backwards?

    About the "user" issue, "user" is a reserved word, that's why pgadmin is having trouble with it. If you have the ability to change that, I recommend it. See reserved words at: http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html.