Unique Field - no unique constraint matching given keys - postgresql

I have three tables in a postgresql database, namely tec_configurations, tep_cores and tep2tec_bindings. The table tec2tep_bindings references to the primary key fields of the first two tables. The related create statements per table are listed in below sql snippets 2,3 and 4. I get the error indicated in the 1st snippet below. Could you please tell me how I can fix this error? The 'id' field in table TEC_CONFIGURATIONS is already unique since it is a primary key. So, I don't see a reason to get this error message.
SNIPPET 1 (Error message):
ERROR: there is no unique constraint matching given keys for referenced table
"tec_configurations"
SNIPPET 2 (TABLE tec_configurations):
CREATE TABLE IF NOT EXISTS TEC_CONFIGURATIONS (
ID SERIAL PRIMARY KEY,
TEC_ID INT NOT NULL,
HANDLER_MAC TEXT NOT NULL,
PRIMARY_MAC TEXT,
SECONDARY_MAC TEXT,
TERTIARY_MAC TEXT,
EXPECTED_FLOWS INT DEFAULT 0,
VERSION INT DEFAULT 0,
UUID TEXT DEFAULT NULL );
SNIPPET 3 (TABLE tep_cores):
CREATE TABLE IF NOT EXISTS TEP_CORES (
ID SERIAL PRIMARY KEY,
MAC TEXT,
UUID TEXT,
CORE_NO INT DEFAULT 0);
SNIPPET 4 (TABLE tec2tep_bindings)
CREATE TABLE IF NOT EXISTS TEC2TEP_BINDINGS (
ID SERIAL PRIMARY KEY,
TEC_ID_FK INT NOT NULL REFERENCES TEC_CONFIGURATIONS(ID),
TEP_CORE_ID_FK INT NOT NULL REFERENCES TEP_CORES(ID),
REPLICA_RANK INT DEFAULT 0);

Wild guess, since you're issuing create table if not exists rather than create table: one of the tables exists without the needed unique key (e.g. from lack of a primary key).
(If correct, I'd add this note. Some Postgres core devs were hostile to the idea of adding if exists and if not exists constructs, objecting thus: "What is supposed to happen when you create table if not exists, silently "succeed", and the existing table has a schema different from the one you were hoping for?")

Related

Weak Entity postgresql

I want to create a table with primary key email,nro being nro a sequential number for each email ex:
user1#e.com, 1
user1#e.com, 2
user2#e.com, 1
create table proposta_de_correcao(
email varchar(255) not null,
nro serial not null,
unique(nro,email),
PRIMARY KEY(nro, email),
FOREIGN KEY (email) REFERENCES Utilizador(email),
);
But I get the following error:
ERROR: there is no unique constraint matching given keys for referenced table "proposta_de_correcao"
I have already tried:
unique(nro,email)
contraint keys unique(nro,email)
Two things here, to help with your problem:
Why nro is serial if is not a sequential field in your database? serial type is used when you want that the field be incremented automatically (as in single integer primary keys). Maybe is better that you put an int type here.
You have in your table no unique constraints. If you create a fiddle, you can see that code runs fine:
CREATE TABLE proposta_de_correcao(
email VARCHAR(255) not null,
nro SERIAL not null,
UNIQUE(nro, email),
PRIMARY KEY(nro, email)
-- FOREIGN KEY (email) REFERENCES Utilizador(email)
);
INSERT INTO proposta_de_correcao VALUES ('user1#e.com', 1);
INSERT INTO proposta_de_correcao VALUES ('user1#e.com', 2);
INSERT INTO proposta_de_correcao VALUES ('user2#e.com', 1);
So, I can conclude that when you want to add the constraint, your database already have duplicated data in those two columns. Try to create in a test database the data mentioned above and you will see that runs perfectly.
I just removed the foreign key constraint to allow to run the code as we don't have the referenced table in example and we can consider that the referenced table don't have influence on the problem cited on answer.
Here's the fiddle.

PostgreSQL/PGAdmin4 ERROR: there is no unique constraint matching given keys for referenced table

PostgreSQL/PGAdmin4 ERROR: there is no unique constraint matching given keys for referenced table
This is the ‘schema’ I’m trying to code into PGAdmin4/Postgresql:
http://i.imgur.com/xPEu8Sh.jpg
I was able to convert all tables, except “QUALIFICATIONS”.
I tried to process the following query:
create table REGISTRATION(
StudentID int,
SectionNo int,
Semester varchar(16),
foreign key(StudentID) references Student(StudentID),
foreign key (SectionNo, Semester) references Section(SectionNo, Semester),
primary key(studentID, SectionNo, Semester)
);
I received the following message:
ERROR: there is no unique constraint matching given keys for referenced table "section"
These are the foreign and primary I have in the table SECTION
PKEY: i.imgur.com/BcUNKug.jpg
FKEY: i.imgur.com/D8B8hRW.jpg
Code of SECTION table:
CREATE TABLE class_scheduling_01.section
(
sectionno integer NOT NULL,
semester character varying(16) COLLATE pg_catalog."default" NOT NULL,
courseid character varying(16) COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT section_pkey PRIMARY KEY (sectionno, semester, courseid),
CONSTRAINT section_sectionno_key UNIQUE (sectionno),
CONSTRAINT section_courseid_fkey FOREIGN KEY (courseid)
REFERENCES class_scheduling_01.course (courseid) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
I additionally ran the command: ALTER TABLE section ADD UNIQUE (sectionno);
Since none of the attributes seemed to be repeating itself.
Despite all this I’m getting:
ERROR: there is no unique constraint matching given keys for referenced table "section" Query returned successfully in 642 msec.
Edit: I've gone back to the COURSE table and made courseID a unique constraint. I still get the same message. SECTION table has a composite primary key made up of 3 columns. As seen in the first picture linked, out of all the values, only SECTION.sectionno is the only column with unique/non-repeating values.
2nd edit: I decided to create the table "REGISTRATION" one step at a time, and make the foreign keys last with alter table command.
I was able to make the columns StudentID andd SectionNo foreign keys to their respective columns. When I tried to make REGISTRATION.semester a foreign key to SECTION.semester I got the error message again.
alter table REGISTRATION add foreign key (semester) references section(semester);
As seen in the image I linked Semester value, is repeated; despite this, am I still required to make it unique? Or do I make a unique command assigning all 3 columns (of SECTION) together as unique, instead of just 1? If so, how?
This
foreign key (SectionNo, Semester) references Section(SectionNo, Semester),
requires that there be a unique constraint on the pair of columns SectionNo and Semester.
CREATE TABLE class_scheduling_01.section
(
sectionno integer NOT NULL,
semester character varying(16) COLLATE pg_catalog."default" NOT NULL,
courseid character varying(16) COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT section_pkey PRIMARY KEY (sectionno, semester, courseid),
CONSTRAINT section_sectionno_key UNIQUE (sectionno),
CONSTRAINT section_courseid_fkey FOREIGN KEY (courseid)
REFERENCES class_scheduling_01.course (courseid) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION,
-- Unique constraint on the pair
CONSTRAINT your_constraint_name UNIQUE (SectionNo, Semester)
);
That change should let these SQL statements succeed. I didn't check to see whether that's a good idea.
SQL is case insensitive.
I understand what you mean, but this is a bad way to think about it.
PostgreSQL folds unquoted identifiers to lowercase. So PostgreSQL would treat the identifiers SQL, Sql, and sql as if they were all sql. A quoted or delimited identifier, like "Select" always refers to either a table or a column; it's never interpreted as a keyword. Quoted identifiers are case-sensitive. You can't successfully refer to the table "Select" as select.

How do I create a check to make sure a value exists in another table?

Right now I have two tables, one that contains a compound primary key and another that that references one of the values of the primary key but is a one-to-many relationship between Product and Mapping. The following is an idea of the setup:
CREATE TABLE dev."Product"
(
"Id" serial NOT NULL,
"ShortCode" character(6),
CONSTRAINT "ProductPK" PRIMARY KEY ("Id")
)
CREATE TABLE dev."Mapping"
(
"LookupId" integer NOT NULL,
"ShortCode" character(6) NOT NULL,
CONSTRAINT "MappingPK" PRIMARY KEY ("LookupId", "ShortCode")
)
Since the ShortCode is displayed to the user as a six character string I don't want to have a another table to have a proper foreign key reference but trying to create one with the current design is not allowed by PostgreSQL. As such, how can I create a check so that the short code in the Mapping table is checked to make sure it exists?
Depending on the fine print of your requirements and your version of Postgres I would suggest a TRIGGER or a NOT VALID CHECK constraint.
We have just discussed the matter in depth in this related question on dba.SE:
Disable all constraints and table checks while restoring a dump
If I understand you correctly, you need a UNIQUE constraint on "Product"."ShortCode". Surely it should be declared NOT NULL, too.
CREATE TABLE dev."Product"
(
"Id" serial NOT NULL,
"ShortCode" character(6) NOT NULL UNIQUE,
CONSTRAINT "ProductPK" PRIMARY KEY ("Id")
);
CREATE TABLE dev."Mapping"
(
"LookupId" integer NOT NULL,
"ShortCode" character(6) NOT NULL REFERENCES dev."Product" ("ShortCode"),
CONSTRAINT "MappingPK" PRIMARY KEY ("LookupId", "ShortCode")
);
Your original "Product" table will allow this INSERT statement to succeed, but it shouldn't.
insert into dev."Product" ("ShortCode") values
(NULL), (NULL), ('ABC'), ('ABC'), ('ABC');
Data like that is just about useless.
select * from dev."Product"
id ShortCode
--
1
2
3 ABC
4 ABC
5 ABC

PostgreSQL: NULL value in foreign key column

In my PostgreSQL database I have the following tables (simplified):
CREATE TABLE quotations (
receipt_id bigint NOT NULL PRIMARY KEY
);
CREATE TABLE order_confirmations (
receipt_id bigint NOT NULL PRIMARY KEY
fk_quotation_receipt_id bigint REFERENCES quotations (receipt_id)
);
My problem now reads as follows:
I have orders which relate to previous quotations (which is fine 'cause I can attach such an order to the quotation referenced by using the FK field), but I also have placed-from-scratch orders without a matching quotation. The FK field would then be NULL, if the database let me, of course. Unfortunately, I get an error when trying to set fk_quotation_receipt_id to NULL in an INSERT statement because of a violated foreign key constraint.
When designing these tables I was still using PgSQL 8.2, which allowed NULL values. Now I've got 9.1.6, which does not allow for this.
What I wish is an optional (or nullable) foreign key constraint order_confirmations (fk_quotation_receipt_id) → quotations (receipt_id). I can't find any hints in the official PgSQL docs, and similar issues posted by other users are already quite old.
Thank you for any useful hints.
Works for me in 9.3 after correcting a missing comma. I'm sure it will work also in 9.1
create table quotations (
receipt_id bigint not null primary key
);
create table order_confirmations (
receipt_id bigint not null primary key,
fk_quotation_receipt_id bigint references quotations (receipt_id)
);
insert into order_confirmations (receipt_id, fk_quotation_receipt_id) values
(1, null);
Confirmation will include:
INSERT 0 1

How to tell PostgreSQL not to verify datatype

I have a table like:
CREATE TABLE test(
id integer not null default nextval('test_id_seq'::regclass),
client_name_id integer not null
);
Foreign-key constraints:
"test_client_name_id_fkey" FOREIGN KEY (client_name_id) REFERENCES company(id) DEFERRABLE INITIALLY DEFERRED
and company table:
CREATE TABLE company(
id integer not null default nextval('company_id_seq'::regclass),
company_name character varying(64) not null
)
Now I have trigger on test table which fetch id from company table using provided value client_name_id which is string by matching it with company_name. but when I insert record PostgreSQL return error that client_name_id is string and int required which is true.
How can I tell PostgreSQL not to verify inserted row as I have taken care of it in my triggers.
What you are trying to do is very unorthodox. Are you sure, this is what you want? Of course, you cant enter a string (with non-digits) into an integer column. No surprise there, right? If you want to enter the text instead, you'd have to add a text column instead - with a fk-constraint to company(company_name) if you want to match your current layout.
ALTER TABLE test ALTER DROP COLUMN client_name_id; -- drops fk constraint, too
ALTER TABLE test ADD COLUMN client_name REFERENCES company(company_name);
You would need a UNIQUE constraint on company.company_name to allow this.
However, I would advise to rethink your approach. Your table layout seems proper as it is. The trigger is the unconventional element. Normally, you would reference the primary key, just like you have it now. No trigger needed. To get the company name, you would join the table in a SELECT:
SELECT *
FROM test t
JOIN company c ON t.client_name_id = c.id;
Also, these non-standard modifiers should only be there if you need them: DEFERRABLE INITIALLY DEFERRED. Like, when you have to enter values in table test before you enter the referenced values in table company (in the same transaction).