1

I have a database with 2 tables, foo and foo_trash.

Both have the same structure with an id (primary key), and a title. foo_trash gets populated with data copied from foo with a statement like this:

INSERT INTO foo_trash (SELECT * FROM foo WHERE id = 253)

I would like to add a constraint on the table foo_trash so that no rows may be inserted into foo_trash if the same pair id and title is not present in foo.

How do I write that?

8
  • 1
    Use a foreign key constraint. Commented Jan 9, 2023 at 13:27
  • add a foreign key to the foo_trash table foo_id? That wouldn't work because of the manner of adding data to the foo_trash. Commented Jan 9, 2023 at 13:33
  • "How do I do that?" - postgresql.org/docs/current/… Commented Jan 9, 2023 at 13:36
  • "That wouldn't work because of the manner of adding data to the foo_trash" - why? Commented Jan 9, 2023 at 13:39
  • 1
    "Then the number of rows in the table foo and foo_trash would not be the same" - you mean columns not rows? But I did not say to add a new column foo_id, I did say to add a constraint. Commented Jan 9, 2023 at 13:49

1 Answer 1

2

Given the table foo:

create table foo (
  id int,
  title varchar(50),
  primary key (id, title)
  );

Define the table foo_trash to reference the two columns you mentioned:

create table foo_trash (
  id int primary key,
  title varchar(50),
  FOREIGN KEY (id, title) REFERENCES foo (id, title)
  );

Now you can insert data into foo:

insert into foo values (1, 'title1');
insert into foo values (2, 'title2');
insert into foo values (3, 'title3');
insert into foo values (253, 'title253');

If you try to insert a row into foo_trash that doesn't exist in foo, you will receive an error:

insert into foo_trash values (4, 'title4');

Output:

ERROR:  insert or update on table "foo_trash" violates foreign key constraint "foo_trash_id_title_fkey"
DETAIL:  Key (id, title)=(4, title4) is not present in table "foo".

You can insert a row in foo_trash that exists in foo:

insert into foo_trash values (3, 'title3');

And you can do your insert into foo_trash as select from foo successfully, assuming that id exists:

INSERT INTO foo_trash (SELECT * FROM foo WHERE id = 253);
Sign up to request clarification or add additional context in comments.

Comments

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.