postgresqlforeign-keysetldata-modelingalter-table

Creating a data model from scratch: Adding a Foreign Key in PostgreSQL


as personal project, I'm creating a small data model from a dataset.

Right now I'm facing issues in creating a foreign key between two tables.

CREATE TABLE IF NOT EXISTS public."Years"
(
    "ID_Year" integer,
    "Year" integer,
    PRIMARY KEY ("ID_Year")
);

CREATE TABLE IF NOT EXISTS public."SendingCountries"
(
    "ID_Send_Country" integer,
    "Year2Years" integer,
    "Country2Countries" integer,
    "Female_legis2FemaleLegislators" integer,
    "FeministPolicy" boolean,
    PRIMARY KEY ("ID_Send_Country")
);

I've used this code:

ALTER TABLE SendingCountries
ADD CONSTRAINT FK_SendingCountries_Years
FOREIGN KEY (Year2Years)
REFERENCES Years(ID_Year);

but I have this output: "ERROR: relation "sendingcountries" does not exist"

Can anyone highlight what I'm doing wrong?

thanks

My goal is to have the column "Year2Years" , from table SendingCountries, as Foreign key of ID_Year of Table Years


Solution

  • I can think of two reason from your code:

    1. Case sensitivity: PostgreSQL by default converts unquoted identifiers to lowercase. Ensure that the table name matches the casing used in your SQL query.
    2. Schema qualification: Ensure that the table belongs to the correct schema.

    Based on the provided code, it seems like you're using double quotes around table and column names, which means PostgreSQL will retain the casing you provide. Double-check the casing in your SQL query.

    can you try:

    ALTER TABLE public."SendingCountries"
    ADD CONSTRAINT FK_SendingCountries_Years
    FOREIGN KEY ("Year2Years")
    REFERENCES public."Years"("ID_Year");