Why Can't I form a foreign key on this? - mysql

I'am trying to add foreign key from department table to employee table. First one is done, But I can't create department table, it pops up error
ERROR 1005 (HY000): Can't create table `assignment`.`department` (errno: 150 "Foreign key constraint is incorrectly formed")
Like this.
CREATE TABLE employee
(
First_Name VARCHAR(15) NOT NULL,
Mid_Name CHAR,
Last_Name VARCHAR(15) NOT NULL,
SSN_Number CHAR(9) PRIMARY KEY NOT NULL,
Birthday DATE,
Address VARCHAR(50),
Sex CHAR CHECK(Sex='M' OR Sex='F' OR Sex='m' OR Sex='f'),
Salary Decimal(10,2) DEFAULT'800',
Supervisor_SSN CHAR(9),
Department_Number INT,
CONSTRAINT fk_employee FOREIGN KEY(Supervisor_SSN)
REFERENCES employee(SSN_Number) ON DELETE SET NULL
);
CREATE TABLE department
(
Department_Name VARCHAR(15) NOT NULL UNIQUE,
Department_Number INT PRIMARY KEY NOT NULL,
Manaager_SSN CHAR(9) NOT NULL,
Manager_Start_Date Date,
CONSTRAINT fk_manager FOREIGN KEY(Manaager_SSN)
REFERENCES employee(SSN_Number) ON DELETE SET NULL
);
I expect to add foreign key on Manaager_SSN to SSN_Number in employee table.

The option ON DELETE SET NULL is not valid if the column is declared NOT NULL. You're telling it to set the column to an impossible value.
So either change the declaration of Manaager_SSN to NULL, or change the foreign key to ON DELETE CASCADE. The former is probably more appropriate -- if the manager of a department leaves the company, you don't usually dissolve the department.

The foreign key definition includes
... ON DELETE SET NULL
^^^^^^^^
but the foreign key column is defined as non-NULL
Manaager_SSN CHAR(9) NOT NULL,
^^^^^^^^

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).

MySQL Error Code 1215: “Cannot add foreign key constraint”

I keep getting this error when attempting to create a table with SQL.
I have these two tables:
I'm using PHPMyAdmin and it won't allow me to use M_id as a foreign key which references Employee Table primary key E_id.
Anyone able to see what's wrong with my code?
Thanks!
Foreign key definitions have to exactly match the primary key columns to which they refer. In this case, you defined Department.M_id to a be a nullable integer column, while EMPLOYEE.E_id is integer not nullable. Try making M_id not nullable:
CREATE TABLE Department (
D_name VARCHAR(100) NOT NULL,
D_id INT NOT NULL,
M_id INT NOT NULL DEFAULT 0000,
...
FOREIGN KEY (M_id) REFERENCES EMPLOYEE(E_id)
ON DELETE SET DEFAULT ON UPDATE CASCADE
)
Your code has multiple errors:
varchar() length is too long.
You have a forward reference for a foreign key constraint.
SET DEFAULT doesn't really work.
You want something like this:
CREATE TABLE employees (
employee_id int not null primary key,
Job_type VARCHAR(100),
Ssn INT NOT NULL,
Salary DECIMAL NOT NULL,
Address VARCHAR(500) NOT NULL,
First_name VARCHAR(50) NOT NULL,
M_initial CHAR(1),
Last_name VARCHAR(50) NOT NULL,
E_end_date DATE,
E_start_date DATE NOT NULL,
department_id INT NOT NULL,
Super_id INT,
FOREIGN KEY (Super_id) REFERENCES employees(employee_id) ON DELETE SET NULL ON UPDATE CASCADE,
UNIQUE (Ssn)
);
CREATE TABLE departments (
department_id int primary key,
D_name VARCHAR(100) NOT NULL,
D_id INT NOT NULL,
M_id INT DEFAULT 0000,
Manager_start_date DATE NOT NULL,
Manager_end_date DATE,
Report VARCHAR(8000),
Num_of_employees INT NOT NULL,
FOREIGN KEY (M_id) REFERENCES employees(employee_id) ON DELETE SET NULL ON UPDATE CASCADE,
UNIQUE (D_name)
);
ALTER TABLE employees ADD CONSTRAINT FOREIGN KEY (department_id) REFERENCES departments(department_id)
ON DELETE CASCADE ON UPDATE CASCADE;
I also changed a few other things:
The table names are plural.
The primary keys are the singular form followed by "_id".
Foreign keys and primary keys have the same name.
The primary key is the first column in the table.
Here is a db<>fiddle showing that this works.
I will not question your design, though it looks problematic.
However - You cannot reference a table which doesn't exist yet (REFERENCES Department(D_id)). You should either remove the FOREIGN KEY constraints from the CREATE statements and add them afterwards in ALTER TABLE statements.
Example:
CREATE TABLE EMPLOYEE (...);
CREATE TABLE Department (...);
ALTER TABLE EMPLOYEE
ADD FOREIGN KEY (D_id)
REFERENCES Department(D_id)
ON DELETE CASCADE
ON UPDATE CASCADE
;
Demo
Or temporarily disable foreign key checks:
SET FOREIGN_KEY_CHECKS = 0;
CREATE TABLE EMPLOYEE (...);
CREATE TABLE Department (...);
SET FOREIGN_KEY_CHECKS = 1;
Demo
You can also not use ON DELETE SET DEFAULT. InnoDB doesn't support it. You need to change it to ON DELETE SET NULL. If you want that behavior, you will need to implement it either in your application code or in a trigger.
I would also use TEXT as data type instead of VARCHAR(30000).

