patternsqlMinor
Add foreign key constraint to an existing table column, referencing a column in a newly created table
Viewed 0 times
addcolumnreferencingcreatedforeignconstraintexistingtablekeynewly
Problem
Let's say I have one table defined as this
Then an ETL process fills this table with data
But later, I need to add a table with actual processed dates, such as
and want to add a foreign key constraint on the old table:
Naturally, I get the following error:
ERROR: insert or update on table "sales" violates foreign key constraint "sales_date_fk" Detail: Key (sale_date)=(2019-01-01) is not present in table "dates".
I know I can work around this by deleting/truncating all data in
Is there any way to accomplish this?
I'm using Postgres 11, but this fiddle running 9.6 shows what I've tried to explain here.
CREATE TABLE sales (
agent_id integer references agents(agent_id),
sale_date date,
amout numeric(10,2)
);Then an ETL process fills this table with data
INSERT INTO sales VALUES
(1, '2019-01-01', 1031.11),
(1, '2019-01-02', 525.44),
(1, '2019-01-03', 323.99);But later, I need to add a table with actual processed dates, such as
CREATE TABLE dates (
date_idx date primary key,
year integer not null,
month integer not null,
day integer not null
);and want to add a foreign key constraint on the old table:
ALTER TABLE sales
ADD CONSTRAINT sales_date_fk FOREIGN KEY (sale_date)
REFERENCES dates (date_idx);Naturally, I get the following error:
ERROR: insert or update on table "sales" violates foreign key constraint "sales_date_fk" Detail: Key (sale_date)=(2019-01-01) is not present in table "dates".
I know I can work around this by deleting/truncating all data in
sales or prefilling dates before adding the constraint, but I would prefer not to if I can avoid it.Is there any way to accomplish this?
I'm using Postgres 11, but this fiddle running 9.6 shows what I've tried to explain here.
Solution
You can use the
I would not recommend this though, unless something prevents you from populating the new child table so you have no choice.
This is postgres specific syntax, for instance the equivalent in SQL Server is
NOT VALID modifier when creating a foreign key to stop it verifying existing data. For instance:ALTER TABLE sales
ADD CONSTRAINT sales_date_fk FOREIGN KEY (sale_date)
REFERENCES dates (date_idx) NOT VALID;I would not recommend this though, unless something prevents you from populating the new child table so you have no choice.
This is postgres specific syntax, for instance the equivalent in SQL Server is
WITH NOCHECK, and some others may not support the option at all, so take care if trying to support multiple database backends.Code Snippets
ALTER TABLE sales
ADD CONSTRAINT sales_date_fk FOREIGN KEY (sale_date)
REFERENCES dates (date_idx) NOT VALID;Context
StackExchange Database Administrators Q#239169, answer score: 4
Revisions (0)
No revisions yet.