I can't insert null on a Foreign Key - sql

I've tried to search but nothing works, and I don't know what to do.
There's a table with two foreign keys, one of which can be null. According to what I've searched, it's perfectly fine to have null foreign keys. But no matter what, when I try to insert a null in that value, it fails. It says:
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.
Here is the code of the table. The FK that I want to be null is idPedido
CREATE TABLE PAGOS(
fechaLimite DATE,
cuantia NUMBER NOT NULL,
fechaInicio DATE DEFAULT SYSDATE,
fechaLiquidacion DATE,
idPago VARCHAR(8) NOT NULL,
dni VARCHAR(14) NOT NULL,
tipoPago VARCHAR(7) DEFAULT 'OTRO' CHECK(tipoPAGO IN('MENSUAL','PEDIDO','OTRO')),
idPedido VARCHAR2(10),
PRIMARY KEY(idPago),
FOREIGN KEY(dni) REFERENCES MIEMBROS ON DELETE SET NULL,
FOREIGN KEY(idPedido) REFERENCES PEDIDOS ON DELETE SET NULL
);
There are some triggers and such to add sequences for the idPago value.
Here is the code of the procedure that creates a new item to the table:
create or replace PROCEDURE CREAR_PAGO(
new_fechaLimite IN PAGOS.fechaLimite%TYPE ,
new_cuantia IN PAGOS.cuantia%TYPE,
new_fechaInicio IN PAGOS.fechaInicio%TYPE,
new_fechaLiquidacion IN PAGOS.fechaLiquidacion%TYPE,
new_dni IN PAGOS.dni%TYPE,
new_tipoPago IN PAGOS.tipoPago%TYPE,
new_idPedido IN PAGOS.idPedido%TYPE
)
IS
BEGIN
INSERT INTO PAGOS(fechaLimite,cuantia,fechaInicio,fechaLiquidacion,dni,tipoPago,idPedido) VALUES(new_fechaLimite,new_cuantia,new_fechaInicio,new_fechaLiquidacion,new_dni,new_tipoPago,new_idPedido);
END CREAR_PAGO;
And here is me trying to insert a new element:
execute CREAR_PAGO('01012020',40,'01012010',null,49035480D,null,null);
I've already tried to put both "NULL" and "DEFAULT NULL" in the table code after idPedido's type and nothing works
Please I need help

It looks like the primary key for your table is idPago, but I don't see it in your insert statement. If that is the case, it would appear that your issue is trying to add a record with no primary key...not that the foreign key is null.

Related

Activate foreign key constraints error in dataGrip

I'm working with DataGrip and sqlite.
I have a table suppliers and another named products :
CREATE TABLE Suppliers (id INTEGER NOT NULL PRIMARY KEY,
nom TEXT,
siege_social TEXT);
CREATE TABLE Products (id INTEGER NOT NULL PRIMARY KEY,
nom TEXT,
prix REAL,
supplier INTEGER,
FOREIGN KEY (supplier) REFERENCES Suppliers(id)
);
I tried PRAGMA foreign_keys = ON; to activate the foreign keys constraint as my teacher do.
However when I try to insert a product while having the supplier table empty, I get no error :
INSERT INTO Products values (1, "Lunettes Cobra", 30, 1);
I expected this : FOREIGN KEY constraint failed
Do you know how I could make it raise an error for this ?
Thanks !
Executing pragma statement enables that setting only for currents session. Console and editor perform in different sessions.
Just go to advanced tab of the data source settings and set it there. It'll be applied for all sessions.
#forpas asked for the whole code so I deleted all the existing tables and used this code :
PRAGMA foreign_keys = ON;
CREATE TABLE Suppliers (id INTEGER NOT NULL PRIMARY KEY,
nom TEXT,
siege_social TEXT);
CREATE TABLE Products (id INTEGER NOT NULL PRIMARY KEY,
nom TEXT,
prix REAL,
supplier INTEGER,
FOREIGN KEY (supplier) REFERENCES Suppliers(id)
);
INSERT INTO Products values (2, "Lunettes Cobra", 30, 1);
And everything worked as expected.
[2021-05-23 12:02:26] [19] [SQLITE_CONSTRAINT_FOREIGNKEY] A foreign key constraint failed (FOREIGN KEY constraint failed)
#forpas was right again, the fact that I created the table before activating the foreign_keys was not the problem. I used 2 console, one for creating the table and another for inserting values. I only activated foreign_keys in the first one. I thought it was activated in the database but it's console related.

SQLite - NOT NULL constraint failed

