Insert empty string value in a foreign key field - sql

I have an error when trying to insert values with a '' in the foreign key field.
I use PostgreSQL v10.
My sql code:
CREATE TABLE meas_name (
nopol varchar(2) NOT NULL,
cchim varchar(10) NOT NULL,
ncon varchar(30) NOT NULL,
PRIMARY KEY (nopol)
);
CREATE TABLE main_device (
ntypapp smallint NOT NULL,
no_main smallint NOT NULL,
lib_main varchar(25),
nopol varchar(2),
no_chrono smallint,
PRIMARY KEY (no_main,ntypapp)
);
ALTER TABLE main_device ADD CONSTRAINT fk_maindevice_measname FOREIGN KEY (nopol) REFERENCES meas_name(nopol) ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE;
When i insert something in measure with a known deviceno I have this error:
insert into main_device values
(1, 1, 'TST LASER','',1578)
ERROR: insert or update on table « main_device » violates foreign key constraint « fk_maindevice_measname »
DETAIL: Key (nopol) = () is not present in table « meas_name ».
I have tested it on: https://www.db-fiddle.com/f/fBnNSYWU8qZwFbmEoU5dce/1
There was no issue on Oracle database, but I don't know much about Postgres, Is there any limitation? How can I manage this?

An empty string is not NULL. Use NULL:
insert into main_device (ntypapp, no_main, lib_main, nopol, no_chrono)
values (1, 1, 'TST LASER', NULL, 1578);
A NULL value does not need to match the foreign key constraint (in this context, NULL means "no value"). However, an empty string is a valid value and the database expects a matching row in the referenced table.
I also added the explicit column names because that is a best-practice.

Related

SQL The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Score_Gebruikersnaam"

I have a create script for my SQL database (see below). Everything works fine except when I run the INSERT INTO Scores() I get an error.
The error I get is:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Score_Gebruikersnaam". The conflict occurred in database "gamescores", table "dbo.Players", column 'gebruikersnaam'
I don't understand what I'm doing wrong so please help me :)
I already tried to drop the database first and then run the rest of the script but that didn't help. I think something went wrong with the foreign key...
Thanks!
USE master;
GO
DROP DATABASE IF EXISTS [gamescores];
CREATE DATABASE gamescores;
GO
USE gamescores;
GO
SET DATEFORMAT dmy;
CREATE TABLE [Players]
(
[gebruikersnaam] VARCHAR(75) NOT NULL,
[voornaam] VARCHAR(75) NOT NULL,
[achternaam] VARCHAR(75) NOT NULL,
[emailadres] VARCHAR(75) NOT NULL,
[geboortdatum] DATE NOT NULL
);
CREATE TABLE [Scores]
(
[scoreID] INT IDENTITY(1,1) NOT NULL,
[gebruikersnaam] VARCHAR(75) NOT NULL,
[aantalScore] INT NOT NULL,
[datum] DATE NOT NULL
);
ALTER TABLE [Players]
ADD CONSTRAINT [PK_Speler]
PRIMARY KEY (gebruikersnaam);
ALTER TABLE [Scores]
ADD CONSTRAINT [PK_Score]
PRIMARY KEY (scoreID);
ALTER TABLE [Players]
ADD CONSTRAINT [AK_Speler_Emailadres]
UNIQUE (emailadres)
ALTER TABLE [Scores]
ADD CONSTRAINT [FK_Score_Gebruikersnaam]
FOREIGN KEY (gebruikersnaam) REFERENCES Players(gebruikersnaam);
GO
INSERT INTO Players([gebruikersnaam], [voornaam], [achternaam], [emailadres], [geboortdatum])
VALUES ('apraundlin1', 'Angelle', 'Praundlin', 'apraundlin1#mapy.cz', '15-9-1997'),
('rnoore3', 'Rebekah', 'Noore', 'rnoore3#vk.com', '9-10-1987'),
('nplevinh', 'Nicolais', 'Plevin', 'nplevinh#mediafire.com', '18-3-2001');
-- SCORE table vullen
INSERT INTO Scores([gebruikersnaam], [aantalScore], [datum])
VALUES ('rsprasen0', 551, '15-5-2021'),
('fwhawell8', 309, '8-4-2021'),
('rgravett9', 1063, '16-11-2021');
You got an error because the database schema, though a foreign key, enforces that a player referenced in the scores table must first exist in the players table. Add the player to the players table, before trying to update their score in the scores table.