mysql foreign key to compound primary key [duplicate]

This question already has answers here:
Composite key as foreign key (sql)
(2 answers)
Closed 6 years ago.
I try to achive the following using MySQL Server 5.x.
I have a table named Customer created like this:
CREATE TABLE Customer(
Title VARCHAR(30) NOT NULL,
Name VARCHAR(100) NOT NULL,
FirstName VARCHAR(100) NOT NULL,
Street VARCHAR(300) NOT NULL,
HouseNumber VARCHAR(30) NOT NULL,
ZipCode VARCHAR(30) NOT NULL,
City VARCHAR(100) NOT NULL,
Telephone VARCHAR(30) NOT NULL,
EMail VARCHAR(300) NULL,
CONSTRAINT PK_Customer PRIMARY KEY(Title,Name,FirstName),
INDEX Index_Name(Name));
And a second table Named 'Order' created like this:
CREATE TABLE `Order`(
Number BIGINT NOT NULL AUTO_INCREMENT,
Customer VARCHAR(230) NOT NULL,
Issued DATETIME NOT NULL,
PRIMARY KEY(Number),
CONSTRAINT FK_Customer FOREIGN KEY(Customer)
REFERENCES Customer(PK_Customer));
But I get an error with the number:
ERROR 1005 (HY000): Can't create table 'SBZ.Order' (errno: 150)
The innodb engine status shows me this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
160317 16:05:29 Error in foreign key constraint of table SBZ/Order:
FOREIGN KEY(Customer) REFERENCES Customer(PK_Customer)):
Cannot resolve column name close to:
))
Is it possible to create a foreign key to a compound primary key using constraint?
Any help appriciated. :)
First, you should have a CustomerId column in the first table. It should be auto-incremented. So the right definitions are:
CREATE TABLE Customer (
CustomerId int auto_increment primary key,
. . .
unique (title, firstname, name)
);
Then you can create a correct foreign key relationship to CustomerId:
CustomerId int,
. . .
CONSTRAINT FK_Customer FOREIGN KEY(CustomerId) REFERENCES Customer(CustomerId)
This is "right" because such synthetic keys have several advantages:
Foreign key references are much simpler.
You can change the components easily (changing part of a foreign key requires understanding cascading constraints).
Integers in indexes are more efficient than strings.
Of course, you can do the same with a composite primary key. You just need all three columns in the second table:
Title VARCHAR(30),
Name VARCHAR(100),
FirstName VARCHAR(100),
CONSTRAINT FK_Customer FOREIGN KEY(Title, Name, Firstname) REFERENCES Customer(Title, Name, Firstname)
Your child table's foreign key must contain the same columns, in the same order, as the primary key of the parent table. In your case it would look like
CREATE TABLE `Order`(
Number BIGINT NOT NULL AUTO_INCREMENT,
Title VARCHAR(30) NOT NULL,
Name VARCHAR(100) NOT NULL,
FirstName VARCHAR(100) NOT NULL,
...
CONSTRAINT FK_Customer FOREIGN KEY (Title, Name, FirstName)
REFERENCES Customer (Title, Name, FirstName)
);
Note the columns don't have to be in the same order in the table, just in the constraint's column list.

what is wrong with this mysql syntax? giving error on first primary key

