How to add foreign key that points to one of 2 tables with Postgres? - sql

I want to add a foreign key that is check record_id of activity exists in one of the record or personal_record tables. Is it possible to do with Postgres?
CREATE TABLE record
(
id BIGSERIAL PRIMARY KEY
);
CREATE TABLE personal_record
(
id BIGSERIAL PRIMARY KEY
);
CREATE TABLE activity
(
id BIGSERIAL PRIMARY KEY,
record_id BIGINT NOT NULL,
CONSTRAINT record_fk FOREIGN KEY (record_id) REFERENCES record (id)
);

As stated, this is not possible. One possibility is generated columns and nullable references:
CREATE TABLE activity (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
private_record_id BIGINT,
private_personal_record_id BIGINT,
record_id BIGINT GENERATED ALWAYS AS (COLAESCE(private_record_id, private_personal_record_id)),
CHECK( (private_record_id IS NOT NULL AND private_personal_record_id IS NULL) OR
(private_record_id IS NULL AND private_personal_record_id IS NOT NULL)
),
CONSTRAINT fk_activity_record_id FOREIGN KEY (private_record_id) REFERENCES record(id),
CONSTRAINT fk_activity_record_id FOREIGN KEY (private_personal_record_id) REFERENCES personal_record(id),
);
You might also want to look into inheritance.

Related

Add a reference to a postgrest table

I want to alter the artist_label to be label_id BIGINT NOT NULL REFERENCES label(id) like how it is in the album_label table.
CREATE TABLE label (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
parent_label_id BIGINT REFERENCES label(id)
);
CREATE TABLE album_label (
id BIGSERIAL PRIMARY KEY,
album_id TEXT NOT NULL UNIQUE,
label_id BIGINT NOT NULL REFERENCES label(id)
);
CREATE INDEX album_label_idx ON album_label(label_id);
CREATE INDEX album_uid_idx ON album_label(id)
CREATE TABLE artist_label (
artist_id VARCHAR(60) NOT NULL,
label_id BIGINT NOT NULL,
PRIMARY KEY (artist_id, label_id)
);
CREATE INDEX artist_label_idx ON artist_label(label_id);
If you haven't created the tables yet, you could modify the creation script and add that clause.
If you're asking how to modify the table after its creation, you can use an alter table statement:
ALTER TABLE artist_label
ADD CONSTRAINT artist_label_fk FOREIGN KEY (label_id) REFERENCES label(id)
SQLFiddle Example

ERROR: No unique constraint matching when having FK

I have three tables that are linked together
My script:
-- Ticket --
CREATE TABLE public.ticket (
id bigint NOT NULL,
libelle character varying(255) NOT NULL,
description character varying(255) NOT NULL,
status character varying(255) NOT NULL,
date_creation timestamp NOT NULL,
date_modification timestamp NOT NULL,
user_createur_id bigint,
referent_realisateur_id bigint,
CONSTRAINT pk_ticket PRIMARY KEY (id)
);
-- Ticket_Avance TABLE --
CREATE TABLE public.ticket_avance (
id bigint NOT NULL,
date_livraison_souhaite timestamp NOT NULL,
date_engagement_livraison timestamp NOT NULL,
referent_demandeur_id bigint
);
ALTER TABLE public.ticket_avance ADD CONSTRAINT "fk_ticket_ticketAvance" FOREIGN KEY (id)
REFERENCES public.ticket (id) MATCH SIMPLE
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- Demande_Travaux TABLE --
DROP TABLE IF EXISTS public.demande_travaux CASCADE;
CREATE TABLE public.demande_travaux (
id bigint NOT NULL,
contrat_id bigint
);
ALTER TABLE public.demande_travaux ADD CONSTRAINT "fk_ticketAvance_DDT" FOREIGN KEY (id)
REFERENCES public.ticket_avance (id) MATCH FULL
ON DELETE NO ACTION ON UPDATE NO ACTION;
I have this error on the demand_travaux creation
SQL Error [42830]: ERROR: there is no unique constraint matching given keys for referenced table "ticket_avance"
ERROR: there is no unique constraint matching given keys for referenced table "ticket_avance"
ERROR: there is no unique constraint matching given keys for referenced table "ticket_avance"
You have forgotten to declare column ID in table ticket_avance as primary key.
Please use the following SQL:
-- Ticket_Avance TABLE --
CREATE TABLE public.ticket_avance (
id bigint NOT NULL,
date_livraison_souhaite timestamp NOT NULL,
date_engagement_livraison timestamp NOT NULL,
referent_demandeur_id bigint,
CONSTRAINT pk_avance PRIMARY KEY (id) --- add this
);
you need add constraint in Ticket_Avance table because you provide reference this id to demande_travaux
-- Ticket_Avance TABLE --
CREATE TABLE ticket_avance (
id bigint NOT NULL,
date_livraison_souhaite timestamp NOT NULL,
date_engagement_livraison timestamp NOT NULL,
referent_demandeur_id bigint,
CONSTRAINT pk_ticket_avance PRIMARY KEY (id) //constraint that you need
);
ALTER TABLE demande_travaux ADD CONSTRAINT "fk_ticketAvance_DDT" FOREIGN KEY (id)
REFERENCES ticket_avance (id) MATCH FULL
ON DELETE NO ACTION ON UPDATE NO ACTION;
here is the demo link of your full query
A foreign key constraint has to target a primary key or unique constraint. The database has to be able to identify a single row in the "parent" table.
You could add primary key constraints:
ALTER TABLE public.ticket_avance ADD PRIMARY KEY (id);
In addition, you should have an index on the column on which the foreign key is defined, particularly if you plan to delete parent rows. With the primary key above, you have such an index on id, but you also should have one on demande_travaux.
The simplest way is to define id as primary key there too:
ALTER TABLE public.demande_travaux ADD PRIMARY KEY (id);