Integrity Constraint violated error when trying to insert into tables

I need a new set of eyes to help me understand what I'm doing wrong here!
I created these tables:
CREATE TABLE bankkund(
PNR VARCHAR2(11) PRIMARY KEY,
FNAMN VARCHAR2(25) NOT NULL,
ENAMN VARCHAR2(25) NOT NULL,
PASSWD VARCHAR2(16) NOT NULL,
UNIQUE(PASSWD));
CREATE TABLE konto(
KNR NUMBER(8)PRIMARY KEY,
KTNR NUMBER(6)NOT NULL,
REGDATUM DATE NOT NULL,
SALDO NUMBER(10,2),
FOREIGN KEY(ktnr) REFERENCES kontotyp(ktnr));
CREATE TABLE kontoägare(
RADNR NUMBER(9)PRIMARY KEY,
PNR VARCHAR2(11)NOT NULL,
KNR NUMBER(8)NOT NULL,
FOREIGN KEY(pnr) REFERENCES bankkund(pnr),
FOREIGN KEY(knr) REFERENCES konto(knr));
then this sequence:
create sequence radnr_seq
start with 1
increment by 1;
and then whenever I want to insert the following values I get an integrity constraint error:
INSERT INTO kontoägare(radnr,pnr,knr)
VALUES(radnr_seq.NEXTVAL,'540126-1111',123);
INSERT INTO kontoägare(radnr,pnr,knr)
VALUES(radnr_seq.NEXTVAL,'691124-4478',123);
INSERT INTO kontoägare(radnr,pnr,knr)
VALUES(radnr_seq.NEXTVAL,'540126-1111',5899);
INSERT INTO kontoägare(radnr,pnr,knr)
VALUES(radnr_seq.NEXTVAL,'691124-4478',8896);
COMMIT;
What am I missing??
The error you're seeing is expected. Table "kontoägare" has 2 foreign keys: FOREIGN KEY(pnr) REFERENCES bankkund(pnr)and FOREIGN KEY(knr) REFERENCES konto(knr)). This means that the values for "pnr" need to exist in table "bankkund" and the value for "knr" needs to exist in "konto". If either of those values do not exist when you do the insert, an integrity constraint error will be raised.

ERROR: violates foreign key constraint, key is not present in parent table (but it is??)

I know this question has been asked many times, but none of the answers have solved my issue.
I am creating a database for a uni assignment, using PostgreSQL through pgadmin 4, and I have a table named "staff" populated with staff members with a primary key of "staffid". I then have another table named "client_international", which includes a foreign key of "staffid" which relates to the staff tables primary key.
When trying to insert into the client table, I am getting the following error:
ERROR: insert or update on table "client_international" violates foreign key constraint "intclient_staff_fkey"
DETAIL: Key (staffid)=(100000024) is not present in table "staff".
SQL state: 23503
I am certain that that '100000024' key is in the staff table.. yet I still get the error. Any suggestions? Below I will paste the code I used to create the staff and client tables, in case anyone notices an error in them.
Staff table:
CREATE SEQUENCE staff_seq
start 100000000
increment 1;
CREATE TABLE staff
(
staffid integer default nextval('staff_seq'),
firstname varchar(20) NOT NULL,
lastname varchar(20) NOT NULL,
"position" varchar(20) NOT NULL,
mobile varchar(20) NOT NULL,
email varchar(100) NOT NULL,
"location" integer NOT NULL,
CONSTRAINT staff_pkey PRIMARY KEY (staffid)
);
Client table:
CREATE SEQUENCE client_seq
start 200000000
increment 1;
CREATE TABLE client
(
clientid integer default nextval('client_seq'),
company varchar(100) NOT NULL,
sector varchar(100) NOT NULL,
pointofcontact varchar(20) NOT NULL,
mobile varchar(20) NOT NULL,
email varchar(100) NOT NULL,
approvalstatus boolean default (false),
"location" integer NOT NULL,
staffid integer NOT NULL,
CONSTRAINT client_pkey PRIMARY KEY (clientid)
);
CREATE TABLE client_international
(
CONSTRAINT client_international_pkey PRIMARY KEY (clientid)
) INHERITS ("client");
ALTER TABLE client
ADD CONSTRAINT client_location_fkey FOREIGN KEY ("location") REFERENCES "location" (locationid),
ADD CONSTRAINT client_staff_fkey FOREIGN KEY (staffid) REFERENCES staff (staffid);
ALTER TABLE client_international
ADD CONSTRAINT intclient_location_fkey FOREIGN KEY ("location") REFERENCES "location" (locationid),
ADD CONSTRAINT intclient_staff_fkey FOREIGN KEY (staffid) REFERENCES staff (staffid);
I get the error when running the following statements:
INSERT INTO client_international(company, sector, pointofcontact, mobile, email, approvalstatus, "location", staffid)
VALUES ('Moores Dogs', 'Border Patrol', 'Carol Moore', '07911 653453', 'jenkinsj#k9solutions.co.uk', 'false', '500000001', '100000024');
Here's a screenshot of the entry in the staff table, showing that it's definitely in there:
Foreign keys aren't "inherited".
Quote from the manual
A serious limitation of the inheritance feature is that [...] foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint.
(emphasis mine)
So what you are trying to do, simply isn't supported.