it is giving me an syntax error but i cannot pinpoint what's wrong.
use test;
CREATE TABLE EMPLOYEE_EXPENSE
(
"EMP_EXP_ID" INT NOT NULL,
"EMP_ID" INT(5,0),
"YEAR" INT(4,0),
"MONTH" INT(2,0),
"EXPENSE_CLAIM" INT(7,2),
"APPROVED_AMT" INT(7,2),
"PAID_DATE" DATE,
CONSTRAINT "EMP_EXP_PK" PRIMARY KEY ("EMP_EXP_ID"),
CONSTRAINT "FK_EMPLOYEE" FOREIGN KEY ("EMP_ID") REFERENCES "EMPLOYEE" ("EMP_ID") ENABLE
);
mysql workbench shows red squibles under first EMP_EXP_ID.
here's employee table.
CREATE TABLE EMPLOYEE(
EMP_ID INT(5) NOT NULL,
FNAME VARCHAR(20),
LNAME VARCHAR(20),
DEPT_ID INT(5) NOT NULL,
MANAGER_EMP_ID INT(5),
SALARY INT(5),
HIRE_DATE DATE,
JOB_ID INT(3),
ACTIVE CHAR(1) DEFAULT 'Y' NOT NULL,
CONSTRAINT employee_pk PRIMARY KEY (EMP_ID)
);
Get rid of the quotes around the column identifiers. They are incorrect. Either use ticks or nothing at all.
use test;
CREATE TABLE EMPLOYEE_EXPENSE
(
EMP_EXP_ID INT NOT NULL,
EMP_ID INT(5,0),
YEAR INT(4,0),
MONTH INT(2,0),
EXPENSE_CLAIM INT(7,2),
APPROVED_AMT INT(7,2),
PAID_DATE DATE,
CONSTRAINT EMP_EXP_PK PRIMARY KEY (EMP_EXP_ID),
CONSTRAINT FK_EMPLOYEE FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (EMP_ID) ENABLE
);

How to add a foreign key constraint which refers to a primary key of the same table ( self reference)

Hello Everyone,
I would like to create a table which has primary key and a foreign key. The foreign key however references the primary key of the same table. I have read online and found out that in order to add this kind of constraint, I first need to drop this constraint, load the data and then user ALTER command to add the constraint. However, this does not seem to to work.
Here's the query:
DROP TABLE employee;
CREATE TABLE employee (
fname varchar(15) not null,
minit varchar(1),
lname varchar(15) not null,
ssn char(9),
bdate date,
address varchar(50),
sex char,
salary decimal(10,2),
superssn char(9),
dno integer(4),
primary key (ssn),
foreign key (superssn) references employee(ssn),
foreign key (dno) references department(dnumber)
);
and this is how I load the data in the table.
LOAD DATA LOCAL INFILE "employee.dat"
INTO TABLE employee
FIELDS ENCLOSED BY "\"" TERMINATED BY ","
;
I would very much appreciate if you can give me a hint on how to accomplish this.
Possible First Answer: (DIDN'T WORK)
DROP TABLE employee;
CREATE TABLE employee (
fname varchar(15) not null,
minit varchar(1),
lname varchar(15) not null,
ssn char(9),
bdate date,
address varchar(50),
sex char,
salary decimal(10,2),
superssn char(9),
dno integer(4),
primary key (ssn),
foreign key (dno) references department(dnumber)
) ENGINE = InnoDB;
LOAD DATA LOCAL INFILE "employee.dat"
INTO TABLE employee
FIELDS ENCLOSED BY "\"" TERMINATED BY ",";
ALTER TABLE employee ADD FOREIGN KEY (superssn) REFERENCES employee(ssn);
I set your create table query to set the table engine format to InnoDB which is required if you wish to use foreign keys.
Possible Second Answer:
It's important to note that for this set of queries, no data insertion was needed and I was able to run these two queries on my development MySQL Server without generating any errors. You'll still need to add your FK for your department table.
CREATE TABLE `test_schema`.`employees` (
`fname` VARCHAR(15) NOT NULL ,
`minit` VARCHAR(1) NULL ,
`lname` VARCHAR(15) NOT NULL ,
`ssn` CHAR(9) NOT NULL ,
`bdate` DATE NULL ,
`address` VARCHAR(50) NULL ,
`sex` CHAR NULL ,
`salary` DECIMAL(10,2) NULL ,
`superssn` CHAR(9) NULL ,
`dno` INT(4) NULL ,
PRIMARY KEY (`ssn`) ) ENGINE = InnoDB;
ALTER TABLE `test_schema`.`employees`
ADD CONSTRAINT `superssn`
FOREIGN KEY (`superssn` )
REFERENCES `test_schema`.`employees` (`ssn` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `superssn_idx1` (`superssn` ASC) ;
I got your question, you are trying to create a database as explained in book by elamsari.
Try to add a constraint " FOREIGN KEY (superssn) REFERENCES company.employee(ssn); "
before adding the data, since adding this constraint won't affect the adding data into table.
However, add the constraint related to dno using ALTER table command Later after adding the data.
Then you won't get error 1452:
I tried this, it works
Cheers
While entering the value of data as null
always use NULL without quotes NOT like "NULL"
this is why you are getting an error because instead of CHAR(9) you are entering a string of char(4)
So use NULL instead of "NULL"