'How to alter Foreign Key reference ON DELETE CASCADE without dropping table

I have created database tables with foreign key reference ON UPDATE CASCADE ON DELETE RESTRICT . However, I set my engine MyISAM so this reference does not work. The primary key is being deleted even if it is used elsewhere as foreign key. How can I fix this issue? I tried to alter table engine to InnoDB, but even if it is set to InnoDB the foreign references does not work. Moreover, I tried to drop one empty table with foreign key reference and engine MyISAM. Then I tried to add that table, but it does not add. Most probably when I drop table foreign references remain somewhere in schemas.

My query to create table.

CREATE TABLE IF NOT EXISTS `products` (
    `productid` int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `productname` varchar(255) NOT NULL,
    `productcode` varchar(255) NOT NULL,
    `producttype` varchar(255) NULL
) 
ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `sales` (
    `salesid` int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY
    `productid` int(10) NOT NULL,
    `quantity` int(10) NOT NULL,
    `price` int(10) NOT NULL,
    `date` datetime NOT NULL,
    CONSTRAINT `fk_sales_productid` 
    FOREIGN KEY (productid) 
    REFERENCES products(productid) ON UPDATE CASCADE ON DELETE RESTRICT
) 
ENGINE=MyISAM DEFAULT CHARSET=utf8;

These 2 tables were created with this query as MyISAM. They have data on it which i need. I run this query to change engine to InnoDB as reference on delete cascade were not working in MyISAM. 'ALTER TABLE products ENGINE=InnoDB;' 'ALTER TABLE sales ENGINE=InnoDB;' But after making them InnoDB, the reference still does not work when I delete product, related productid in sales table becomes NULL.



Solution 1:[1]

As per P.Salmon's demo queries seems valid. You probably missing something in FK references. I suggest you to export 2 tables, the examine it in editor, especially FK references part and make sure engine is InnoDB as it has row-level locking and has what is called referential integrity that involves supporting foreign keys and relationship constraints.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 esqeudero