Foreign key in SQL Server - which style to use?

In my database, I have the following code
CREATE TABLE [Users]
(
userID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Username VARCHAR(255),
Password VARCHAR(255)
);
CREATE TABLE [Image]
(
ImageID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Imagename VARCHAR,
userID INT,
FOREIGN KEY(userID) REFERENCES Users (userID)
);
However, here on stackOverflow and multiple other sites, people suggest writing it like this:
CREATE TABLE [Users]
(
userID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Username VARCHAR(255),
Password VARCHAR(255)
);
CREATE TABLE [Image]
(
ImageID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Imagename VARCHAR,
userID INT,
CONSTRAINT fk_Users
FOREIGN KEY(userID) REFERENCES Users (userID)
);
I've tried executing both statements, and it seems to do the same..
What am I missing, what's the trick when writing CONSTRAINT fk_Users?
Writing constraint allows you to name the constraint.
In general, you notice this when the constraint is violated. If you have an opportunity to name the constraint, the error message will make more sense.
For instance, this:
The INSERT statement conflicted with the FOREIGN KEY constraint
"fk_image_userId". The conflict occurred in database "rextester",
table "dbo.Users", column 'userID'.
The statement has been terminated.
is clearer than this:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK__Image__userID__09211CD4". The conflict occurred in database
"rextester", table "dbo.Users", column 'userID'.
The statement has been terminated.
In addition, the constraint name is used in the alter table when you drop or disable the constraint, so having a reasonably named constraint makes that easier.

Reusing a constraint while creating a table

While creating a table how can I reuse a constraint that has been mentioned for a previous column?
create table ticket_details(
from_stn char(3)
constraint chk check(from_stn in ('vsh','mas','ndl'))
constraint nn NOT NULL,
to_stn char(3)
constraint nn1 NOT NULL, (instead of crea)
seat_no number(3)
constraint PK primary key,
);
A domain constraint will be enforced on any instance of the domain. Also: upon change, you'll have to change it in only one place. (the syntax might differ slightly between implementations)
CREATE DOMAIN THE_STN CHAR(3) constraint THE_STN_check_da_value check(VALUE in ('vsh','mas','ndl'))
;
CREATE table ticket_details
( seat_no INTEGER NOT NULL PRIMARY KEY
, from_stn THE_STN NOT NULL
, to_stn THE_STN
);
INSERT INTO ticket_details(seat_no,from_stn,to_stn) VALUES (1, 'vsh', 'ndl' ); -- succeeds
INSERT INTO ticket_details(seat_no,from_stn,to_stn) VALUES (2, 'vsh', NULL ); -- succeeds
INSERT INTO ticket_details(seat_no,from_stn,to_stn) VALUES (2, 'lol', 'mas' ); -- fails
Reusing a constraint for another column is not possible. You have to define it for other column if you want