HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Postgres - copy table INCLUDING CONSTRAINT doesn't include constraint

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresincludedoesnincludingconstrainttablecopy

Problem

How come that statement don't copy constraints if I explicitly ask for it?

CREATE TABLE backup_schema.permissions (LIKE public.permissions INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES INCLUDING STORAGE INCLUDING COMMENTS);
INSERT INTO backup_schema.permissions
    SELECT *
    FROM public.permissions
    WHERE community_id=123;


verifying with pgadmin3 I discovered that constraints on the new table(eg.:backup_schema) was:

but in the original table in public schema was like this:

Solution

The documentation says about INCLUDING CONSTRAINTS (emphasis mine):


Not-null constraints are always copied to the new table. CHECK constraints will only be copied if INCLUDING CONSTRAINTS is specified; other types of constraints will never be copied. Also, no distinction is made between column constraints and table constraints — when constraints are requested, all check constraints are copied.

Foreign keys obviously fall into this 'other constraints' group, this is why the two FKs of yours are not copied over.

Interestingly, the documentation for version 9.3 has a different wording, not stating the above so clearly.

Context

StackExchange Database Administrators Q#98333, answer score: 10

Revisions (0)

No revisions yet.