Foreign key BIGSERIAL NULL Postgres - mysql

I can not insert a record in the POSTGRES database, I want the foreign key to be null.
My table:
CREATE TABLE sad_avaliado (
id BIGSERIAL NOT NULL,
tenant_id INT8 NOT NULL,
funcionario_id BIGSERIAL NOT NULL,
epoca_id BIGSERIAL NOT NULL,
cca_id BIGSERIAL,
avaliador_id BIGSERIAL NOT NULL,
apagado boolean NOT NULL,
PRIMARY KEY (id)
);
alter table sad_avaliado add constraint sad_funcionario_fkey foreign key (funcionario_id) references sad_funcionario;
alter table sad_avaliado add constraint sad_epoca_fkey foreign key (epoca_id) references sad_epoca;
alter table sad_avaliado add constraint sad_cca_fkey foreign key (cca_id) references sad_cca;
alter table sad_avaliado add constraint sad_avaliador_fkey foreign key (avaliador_id) references sad_avaliador;
My SQL Insert:
INSERT INTO public.sad_avaliado(
id, tenant_id, funcionario_id, epoca_id, cca_id, avaliador_id, apagado)
VALUES (1, 1, 1, 1, null, 1, false);
My Error:
ERROR: null value in column "cca_id" violates not-null constraint

The foreign key references for BIGSERIAL should use BIGINT:
CREATE TABLE sad_avaliado (
id BIGSERIAL NOT NULL,
tenant_id INT8 NOT NULL,
funcionario_id BIGINT NOT NULL,
epoca_id BIGINT NOT NULL,
cca_id BIGINT,
avaliador_id BIGINT NOT NULL,
apagado boolean NOT NULL,
PRIMARY KEY (id)
);
I think this is the one exception to the notion that foreign key references should have the same type as the primary key. I mean, the underlying type is the same, but BIGSERIAL is used to specify that it is auto-incrementing (other databases use a separate keyword such as auto_increment or identity).

bigserial is meant for autoincremented id columns and it has default "not null" and creates one sequence.
And you should not specify your id in insert statements as it is inserted as default with nextval()
see this example
test=# create table test01 ( id bigserial );
CREATE TABLE
test=# \d test01*
Table "public.test01"
Column | Type | Collation | Nullable | Default
--------+--------+-----------+----------+------------------------------------
id | bigint | | not null | nextval('test01_id_seq'::regclass)
Sequence "public.test01_id_seq"
Type | Start | Minimum | Maximum | Increment | Cycles? | Cache
--------+-------+---------+---------------------+-----------+---------+-------
bigint | 1 | 1 | 9223372036854775807 | 1 | no | 1
Owned by: public.test01.id

Use bigint instead of bigserial.

Related

Error Code 1215 Cannot Add Foreign Code Constraint

My code:
CREATE TABLE Horse (
ID SMALLINT UNSIGNED AUTO_INCREMENT,
RegisteredName VARCHAR(15),
PRIMARY KEY (ID)
);
CREATE TABLE Student (
ID SMALLINT UNSIGNED AUTO_INCREMENT,
FirstName VARCHAR(20),
LastName VARCHAR(30),
PRIMARY KEY (ID)
);
CREATE TABLE LessonSchedule (
HorseID SMALLINT UNSIGNED NOT NULL,
StudentID SMALLINT UNSIGNED NOT NULL,
LessonDateTime DATETIME NOT NULL,
Primary Key (HorseID, StudentID, LessonDateTime),
Foreign Key (HorseID) REFERENCES Horse(ID)
ON DELETE CASCADE,
Foreign Key (StudentID) REFERENCES Student(ID)
ON DELETE SET NULL
);
I'm trying to create "LessonSchedule" with these requirements:
HorseID - integer with range 0 to 65 thousand, not NULL, partial primary key, foreign key references Horse(ID)
StudentID - integer with range 0 to 65 thousand, foreign key references Student(ID)
LessonDateTime - date/time, not NULL, partial primary key
If a row is deleted from Horse, the rows with the same horse ID should be deleted from LessonSchedule automatically.
If a row is deleted from Student, the same student IDs should be set to NULL in LessonSchedule automatically.
The create horse table and create student table was given to me.
I am getting the error:
Query failed: ERROR 1215 (HY000) at line 15:
Cannot add foreign key constraint
I tested your table creation statements, and then ran SHOW ENGINE INNODB STATUS. This includes a section that gives more specific information about the reason for the failure.
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2021-11-08 10:31:11 0x700002686000 Error in foreign key constraint of table test/lessonschedule:
Foreign Key (StudentID) REFERENCES Student(ID) ON DELETE SET NULL ):
You have defined a SET NULL condition though some of the
columns are defined as NOT NULL.
This means you can't define a foreign key with ON DELETE SET NULL if the column it is based on is defined with the NOT NULL option (as a PRIMARY KEY column must be).

