Skip to content

Partial Foreign Keys #7260

@livius2

Description

@livius2

As the #3750 is now in pull requests and will be soon available,
i have moved my comment into new feature request for simpler processing.

Please add partial referential constraints (foreign keys).

Example:


instead of multiple "NOTES" tables NOTES_CUSTOMER, NOTES_PERSON, NOTES_THING ...


or one table with multiple ids which refere to other tables

CRATE TABLE NOTES
(
ID BIGINT NOT NULL PRIMARY KEY

, ID_CUSTOMER BIGINT NOT NULL
, ID_PERSON BIGINT NOT NULL
, ID_THING BIGINT NOT NULL
... other refids ...

DESCRIPTION VARCHAR(200)
);

we can do this:

CRATE TABLE NOTES
(
ID BIGINT NOT NULL PRIMARY KEY
, ID_REF BIGINT NOT NULL /* field from multiple tables */
,REF_TYPE INTEGER NOT NULL /* table type like Customer, Person, ... */
DESCRIPTION VARCHAR(200)
);

and now the crucial part - partial Foreign Keys:

ALTER TABLE NOTES ADD CONSTRAINT FK_NOTES__CUSTOMER FOREIGN KEY(ID_REF) WHERE REF_TYPE=1 REFERENCES CUSTOMER(ID) ON DELETE NO ACTION ON UPDATE CASCADE;
ALTER TABLE NOTES ADD CONSTRAINT FK_NOTES__PERSON FOREIGN KEY(ID_REF) WHERE REF_TYPE=2 REFERENCES PERSON(ID) ON DELETE NO ACTION ON UPDATE CASCADE;
ALTER TABLE NOTES ADD CONSTRAINT FK_NOTES__THING FOREIGN KEY(ID_REF) WHERE REF_TYPE=3 REFERENCES THING(ID) ON DELETE NO ACTION ON UPDATE CASCADE;

This foreign keys will create partial index.

This is maybe not ideal design - but sometimes this will simplify many, many problems.
In the past i have many times such situation that i need multiple "same" table only reference is different.


There is another case for this and the common one. It can exclude nulls from FK indexes.

ALTER TABLE TEST ADD CONSTRAINT FK_TEST__PERSON FOREIGN KEY(PERSON_ID) WHERE PERSON_ID IS NOT NULL REFERENCES PERSON(ID) ON DELETE NO ACTION ON UPDATE CASCADE;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions