MySQL Foreign Key syntax error - mysql

CREATE TABLE DEPARTMENT ( Dname VARCHAR(15) NOT NULL,
Dnumber INT NOT NULL,
Mgr_ssn CHAR(9) NOT NULL,
Mgr_start_Date DATE,
PRIMARY KEY(Dnumber),
UNIQUE(Dname),
FOREIGN KEY(Mgr_ssn) REFERENCES EMPLOYEE (Ssn)
ON DELETE SET DEFAULT ON UPDATE CASCADE);
I am a beginner in MySQL. The command above gives me this:
Cannot add foreign key constraint
I have tried SHOW ENGINE INNODB STATUS;
I checked EMPLOYEE.Ssn's data type.
Please help.
Edit: My EMPLOYEE table
| employee | CREATE TABLE `employee` (
`Fname` varchar(10) DEFAULT NULL,
`Minit` char(1) DEFAULT NULL,
`Lname` varchar(10) DEFAULT NULL,
`Ssn` char(9) NOT NULL,
`Bdate` date DEFAULT NULL,
`Address` varchar(40) DEFAULT NULL,
`Sex` char(1) DEFAULT NULL,
`Salary` int(11) DEFAULT NULL,
`Super_ssn` char(9) DEFAULT NULL,
`Dno` int(11) DEFAULT NULL,
PRIMARY KEY (`Ssn`),
KEY `Super_ssn` (`Super_ssn`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`Super_ssn`) REFERENCES `EMPLOYEE` (`Ssn`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

According to the MySQL docs at https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html , you can't use SET DEFAULT with INNODB :
SET DEFAULT: This action is recognized by the MySQL parser, but both InnoDB and NDB reject table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses

Related

How to use "ON UPDATE CASCADE" Correctly in MariaDB 10.1.37 / Ver 15.1?

I am experiencing trouble getting ON UPDATE CASCADE to work with a CONSTRAINT. If I use UPDATE to change the value of customerName in the customer table, it will not change the customerName value in the city table. No error message shows up.
The version of the MariaDB:
Ver 15.1 Distrib 10.1.37-MariaDB
My city table when using SHOW CREATE TABLE city:
city | CREATE TABLE `city` (
`cityId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`city` varchar(50) DEFAULT NULL,
`countryId` int(10) unsigned DEFAULT NULL,
`customerName` varchar(50) DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
`postalCode` varchar(50) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`createDate` varchar(50) DEFAULT NULL,
`createdBy` varchar(50) DEFAULT NULL,
`lastUpdateBy` varchar(50) DEFAULT NULL,
PRIMARY KEY (`cityId`),
KEY `customerNameChange01` (`customerName`),
CONSTRAINT `customerNameChange01` FOREIGN KEY (`customerName`)
REFERENCES `customer` (`customerName`)
ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
My customer table SHOW CREATE TABLE customer:
customer | CREATE TABLE `customer` (
`customerId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`customerName` varchar(50) DEFAULT NULL,
`addressId` int(10) unsigned DEFAULT NULL,
`active` int(10) unsigned DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
`city` varchar(50) DEFAULT NULL,
`postalCode` varchar(50) DEFAULT NULL,
`phone` varchar(50) DEFAULT NULL,
`createDate` varchar(50) DEFAULT NULL,
`createdBy` varchar(50) DEFAULT NULL,
`lastUpdateBy` varchar(50) DEFAULT NULL,
PRIMARY KEY (`customerId`),
KEY `CustomerName` (`customerName`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
These are the commands I used to create the index and CONSTRAINT:
CREATE INDEX CustomerName ON customer (customerName);
ALTER TABLE city
ADD CONSTRAINT customerNameChange01
FOREIGN KEY (customerName)
REFERENCES customer (customerName)
ON UPDATE CASCADE
ON DELETE SET NULL;
In the customer table, the CustomerName key references an index. Otherwise, I would not have been able to put in the CONSTRAINT in the city table.
Update: The code works fine in DB Fiddle for MariaDB 10.2 and personal testing confirms that the example code from there works in my own database as well.
Thank you for spending your time.

mysql foreign key ERROR 1451 update cascade not happening

I am trying to update a field that is referenced as a foreign key in another table.
mysql> update Maintenance set contract='95096916-OLD' where contract='95096916';
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign
key constraint fails (systems_doc.Equipment, CONSTRAINT
Equipment_ibfk_1 FOREIGN KEY (contract) REFERENCES Maintenance
(contract) ON UPDATE CASCADE)
| Maintenance | CREATE TABLE `Maintenance` (
`contract` char(30) NOT NULL,
`quote` char(30) NOT NULL,
`vendor` char(20) NOT NULL,
`provider` char(20) NOT NULL,
`product` char(30) NOT NULL,
`expiryDate` date NOT NULL,
`annualCost` int(11) NOT NULL,
`reference` char(13) NOT NULL,
`purchaseOrder` char(13) NOT NULL,
`cq` char(10) NOT NULL,
`cqRenewal` char(10) NOT NULL,
`comments` char(40) NOT NULL,
UNIQUE KEY `contract` (`contract`,`expiryDate`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
| Equipment | CREATE TABLE `Equipment` (
`vendor` char(20) NOT NULL,
`model` char(30) NOT NULL,
`serialNumber` char(20) NOT NULL,
`purchaseOrder` char(20) NOT NULL,
`purchaseDate` date NOT NULL,
`contract` char(15) NOT NULL,
`annualCost` int(11) NOT NULL,
`comments1` varchar(256) DEFAULT NULL,
`comments2` varchar(256) NOT NULL,
PRIMARY KEY (`serialNumber`),
KEY `contract` (`contract`),
CONSTRAINT `Equipment_ibfk_1` FOREIGN KEY (`contract`) REFERENCES `Maintenance` (`contract`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
Why isn't it cascading the UPDATE? I don't think it's circular. Thanks for your help. I've read other similar problems, but either I am misinterpreting how it should work, or I've got something setup wrong.

Foreign key constraint fails during `drop table`

I have a strange problem in which I'm not able to delete a table as a foreign key constraint fails. The scenario is as follows.
I'm trying to drop the table departments from my DB, the structure for which is as follows:
show create table `departments`
CREATE TABLE `departments` (
`dept_id` int(11) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(50) NOT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Now, the only other table in the database that has department_id is the employee table:
show create table employee
CREATE TABLE `employee` (
`emp_id` varchar(20) NOT NULL,
`role` varchar(10) DEFAULT NULL,
`password` varchar(500) DEFAULT NULL,
`division_id` int(20) DEFAULT NULL,
`email_bb` varchar(100) DEFAULT NULL,
`is_active` tinyint(1) NOT NULL,
`date_joining` date DEFAULT NULL,
`date_confirmation` date DEFAULT NULL,
`date_appraisal` date DEFAULT NULL,
`date_leaving` date DEFAULT NULL,
`first_name` varchar(100) DEFAULT NULL,
`middle_name` varchar(100) DEFAULT NULL,
`last_name` varchar(100) DEFAULT NULL,
`sex` varchar(1) DEFAULT NULL,
`dob` date DEFAULT NULL,
`email_other` varchar(100) DEFAULT NULL,
`contact` varchar(100) DEFAULT NULL,
`present_addr` varchar(1000) DEFAULT NULL,
`perma_addr` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
As you can see, none of these tables are related via foreign keys. So why do I get this error when trying to drop the department table:
#1217 - Cannot delete or update a parent row: a foreign key constraint fails
Is there a better way (and hopefully, simpler) way to see the foreign keys defined? What might be going wrong?
show create table doesn't show incoming FK restraints (e.g. FK is specified in child table, not parent)
So there is a possibility that you have another table with a FK constraint to that table. I usually dump the schema of the database, which shows all FK constraints.

MySQL Foreign key constraint - Error 1452 - Cannot add or update child row

I've used the other posts on this topic, but I'm having no luck.
Here's the code I execute:
UPDATE tblOrderItems SET `ItemID` = 0004 WHERE `OrderNum`= 203 AND `OrderItemID` = 26
Here's my error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`cai0066`.`tblOrderItems`, CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`))
Notes:
It happens when I either INSERT or UPDATE into tblOrderItems.
tblCatalogItems does have an ItemID of 0004. See: this
Here are the create statements generated by MySQL Workbench:
delimiter $$
CREATE TABLE `tblCatalogItems` (
`ItemID` varchar(10) NOT NULL DEFAULT '',
`ItemName` varchar(50) DEFAULT NULL,
`Wholesale` decimal(10,2) DEFAULT NULL,
`Cost5-10` decimal(10,2) DEFAULT NULL,
`Cost11-19` decimal(10,2) DEFAULT NULL,
`Cost20` decimal(10,2) DEFAULT NULL,
`Retail` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`ItemID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblItemCosts` (
`Cost` decimal(10,2) DEFAULT NULL,
`VendorID` int(11) NOT NULL,
`ItemID` varchar(10) NOT NULL,
KEY `VendorID_idx` (`VendorID`),
KEY `ItemID_idx` (`ItemID`),
CONSTRAINT `VendorID` FOREIGN KEY (`VendorID`) REFERENCES `tblVendors` (`VendorID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblOrderItems` (
`OrderItemID` int(11) NOT NULL AUTO_INCREMENT,
`OrderNum` int(11) NOT NULL,
`PayPalTxnID` int(10) DEFAULT NULL,
`Description` varchar(225) DEFAULT NULL,
`Quantity` int(11) DEFAULT NULL,
`UnitPrice` decimal(10,2) DEFAULT NULL,
`ItemStatus` varchar(30) DEFAULT NULL,
`TrackingNumber` varchar(50) DEFAULT NULL,
`ShippingCost` decimal(10,2) DEFAULT NULL,
`ItemID` varchar(50) DEFAULT NULL,
`TotalPrice` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`OrderItemID`,`OrderNum`),
UNIQUE KEY `PayPalTxnID_UNIQUE` (`PayPalTxnID`),
KEY `PayPalTxnID_idx` (`PayPalTxnID`),
KEY `UnitPrice_idx` (`ItemID`),
KEY `OrderNum_idx` (`OrderNum`),
CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`),
CONSTRAINT `OrderNum` FOREIGN KEY (`OrderNum`) REFERENCES `tblOrders` (`OrderNum`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `UnitPrice` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=7678 DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblOrderItemStatus` (
`OrderItemID` int(11) NOT NULL,
`OrderDate` varchar(12) DEFAULT NULL,
`DesignProofSent` varchar(12) DEFAULT NULL,
`SubmittedToProduction` varchar(12) DEFAULT NULL,
`InProduction` varchar(12) DEFAULT NULL,
`Shipped` varchar(12) DEFAULT NULL,
PRIMARY KEY (`OrderItemID`),
UNIQUE KEY `OrderItemID_UNIQUE` (`OrderItemID`),
KEY `OrderItemID_idx` (`OrderItemID`),
CONSTRAINT `OrderItemID` FOREIGN KEY (`OrderItemID`) REFERENCES `tblOrderItems` (`OrderItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblOrders` (
`OrderNum` int(11) NOT NULL AUTO_INCREMENT,
`PayPalTxnID` int(10) DEFAULT NULL,
`OrderDate` varchar(50) DEFAULT NULL,
`OrderStatus` varchar(10) DEFAULT 'New',
`RushFlag` bit(1) DEFAULT b'0',
`ShipName` varchar(50) DEFAULT NULL,
`ShipEmail` varchar(100) DEFAULT NULL,
`ShipAddress1` varchar(50) DEFAULT NULL,
`ShipAddress2` varchar(50) DEFAULT NULL,
`ShipCity` varchar(50) DEFAULT NULL,
`ShipState` char(2) DEFAULT NULL,
`ShipZip` varchar(10) DEFAULT NULL,
`ShippingCharge` decimal(10,2) DEFAULT NULL,
`TotalCost` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`OrderNum`),
UNIQUE KEY `PayPalTxnID_UNIQUE` (`PayPalTxnID`)
) ENGINE=InnoDB AUTO_INCREMENT=346 DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblVendors` (
`VendorID` int(11) NOT NULL,
`VendorName` varchar(50) DEFAULT NULL,
PRIMARY KEY (`VendorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
I tried the suggestion in this relevant post, but there were no results. This is a new database that hasn't actually been used yet; I've just filled it with fake data. Any ideas would be greatly appreciated.
There is a foreign key constraint on tblOrderItems that its ItemID needs to reference an ItemID that already exists in tblCatalogItems.
CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`),
The message only means that you're trying to update tblOrderItems to reference the item in tblCatalogItems with ItemID= 0004, but that item does not exist.
Since ItemID is a varchar, you probably want to quote the 0004 or it may be converted to an int 4 before conversion to varchar. That may be your problem if the row with ItemID = 0004 actually exists.
UPDATE tblOrderItems SET `ItemID` = '0004' WHERE `OrderNum`= 203 AND `OrderItemID` = 26
Without seeing the table data I can't be sure, but I'm guessing it's because there is no record in tblCatalogItems with an ItemID of '0004'.
Also, you probably need to quote the 0004 in your update statement since the column is defined as character (varchar(10)) not number (int).
There is a foreign key relationship defined between tblCatalogItems.ItemId and tblOrderItems.ItemId which means that any row in tblOrderItems can only have a value for ItemId that matches an ItemId found in tblCatalogItems.
You would therefore need to insert a record into 'tblCatalogItems' with an ItemId of '0004' first, before running your update on tblOrderItems
Alternatively you need to change the SET ItemID = clause in your update to set a value that matches to an ItemId value that actually exists in the tblCatalogItems table
The data type needs to match on both sides of your foreign key constraint. Here you have a varchar(50) referring a varchar(10), which isn't allowed.
CREATE TABLE `tblCatalogItems` (
`ItemID` varchar(10) NOT NULL DEFAULT '',
...
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
...
CREATE TABLE `tblOrderItems` (
`ItemID` varchar(50) DEFAULT NULL,
...
CONSTRAINT `UnitPrice` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=7678 DEFAULT CHARSET=latin1$$

mysql stored procedure not accepting Foreign key Constraint

I had created a table using StoredProcedure in mysql and i had applied primary key constraint also when i tried to apply foreign key constraint..iam getting error 'Cant create table dbname.tablename'..and here is my Simple StoredProcedure
delimiter |
CREATE PROCEDURE SP_CREATE_TABLE_SAMP()
BEGIN
CREATE TABLE anan_user (
user_id bigint(15) NOT NULL AUTO_INCREMENT,
name varchar(70) DEFAULT NULL,
last_name varchar(70) DEFAULT NULL,
gender varchar(10) DEFAULT NULL,
username varchar(40) DEFAULT NULL,
password varchar(40) DEFAULT NULL,
dateofbirth date DEFAULT NULL,
email varchar(100) DEFAULT NULL,
phone varchar(25) DEFAULT NULL,
mobile varchar(25) DEFAULT NULL,
address varchar(250) DEFAULT NULL,
pincode varchar(15) DEFAULT NULL,
state_id bigint(15) DEFAULT NULL,
district_id bigint(15) DEFAULT NULL,
constituency_id bigint(15) DEFAULT NULL,
profile_Img varchar(100) DEFAULT NULL,
is_pwd_changed varchar(10) DEFAULT 'false',
registered_time timestamp NULL DEFAULT NULL,
updated_date timestamp NULL DEFAULT NULL,
PRIMARY KEY ( user_id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
END;
how to give foreign key constraints in stored procedures?
Check your syntax against the MySQL reference on foreign key constraints. It would also be helpful for you to post what you tried, and how you're trying to set the foreign key constraint.
An example constraint definition is:
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
The relevant syntax is the FOREIGN KEY (parent_id) REFERENCES parent(id).