Unable to insert rows and getting foreign key constraint fails error

I have the following table:
CREATE TABLE IF NOT EXISTS profile_claim_ruling_tasks (
profile_claim_ruling_task_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
account_id BIGINT UNSIGNED NOT NULL,
profile_id BIGINT UNSIGNED NOT NULL,
admin_task_status_id BIGINT UNSIGNED NOT NULL,
profile_claim_ruling_task_ref_id VARCHAR(36) NOT NULL,
profile_claim_ruling_task_requested_at DATETIME NOT NULL,
CONSTRAINT pk_profile_claim_ruling_tasks PRIMARY KEY (profile_claim_ruling_task_id),
CONSTRAINT fk_profile_claim_ruling_task_account_id FOREIGN KEY (account_id) REFERENCES accounts (account_id),
CONSTRAINT fk_profile_claim_ruling_task_profile_id FOREIGN KEY (profile_id) REFERENCES accounts (profile_id),
CONSTRAINT fk_profile_claim_ruling_task_admin_task_status_id FOREIGN KEY (admin_task_status_id) REFERENCES admin_task_statuses (admin_task_status_id),
INDEX idx_profile_claim_ruling_tasks_admin_task_status_id(admin_task_status_id),
CONSTRAINT uc_profile_claim_ruling_tasks_profile_claim_ruling_tasks_ref_id UNIQUE (profile_claim_ruling_task_ref_id)
);
When I do a SELECT * on accounts:
+------------+--------------------------------------+------------+
| account_id | account_ref_id | profile_id |
+------------+--------------------------------------+------------+
| 1 | 521ef2cb-01f9-49f3-a214-42e1514d7dc2 | 1 |
+------------+--------------------------------------+------------+
And when I do a SELECT * on profiles:
+------------+--------------------------------------+
| profile_id | profile_ref_id |
+------------+--------------------------------------+
| 2 | 1d8caa66-e080-4cc6-88ff-a063e576bafa |
| 3 | 619a7ec6-813a-41f0-a1f9-16289893df5d |
| 4 | c50ceb2f-49f0-4319-b115-0a1454593c46 |
| 1 | d6369f9b-b66a-468c-86f9-a7e0abc75b65 |
+------------+--------------------------------------+
So far, so good! But when I run the following insert:
INSERT INTO profile_claim_ruling_tasks (
account_id,
profile_id,
admin_task_status_id,
profile_claim_ruling_task_ref_id,
profile_claim_ruling_task_requested_at
) VALUES (
1,
4,
1,
'4bed7334-e17b-462f-a7e6-454c3b2f5235',
'2018-01-29 13:12:57'
);
I get the following error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`myapp_db`.`profile_claim_ruling_tasks`, CONSTRAINT `fk_profile_claim_ruling_task_profile_id` FOREIGN KEY (`profile_id`) REFERENCES `accounts` (`profile_id`))
What's going on here?!
FOREIGN KEY (profile_id) REFERENCES accounts (profile_id)
You are trying to insert data with profile_id=4 in table profile_claim_ruling_tasks, which is referring to accounts (profile_id).
But, you don't have profile_id=4 in accounts table. You need to populate accounts table first to resolve this issue.
You appear to have an error in your first SHOW CREATE TABLE,
CONSTRAINT fk_profile_claim_ruling_task_profile_id FOREIGN KEY (profile_id) REFERENCES accounts (profile_id),
should be
CONSTRAINT fk_profile_claim_ruling_task_profile_id FOREIGN KEY (profile_id) REFERENCES profiles (profile_id),
IMO.

Assign different muliple foreign key in one table from other table in MySQL

I was planning to make 2 tables for user infomation . The first lager table named userInfo has all data . The second smaller table named loginDetails have the minimum data to log in .
My problem is : I could not assign multiple foreign key .
MySQL said:
#1005 - Can't create table `test`.`logindetails` (errno: 150 "Foreign key constraint is incorrectly formed")
Here is code :
CREATE TABLE userInfo
(
userInfoUserNumber INT(255) UNSIGNED AUTO_INCREMENT UNIQUE NOT NULL,
userInfoUserName VARCHAR(255) UNIQUE NOT NULL,
userInfoPassword VARCHAR(255) NOT NULL,
userInfoFirstName VARCHAR(255) NOT NULL,
userInfoLastName VARCHAR(255) NOT NULL,
userInfoPhoneNumber INT(255) UNSIGNED ZEROFILL UNIQUE NOT NULL,
userInfoPlaceWithoutDivision VARCHAR(255) NOT NULL,
userInfoDivision VARCHAR(255) NOT NULL,
userInfoEmail VARCHAR(255) UNIQUE,
userInfoProfilePicture VARCHAR(255),
PRIMARY KEY (userInfoUserNumber)
);
CREATE TABLE loginDetails
(
loginDetailsUserNumber INT(255) UNSIGNED AUTO_INCREMENT UNIQUE NOT NULL,
loginDetailsUserName VARCHAR(255) UNIQUE NOT NULL,
loginDetailsPassword VARCHAR(255) NOT NULL,
loginDetailsPhoneNumber INT(255) UNSIGNED ZEROFILL UNIQUE NOT NULL,
loginDetailsEmail VARCHAR(255) UNIQUE,
PRIMARY KEY (loginDetailsUserNumber) ,
FOREIGN KEY (loginDetailsUserName) REFERENCES userInfo(userInfoUserName)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (loginDetailsPassword) REFERENCES userInfo(userInfoPassword)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (loginDetailsPhoneNumber) REFERENCES userInfo(userInfoPhoneNumber)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (loginDetailsEmail) REFERENCES userInfo(userInfoEmail)
ON DELETE SET NULL
ON UPDATE CASCADE
);
[ In short : suppose my first table has 10 columns , my second table has 5 columns , i want to choose any 4 columns from 1st table and copy to my second table ]
Question 2 :
why this statement is error ? please explain
INSERT INTO userInfo(userInfoUserName,userInfoPassword,userInfoFirstName,userInfoLastName,userInfoPhoneNumber,userInfoPlaceWithoutDivision,userInfoDivision)
VALUES (cat,SHA1(cat),white,cat,01111111111,myplace,mydivision);
You can declare a foreign key only if the column you reference is the leftmost column of a key.
Traditionally, you'd reference only a unique or primary key, but InnoDB (strangely) allows a foreign key to reference any kind of key or partial key.
Your column userInfo.userInfoPassword is not part of any key.
It's not clear what purpose there could be for declaring all those foreign keys. If you want them to cascade, to always remain the same value in the userInfo table, then why are they stored in both tables at all? Just store them in one table.
i want to create a different table (loginDetails) taking 4 columns from userinfo
Why? You don't have to create a different table if you want to fetch a result set with just those four columns. You just specify the columns you want in a query instead of using SELECT *.
SELECT loginDetailsUserNumber,
loginDetailsUserName,
loginDetailsPassword,
loginDetailsPhoneNumber,
loginDetailsEmail
FROM userInfo;
Another option would be to use CREATE VIEW to define a view with those four columns, and then you could use SELECT * from your view.
CREATE VIEW loginDetails AS
SELECT loginDetailsUserNumber,
loginDetailsUserName,
loginDetailsPassword,
loginDetailsPhoneNumber,
loginDetailsEmail
FROM userInfo;
SELECT * FROM loginDetails;
When designing foreign key relationships, you should be linking using primary keys. This would suggest:
CREATE TABLE loginDetails (
loginDetailsUserNumber INT UNSIGNED AUTO_INCREMENT UNIQUE NOT NULL,
loginDetailsUserInfoUserNumber INT UNSIGNED,
loginDetailsUserName VARCHAR(255) UNIQUE NOT NULL,
loginDetailsPassword VARCHAR(255) NOT NULL,
loginDetailsPhoneNumber INT(255) UNSIGNED ZEROFILL UNIQUE NOT NULL,
loginDetailsEmail VARCHAR(255) UNIQUE,
PRIMARY KEY (loginDetailsUserNumber) ,
FOREIGN KEY (loginDetailsUserInfoUserNumber) REFERENCES userInfo(userInfoUserNumber)
ON DELETE SET NULL
ON UPDATE CASCADE,
);
In other words, you can keep the duplicated columns (perhaps a user changes his/her name or password and you want the version associated with the login). BUT, you should be assigning a user number at login and putting that id in the table.

How to create concatened primary key?

Hello I'm new to MySQL but I would like to create a unique ID based on two primary keys created in two other tables.
Here is just the part that interests us:
CREATE TABLE patient(
id_patient int NOT NULL AUTO_INCREMENT,
...,
PRIMARY KEY (id_patient))
CREATE TABLE surgeon(
id_surgeonint NOT NULL AUTO_INCREMENT,
...,
PRIMARY KEY (id_surgeon))
CREATE TABLE case(
id_patient int NOT NULL,
id_surgeon int NOT NULL,
CONSTRAINT FK_case_patient FOREIGN KEY (id_patient) REFERENCES patient(id_patient),
CONSTRAINT FK_case_surgeon FOREIGN KEY (id_surgeon) REFERENCES surgeon(id_surgeon),
CONSTRAINT id_case PRIMARY KEY (id_patient, `_`,id_surgeon));
I think i don't get the trick. I wanted the following result :
SELECT * FROM case;
id_case | id_patient | id_surgeon
32_56 | 32 | 56
18_66 | 18 | 66
I know that the speed of calculation will not be optimal but this id-case is really necessary and must be visible during the select
You can create a computed column, and if you really want its values on disk you can persist the computed column
CREATE TABLE case(
id_patient int NOT NULL,
id_surgeon int NOT NULL,
id_case varchar(30) AS CONCAT(id_patient, '_', id_surgeon),
CONSTRAINT FK_case_patient FOREIGN KEY (id_patient) REFERENCES patient(id_patient),
CONSTRAINT FK_case_surgeon FOREIGN KEY (id_surgeon) REFERENCES surgeon(id_surgeon),
CONSTRAINT pk_case PRIMARY KEY (id_patient,id_surgeon));
However unless you have the requirement that the pair (patient, surgeon) uniquely identifies a case you should consider adding in an extra field (e.g surgery date)

Creation Failed: Key column 'name' doesn't exist in table:

I am trying to create a series of tables using Foreign Keys of Primary Keys from other tables, however I always get the error
Table Creation Failed: Key column 'PACId' doesn't exist in table:
Here is the first case it appears:
CREATE TABLE PlantAreaCodes(
PACId INT NOT NULL AUTO_INCREMENT,
AreaCode INT,
AreaName CHAR(32),
Comments TEXT,
PRIMARY KEY (PACId)
);
CREATE TABLE MajorEquipment(
MEId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (MEId),
FOREIGN KEY (PACId)
REFERENCES PlantAreaCodes(PACId)
);
Is it to do with the syntax of the foreign key, or is it because the PACId is still empty, and cannot be?
It is not that PACId is empty. You haven't declared it in MajorEquipment.
Try using this definition for the second table:
CREATE TABLE MajorEquipment(
MEId INT NOT NULL AUTO_INCREMENT,
PACId INT, -- Added this column
PRIMARY KEY (MEId),
FOREIGN KEY (PACId)
REFERENCES PlantAreaCodes(PACId)
);
Here is a SQL Fiddle.
Try this
CREATE TABLE MajorEquipment(
MEId INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (MEId),
PACId INT
REFERENCES PlantAreaCodes(PACId)
)