Skip to content

Instantly share code, notes, and snippets.

@dacc
Created August 26, 2013 21:48
Show Gist options
  • Save dacc/6347080 to your computer and use it in GitHub Desktop.
Save dacc/6347080 to your computer and use it in GitHub Desktop.
postgres=# create table bar(id serial primary key);
NOTICE: CREATE TABLE will create implicit sequence "bar_id_seq" for serial column "bar.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "bar_pkey" for table "bar"
CREATE TABLE
postgres=# create table foo(bar_id int not null references bar deferrable initially deferred);
CREATE TABLE
postgres=# insert into bar values(1);
INSERT 0 1
postgres=# insert into foo values(1);
INSERT 0 1
postgres=# begin;
BEGIN
postgres=# truncate table bar;
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "foo" references "bar".
HINT: Truncate table "foo" at the same time, or use TRUNCATE ... CASCADE.
postgres=# rollback;begin;
ROLLBACK
BEGIN
postgres=# set constraints all deferred;
SET CONSTRAINTS
postgres=# truncate table bar;
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "foo" references "bar".
HINT: Truncate table "foo" at the same time, or use TRUNCATE ... CASCADE.
postgres=# rollback;begin;
ROLLBACK
BEGIN
postgres=# delete from bar;
DELETE 1
postgres=# commit;
ERROR: update or delete on table "bar" violates foreign key constraint "foo_bar_id_fkey" on table "foo"
DETAIL: Key (id)=(1) is still referenced from table "foo".
postgres=# rollback;begin;
ROLLBACK
BEGIN
postgres=# delete from bar;
DELETE 1
postgres=# copy bar from stdin;
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 1
>> \.
postgres=# commit;
COMMIT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment