PostgreSQL/pgAdmin4 ERROR: there is no unique constraint matching given keys for referenced table "index" - postgresql

I'm trying to transform my MySQL design to PostgreSQL but when I try to create the table "index":
CREATE TABLE "model1"."index" (
"id_index" INT GENERATED ALWAYS AS IDENTITY ,
"index_name" VARCHAR(5) NOT NULL,
"index_type_id_index_type" INT NOT NULL,
"index_provider_id_index_provider" INT NOT NULL,
"miseq" VARCHAR(45) NOT NULL,
"nextseq" VARCHAR(45) NOT NULL,
PRIMARY KEY ("id_index"),
CONSTRAINT "fk_index_index_type"
FOREIGN KEY ("index_type_id_index_type")
REFERENCES "model1"."index_type" ("id_index_type")
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT "fk_index_index_provider"
FOREIGN KEY ("index_provider_id_index_provider")
REFERENCES "model1"."index_provider" ("id_index_provider")
ON DELETE NO ACTION
ON UPDATE NO ACTION);
I got this error: ERROR: there is no unique constraint matching given keys for referenced table "index".
The two tables containing the foreign keys were created before the "index" table:
CREATE TABLE "model1"."index_type" (
"id_index_type" INT GENERATED ALWAYS AS IDENTITY ,
"name" VARCHAR(3) NOT NULL,
PRIMARY KEY ("id_index_type"));
CREATE TABLE "model1"."index_provider" (
"id_index_provider" INT GENERATED ALWAYS AS IDENTITY ,
"name" VARCHAR(40) NOT NULL,
PRIMARY KEY ("id_index_provider"));

Solved. The error was in another table as #a_horse_with_no_name suggested.

Related

DB2 referential constraint cannot created

I can not add a referential constraint, both tables has the two columns id and version as primary key. I will only check the integrity that the row is existing without checking version.
CREATE TABLE TABLEE
(ID INTEGER NOT NULL,
VERSION INTEGER NOT NULL,
PRIMARY KEY (ID , VERSION);
CREATE TABLE CHAIR
(ID INTEGER NOT NULL,
VERSION INTEGER NOT NULL,
ID_TABLEE INTEGER,
PRIMARY KEY (ID , VERSION);
ALTER Chair
ADD constraint MYC FOREIGN KEY (ID)
REFERENCES TABLEE (ID)
ON DELETE RESTRICT
Got this error
[Code: -573, SQL State: 42890] A column list specified in the references clause of constraint "MYC " does not identify a unique constraint of the parent table or nickname "TABLEE".. SQLCODE=-573, SQLSTATE=42890, DRIVER=4.28.11
The problem here is that Tablee its primary key consists of two columns id and version. But the integrity check should only be made on the referenced id, not version.
To establish a foreign key on a table the referenced column needs to:
Be a primary key on the other table.
...or at least act as one.
Since you already have a primary key on the referenced table, you can use the second approach and add a UNIQUE and NOT NULL constraints on ID.
For example:
CREATE TABLE TABLEE (
ID INTEGER NOT NULL,
VERSION INTEGER NOT NULL,
PRIMARY KEY (ID , VERSION),
constraint uq1 unique (id) -- added UNIQUE constraint on ID
);
CREATE TABLE CHAIR (
ID INTEGER NOT NULL,
VERSION INTEGER NOT NULL,
ID_TABLEE INTEGER,
PRIMARY KEY (ID , VERSION)
);
ALTER table Chair
ADD constraint MYC FOREIGN KEY (ID)
REFERENCES TABLEE (ID)
ON DELETE RESTRICT;
See running example at db<>fiddle.
Note: If you want ID to have repeated values over the table, then ID is not a key, and cannot be referenced as one.

creating a table with two foreign keys in consideration

CREATE TABLE youth(
yh_id int NOT NULL,
surname VARCHAR(30) NOT NULL,
post VARCHAR(30) NOT NULL,
PRIMARY KEY (yh_id), REFERENCES members (mbrs_id) FOREIGN KEY (mbrs_id);
ERROR: syntax error at or near "REFERENCES"
LINE 5: PRIMARY KEY (yh_id), REFERENCES members (mbrs_id) FOREIGN ...
^
SQL state: 42601
Character: 128
Here is an example with the correct syntax.
create table members (
mbrs_id int primary key);
CREATE TABLE youth(
yh_id int NOT NULL,
surname VARCHAR(30) NOT NULL,
post VARCHAR(30) NOT NULL,
CONSTRAINT pk_youth_yh_id PRIMARY KEY (yh_id),
CONSTRAINT fk_youth_members_mbrs_id FOREIGN KEY (yh_id) REFERENCES members (mbrs_id) );
✓
✓
insert into members values(1);
insert into youth values
(1,'Jones','manager');
1 rows affected
1 rows affected
insert into youth values
(2,'Smith','chairman');
ERROR: insert or update on table "youth" violates foreign key constraint "fk_youth_members_mbrs_id"
DETAIL: Key (yh_id)=(2) is not present in table "members".
db<>fiddle here

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'questions_ibfk_1' in the referenced table 'category'

cannot add foreign key constraint to table
create table users
(
user_id int auto_increment primary key not null,
username varchar(50) unique null ,
email varchar(50) unique ,
passwords varchar(50) not null,
login_status boolean not null
);
create table category (
category_id int primary key not null,
category_name varchar(50) not null
);
create table answers (
id_answer int auto_increment primary key not null,
answer boolean not null
);
create table questions (
question_id int primary key not null,
category_name varchar(50) not null,
content varchar(50) not null ,
foreign key (category_name) references category (category_name)
);
You get this error because there's no index on category_name in the category table. Change that CREATE statement as follows:
create table category (
category_id int primary key not null,
category_name varchar(50) not null,
KEY category_name_index (category_name)
);
From the docs (8.0 version, but the statement is true for older versions):
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
Also, you're using a varchar(50) as your foreign key, which is not usually a great idea for a variety of reasons. You probably want to use a numeric value, such as category_id, instead.

Find cause of error "constraint xxxx is not a foreign key constraint" in Postgresql

I have defined these tables:
CREATE TABLE "public".category (id BIGSERIAL NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY (id));
CREATE UNIQUE INDEX category_name ON "public".category (name);
CREATE TABLE "public".clusters (id BIGSERIAL NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY (id));
CREATE INDEX clusters_name ON "public".clusters (name);
CREATE TABLE "public".keywords (id BIGSERIAL NOT NULL, text varchar(255) NOT NULL, category_id int8 NOT NULL, top_results int4, cluster_id int8, month_requests int4, click_cost float8, PRIMARY KEY (id));
CREATE INDEX keywords_text ON "public".keywords (text);
ALTER TABLE "public".keywords ADD CONSTRAINT FKkeywords488682 FOREIGN KEY (cluster_id) REFERENCES "public".clusters (id);
ALTER TABLE "public".keywords ADD CONSTRAINT FKkeywords446526 FOREIGN KEY (category_id) REFERENCES "public".category (id) ON UPDATE CASCADE ON DELETE CASCADE;
added one record to category table:
INSERT INTO "public".category(id, name) VALUES (1, 'Test');
And now when I try to add record to keyword table
insert into "public"."keywords" ( "category_id", "text") values ( 1, 'testkey')
I got error:
ERROR: constraint 16959 is not a foreign key constraint
When I do
select * FROM pg_constraint;
I can't see constraint with this id. I can't understand what is the cause of this problem.

PostgreSQL foreign keys multiple keys on single table

I can imagine that it is unlikely that this question has never been answered. However, I have not found it, so in any case here is my problem:
I am migrating from MySQL.
I am getting an error when I try to create a table with one single data field with 2 foreign keys referencing another table.
My goal is to simply have a phone directory for employees.
The directory table must reference the employee id as well as the phone number type.
I get this error when trying to do so:
ERROR: There is no unique constraint matching given keys, for referenced table: Employees!
Here is my current sql dump:
-- ----------------------------
-- Table structure for EmployeeGroups
-- ----------------------------
DROP TABLE IF EXISTS "public"."EmployeeGroups";
CREATE TABLE "public"."EmployeeGroups" (
"Id" int8 DEFAULT nextval('"EmployeeGroups_Id_seq"'::regclass) NOT NULL,
"EmployeeGroup" varchar(255) COLLATE "default"
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for Employees
-- ----------------------------
DROP TABLE IF EXISTS "public"."Employees";
CREATE TABLE "public"."Employees" (
"Id" int8 DEFAULT nextval('"Employees_Id_seq"'::regclass) NOT NULL,
"EmployeeGroupId" int8 DEFAULT
nextval('"Employees_EmployeeGroupId_seq"'::regclass) NOT NULL,
"FirstName" varchar(255) COLLATE "default",
"LastName" varchar(255) COLLATE "default",
"CivicNumber" int4,
"CivicNumberAlias" int4,
"StreetName" varchar(255) COLLATE "default",
"City" varchar(255) COLLATE "default",
"PostalCode" varchar(255) COLLATE "default",
"UserAcessLevel" int8 DEFAULT
nextval('"Employees_UserAcessLevel_seq"'::regclass) NOT NULL,
"Username" varchar(255) COLLATE "default",
"Password" varchar(255) COLLATE "default",
"Timestamp" date
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for PhoneNumberType
-- ----------------------------
DROP TABLE IF EXISTS "public"."PhoneNumberType";
CREATE TABLE "public"."PhoneNumberType" (
"Id" int8 DEFAULT nextval('"PhoneNumberType_Id_seq1"'::regclass) NOT NULL,
"PhoneNumberType" varchar(150) COLLATE "default" NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for SystemAcessLevel
-- ----------------------------
DROP TABLE IF EXISTS "public"."SystemAcessLevel";
CREATE TABLE "public"."SystemAcessLevel" (
"Id" int8 DEFAULT nextval('"SystemAcessLevel_Id_seq"'::regclass) NOT NULL,
"AcessLevel" varchar(255) COLLATE "default" NOT NULL
)
WITH (OIDS=FALSE);
Here is my error generating statement:
CREATE TABLE "public"."NewTable" (
"Id" serial8 NOT NULL,
"EmployeeId" int8 NOT NULL,
"PhoneNumberTypeId" int8 NOT NULL,
"PhoneNumber" varchar(16) NOT NULL,
PRIMARY KEY ("Id"),
CONSTRAINT "phone_fk_emp_id" FOREIGN KEY ("EmployeeId")
REFERENCES "public"."Employees" ("Id") ON DELETE NO ACTION ON UPDATE
CASCADE,
CONSTRAINT "phone_fk_type_id" FOREIGN KEY ("PhoneNumberTypeId")
REFERENCES "public"."PhoneNumberType" ("Id") ON DELETE NO ACTION ON
UPDATE CASCADE
)
WITH (OIDS=FALSE)
;
As it turns out the problem was identifying the
EmployeeGroupId
field that was referenced in the Employees table as a second primary key created a conflict when adding the EmployeeDirectory table referencing the same foreing key as a second primary key of the Employees.GroupId field.
In other word seems like PostgreSQL considers second primary key as unique identifiers creating a one to one relationship therefore it considers it as an error to have an additional table referencing the same identifier as a foreing key stated as a second primary key, and please correct me if I am wrong since not an expert when it comes to PostgreSQL.
This however is accepted by Mysql; this is why I was having a hard time figuring out this error.
Every column (or set of columns) that you reference in a foreign key must have a primary key or unique constraint on it.
Otherwise, how could you identify which row the foreign key points to?