Make attribute primary and foreign key in sql

How can I make an attribute a primary key within a table but also as a foreign key which references another table using sql in sql developer?
I know how to make it an attribute as a foreign key and a primary separate but not as a primary key as well as a foreign key
That's perfectly normal. For example:
create table employee (
id number(6) primary key not null,
name varchar2(50)
);
create table employee_desk (
desk_id number(6) primary key not null, -- PK and FK!
location varchar2(20),
constraint fk1 foreign key (desk_id) references employee (id)
);
The column desk_id is the primary key of the table employee_desk, and also a foreign key that points to the table employee.
Below is the example of primary key with foreign key
create table animals (id integer primary key);
create table cats (
id integer primary key
, name varchar(100) not null
, constraint d_cats_animals_fk foreign key (id) references animals (id)
);

Composite primary key for 1-to-many relationship?

Well, I was always doing it like this:
create table language (
id bigserial primary key,
code varchar(10) not null
);
create table entity (
id bigserial primary key
);
create table entity_description (
id bigserial primary key,
language_id bigint not null,
constraint fk__entity_description__language
foreign key language_id
references language(id),
entity_id bigint not null,
constraint fk__entity_description__entity
foreign key entity_id
references entity(id),
name varchar(20) not null
);
but I wonder.. why wouldn't I do it like this:
create table language (
id bigserial primary key,
code varchar(10) not null
);
create table entity (
id bigserial primary key
);
create table entity_description (
language_id bigint not null,
constraint fk__entity_description__language
foreign key language_id
references language(id),
entity_id bigint not null,
constraint fk__entity_description__entity
foreign key entity_id
references entity(id),
primary key (language_id, entity_id),
name varchar(20) not null
);
My questions are
Is there anything that speaks against the composite primary key in the second example?
Are there any benefits?
Are, in the second example, (language_id, entity_id), language_id and entity_id indexed separately for table entity_description? If I fetch for .. WHERE entity_description.id = x is this slower than fetching for .. WHERE (entity_description.language_id, entity_description.entity_id) = (x,y)?

Not able to create foreign key "There are no primary or candidate keys in the referenced table"

This is my table 1:
CREATE TABLE PurchasedProducts
(
Purchase_Order_No int,
Purchase_Product_ID int FOREIGN KEY REFERENCES Inventory(In_Product_ID),
Purchase_Quantity int NOT NULL,
Purchase_Status varchar(7) NOT NULL,
PRIMARY KEY(Purchase_Order_No, Purchase_Product_ID)
);
This my table 2:
CREATE TABLE PurchasedDate
(
PD_PO_No int NOT NULL PRIMARY KEY FOREIGN KEY REFERENCES PurchasedProducts(Purchase_Order_No),
PD_Date date NOT NULL
);
I executed the first table successfully, but when I execute the second table It is showing this error message:
There are no primary or candidate keys in the referenced table 'PurchasedProducts' that match the referencing column list in the foreign key 'FK__Purchased__PD_PO__0B5CAFEA'.
I don't what is the problem is. Please help me!
The primary key in your PurchasedProducts table is made up of two columns:
PRIMARY KEY(Purchase_Order_No, Purchase_Product_ID)
So any child table that wants to reference that also must have these exact two columns:
CREATE TABLE PurchasedDate
(
PD_PO_No int NOT NULL PRIMARY KEY,
Purchase_Product_ID INT NOT NULL,
PD_Date date NOT NULL
);
ALTER TABLE dbo.PurchasedDate
ADD CONSTRAINT FK_PurchaseDate_PurchasedProducts
FOREIGN KEY(PD_PO_No, Purchase_Product_ID)
REFERENCES PurchasedProducts(Purchase_Order_No, Purchase_Product_ID)
A foreign key can only reference the whole primary key of a parent table - you cannot reference only one column out of 2 from the parent table's PK.