I am trying to create a simple SQLite database that will allow me to store email addresses and timestamps. I have created the table like this:
$sql =<<<EOF
CREATE TABLE ENTRIES
(ID INT PRIMARY KEY NOT NULL,
EMAIL EMAIL NOT NULL,
TIMESTAMP DATETIME DEFAULT CURRENT_TIMESTAMP);
EOF;
And I am trying to insert an email like this:
$sql =<<<EOF
INSERT INTO ENTRIES (EMAIL)
VALUES (test#test.com);
EOF;
I am getting an error
NOT NULL constraint failed: ENTRIES.ID
I am assuming this is to do with the ID and autoincrement? I have read the docs and it advises against using autoincrement. Where am I going wrong?
The docs say:
If a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID.
And because it becomes an alias for the ROWID, it's not necessary to explicitly specify a value.
You have INT PRIMARY KEY, not INTEGER PRIMARY KEY. If you change it to INTEGER PRIMARY KEY, it works the way you expect.

Multiple constraints on a single column

I want to ensure that only the values 'Expert', 'Average' or 'Adequate' are entered into the levelOfExpertise column of this table, however whenever I do try an enter one of those values, it returns an error saying the value entered is too short. Here is the create table query for this particular table. The the column I am referring to is levelOfExpertise:
CREATE TABLE MusicianInstrument
(
musicianNo varchar(5) not null
CONSTRAINT MI_PK1 REFERENCES Musician(musicianNo),
instrumentName varchar(50) not null
CONSTRAINT MI_PK2 REFERENCES Instrument(instrumentName),
levelOfExpertise varchar(50),
CONSTRAINT levelOfExpertise CHECK (levelOfExpertise = 'Expert', 'Adequate', 'Avergage'),
PRIMARY KEY(musicianNo,instrumentName)
);
Any ideas how I can ensure only those three values (Expert, Adequate or Average) can be entered?
Thanks
Use the IN operator
CHECK (levelOfExpertise IN ('Expert','Adequate','Avergage'))
Try to change your CHECK constraint as following:
CONSTRAINT levelOfExpertise CHECK (levelOfExpertise IN ('Expert','Adequate','Avergage'))
I suppose that you use sql server as RDBMS.

SQL Server unique constraint issue on unicode characters

I have my table definition as follows:
create table [Language](
Id int primary key identity,
Code varchar(11) not null unique,
NativeName nvarchar(50) not null unique
)
And then, I have a long list of statements that insert into that table. The problem is that some of the insert statements conflict on my NativeName column's unique constraint. The weird thing is that the content is not unique at all. For example, if I only insert the following with the table empty:
insert into Language (Code, NativeName) values('am', N'አማርኛ');
insert into Language (Code, NativeName) values('dv', N'ދިވެހިބަސް‏');
I get for the second insert.
Violation of UNIQUE KEY constraint 'UQ__Language__EB1957A5F98D1F9C'. Cannot insert duplicate key in object 'dbo.Language'. The duplicate key value is (ދިވެހިބަސް‏).
Does anyone know why unicode characters are causing these issues?
Try declaring the NativeName column with a more specific (binary) collation.
eg:
NativeName nvarchar(50) collate SQL_Latin1_General_CP437_BIN not null unique

Why does this MySQL Create Table statement fail?

Using mySQLAdmin tool, I try to create a table. The tool generates the SQL statement, and then replorts a "Can't create table" with no other clue on what error it is!
Here it is :
CREATE TABLE `C121535_vubridge`.`Products` (
`pr_ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`pr_Name` VARCHAR(45) NOT NULL,
`pr_Type` VARCHAR(2) NOT NULL COMMENT 'H=Hand Series V=VuBridge software E=Event Subs S=Sponsoring',
`pr_AuthorID` INTEGER UNSIGNED COMMENT '= m_ID (for Bridge Hand Series',
`pr_SponsorID` INTEGER UNSIGNED NOT NULL,
`pr_DateCreation` DATETIME NOT NULL,
`pr_Price` FLOAT NOT NULL,
`pr_DescriptionText` TEXT,
`pr_Description` VARCHAR(245),
PRIMARY KEY (`pr_ID`),
CONSTRAINT `FK_prAuthor` FOREIGN KEY `FK_prAuthor` (`pr_AuthorID`)
REFERENCES `Members` (`m_ID`)
ON DELETE SET NULL
ON UPDATE NO ACTION,
CONSTRAINT `FK_Sponsor` FOREIGN KEY `FK_Sponsor` (`pr_SponsorID`)
REFERENCES `Members` (`m_ID`)
ON DELETE SET NULL
ON UPDATE NO ACTION
) ENGINE = InnoDB;
Can someone help?
The CREATE TABLE works for me if I omit the foreign key references:
CREATE TABLE `Products` (
`pr_ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`pr_Name` VARCHAR(45) NOT NULL,
`pr_Type` VARCHAR(2) NOT NULL COMMENT 'H=Hand Series V=VuBridge software E=Event Subs S=Sponsoring',
`pr_AuthorID` INTEGER UNSIGNED COMMENT '= m_ID (for Bridge Hand Series',
`pr_SponsorID` INTEGER UNSIGNED NOT NULL,
`pr_DateCreation` DATETIME NOT NULL,
`pr_Price` FLOAT NOT NULL,
`pr_DescriptionText` TEXT,
`pr_Description` VARCHAR(245),
PRIMARY KEY (`pr_ID`)
)
...so I'm inclined to believe that C121535_vubridge.MEMBERS does not already exist. C121535_vubridge.MEMBERS needs to be created before the CREATE TABLE statement for the PRODUCTS table is run.
Just split up the create table and try one part at the time. This way you should be able to identify a single line that it fails on.
I do note in the reference manual that if a symbol subclause is given for the CONSTRAINT clause (in your case, the back-quoted strings before FOREIGN KEY in each clause, FK_prAuthor and FK_Sponsor) have to be unique over the database. Are they? If not, that symbol can be omitted and InnoDB will assign then automatically.
Similarly, the tables your FKs refer to may not have the structure that this create statement expects.