How to delete from a Table without having to drop a constraint - mysql

I have a question in which im required to delete information without dropping or suspending constraints. The question, if allowed to drop constraints is simple. However i am allowed to change Values from NULL to NOT NULL.
DELETE FROM SUPPLIER
WHERE COUNTRY = 'USA';
however another table PRODUCT is the foreign key of a column SUPPLIER_NAME within SUPPLIER. I am not allowed to drop this Constraint.
Ive tried setting the Foreign key to null but it doesnt Work.
EDIT im not allowed to restrict or suspend constraints
this is the full question
"Delete from the database information about all suppliers located in USA. Information about all products supplied by the suppliers located in USA must remain in the database. You are not allowed to drop and/or to suspend any referential integrity constraints and you must modify one of NULL/NOT NULL consistency constraints. "
The tables being used
CREATE TABLE PRODUCT
(
PRODUCT_NAME VARCHAR(40) NOT NULL,
SUPPLIER_NAME VARCHAR(40) NOT NULL,
CATEGORY_NAME VARCHAR(30) NOT NULL,
QUANTITY_PER_UNIT VARCHAR(20),
UNIT_PRICE DECIMAL(10,2) NOT NULL DEFAULT 0,
UNITS_IN_STOCK DECIMAL(9) NOT NULL DEFAULT 0,
UNITS_ON_ORDER DECIMAL(9) NOT NULL DEFAULT 0,
REORDER_LEVEL DECIMAL(9) NOT NULL DEFAULT 0,
DISCONTINUED CHAR(1) NOT NULL DEFAULT 'N',
CONSTRAINT PK_PRODUCT PRIMARY KEY (PRODUCT_NAME),
CONSTRAINT FK_CATEGORY_NAME FOREIGN KEY (CATEGORY_NAME) REFERENCES CATEGORY(CATEGORY_NAME),
CONSTRAINT FK_SUPPLIER_NAME FOREIGN KEY (SUPPLIER_NAME) REFERENCES SUPPLIER(COMPANY_NAME),
CONSTRAINT CK_PRODUCT_UNIT_PRICE CHECK (UNIT_PRICE >= 0),
CONSTRAINT CK_PRODUCT_UNITS_IN_STOCK CHECK (UNITS_IN_STOCK >= 0),
CONSTRAINT CK_PRODUCT_UNITS_ON_ORDER CHECK (UNITS_ON_ORDER >= 0),
CONSTRAINT CK_PRODUCT_REORDER_LEVEL CHECK (REORDER_LEVEL >= 0),
CONSTRAINT CK_PRODUCT_DISCONTINUED CHECK (DISCONTINUED in ('Y','N'))
);
CREATE TABLE SUPPLIER
(
COMPANY_NAME VARCHAR(40) NOT NULL,
CONTACT_NAME VARCHAR(30),
CONTACT_TITLE VARCHAR(30),
ADDRESS VARCHAR(60),
CITY VARCHAR(15),
REGION VARCHAR(15),
POSTAL_CODE VARCHAR(10),
COUNTRY VARCHAR(15),
PHONE VARCHAR(24),
FAX VARCHAR(24),
HOME_PAGE VARCHAR(500),
CONSTRAINT PK_SUPPLIER PRIMARY KEY (COMPANY_NAME)
);

As the foreign key to your PRODUCT table doe not specify an ON DELETE action, it'll have the default behaviour which is RESTRICT. Since you can't update this constraint to SET NULL, you'd probably have to set them NULL yourself.
First, alter the table so the SUPPLIER_NAME foreign key can accept NULL values.
Then, update the PRODUCTS whose supplier are in the USA, set their SUPPLIER_NAME to NULL. Something like this:
update PRODUCT set SUPPLIER_NAME = NULL where SUPPLIER_NAME IN (
select SUPPLIER_NAME from SUPPLIER where COUNTRY = 'USA');
And at last you can then delete the SUPPLIERS with COUNTRY = 'USA'.

Related

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

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,
^^^^^^^^

sql code is not working in phpmyadmin using mac?

My teacher provided me with this sql code, and I logged in as root into phpmyadmin, added a database called webstore, and then tried to add this code and it's giving me errors. Is there anyone who can tell me what could be causing the errors? I am using a Mac, so I'm not sure if that makes any difference, I can give you a link to dropbox with additional information if necessary.
This is the dropbox link with the code provided (Webstore.sql): https://www.dropbox.com/sh/usfmbeyxqd2q1g5/AADoLFbsz8cL30EC76d60i40a?dl=0
Also, the zip file contains images of the errors I was receiving. PLEASE HELP!!
The SQL statement the error occurs on is
CREATE TABLE Shopping_Cart (
CustID INTEGER NOT NULL,
ProdID INTEGER NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID)
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
The error reads
A comma or closing bracket was expected. (near "CONSTRAINT" at position 153)
Unexpected beginning of statement. (near "CustID" at position 192)
Unrecognised statement type. (near "REFERENCES" at position 206)
Your PRIMARY KEY line needs a comma after it before the CONSTRAINT.
CREATE TABLE Shopping_Cart (
CustID INTEGER NOT NULL,
ProdID INTEGER NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID),
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
Edit
It turns out there were a lot of problems with the SQL. The tables were created in the wrong order and the data types were wrong. Here is a rewritten version that I have tested out:
DROP DATABASE IF EXISTS WebStore;
CREATE DATABASE WebStore;
USE WebStore;
CREATE TABLE Categories (
CatID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(20) NOT NULL,
Descr VARCHAR(120) NOT NULL,
IconURL VARCHAR(64) NOT NULL,
PRIMARY KEY (CatID)
);
CREATE TABLE Products (
ProdID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
Name VARCHAR(20) NOT NULL,
Category INTEGER UNSIGNED,
Descr VARCHAR(120) NOT NULL,
Price FLOAT NOT NULL,
Stock INTEGER UNSIGNED NOT NULL,
IconURL VARCHAR(64) NOT NULL,
PRIMARY KEY (ProdID),
CONSTRAINT FK_Cat FOREIGN KEY FK_Cat (Category)
REFERENCES Categories (CatID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
INSERT INTO Categories VALUES(null,"Laptops","Small computers you can carry","http://localhost/images/laptop.jpg");
SET #laptops := LAST_INSERT_ID();
INSERT INTO Categories VALUES(null,"Desktops","Big computers you cannot carry","http://localhost/images/desktop.jpg");
SET #desktops := LAST_INSERT_ID();
INSERT INTO Categories VALUES(null,"Tablets"," Flat things you lose frequently","http://localhost/images/tablet.jpg");
SET #tablets := LAST_INSERT_ID();
INSERT INTO Products VALUES(null,"DULL 1200",#desktops,"A big dull machine",1290.99,23,"http://localhost/images/dull1200.jpg");
INSERT INTO Products VALUES(null,"8P Totalo",#desktops,"Almost as big as the DULL",990.99,2,"http://localhost/images/8ptotalo.jpg");
INSERT INTO Products VALUES(null,"LaNuveau Bingster",#desktops,"Comes in blue and red",690.99,12,"http://localhost/images/lanuveaubingster.jpg");
INSERT INTO Products VALUES(null,"DULL 122",#laptops,"Small, portable and useless",422.99,4,"http://localhost/images/dull122.jpg");
INSERT INTO Products VALUES(null,"8P Tootsie",#laptops,"Sticky and too heavy",559.99,12,"http://localhost/images/8ptootsie.jpg");
INSERT INTO Products VALUES(null,"LaNuveau Shoobie XT",#laptops,"Weighs a ton but looks sharp",1690.99,122,"http://localhost/images/lanuveaushoobiext.jpg");
INSERT INTO Products VALUES(null,"Motor Roller 12",#tablets,"The only one with a oval screen",422.99,4,"http://localhost/images/mr12.jpg");
INSERT INTO Products VALUES(null,"SamSings OffKey",#tablets,"Needs duct tape to run",559.99,2,"http://localhost/images/samsingsOK.jpg");
INSERT INTO Products VALUES(null,"jPet 12",#tablets,"The first that kinda sorta works",16290.99,722,"http://localhost/images/jpet12.jpg");
CREATE TABLE Customers (
CustID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
FirstName VARCHAR(40) NOT NULL,
LastName VARCHAR(40) NOT NULL,
Address VARCHAR(60) NOT NULL,
City VARCHAR(40) NOT NULL,
State VARCHAR(20) NOT NULL,
Zip VARCHAR(5) NOT NULL,
PRIMARY KEY (CustID)
);
INSERT INTO Customers VALUES(null,"Gerald","Bostock","1234 TAAB Drive","St. Cleve","FL","12345");
INSERT INTO Customers VALUES(null,"Suzy","Creamcheese","8722 Zappa Road","Paris","TX","75460");
CREATE TABLE Shopping_Cart (
CustID INTEGER UNSIGNED NOT NULL,
ProdID INTEGER UNSIGNED NOT NULL,
NumOfItems INTEGER,
PRIMARY KEY CLUSTERED (CustID, ProdID),
CONSTRAINT FK_Cust FOREIGN KEY FK_Cat (CustID)
REFERENCES Customers (CustID)
ON DELETE RESTRICT
ON UPDATE RESTRICT,
CONSTRAINT FK_Prod FOREIGN KEY FK_Prod (ProdID)
REFERENCES Products (ProdID)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
INSERT INTO Shopping_Cart VALUES("1","4","2");
INSERT INTO Shopping_Cart VALUES("1","9","1");

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

MySQL & PHPMyadmin - cannot create relation

Ok, so I have a database with a number of tables, but I have an issue with two in particular. One is called "asset", and structure is thus:
`assetid` varchar(5) NOT NULL,
`typeid` varchar(2),
`make` varchar(40),
`model` varchar(40),
`serno` varchar(40),
`opsys` varchar(40),
`ownerid` varchar(4)L,
`locid` varchar(4),
`purdate` date,
`insdate` date,
`remdate` date,
`dispdate` date,
`techid` varchar(3)
The other is called "supplier":
`suppid` varchar(3) NOT NULL,
`suppname` varchar(40),
`assetid` varchar(5),
`lastpurdate` date,
In "asset" my PK is assetID. In supplier, I originally had a PK as suppid and assetid. However I could not create a relation linking supplier.assetid to asset.assetid. I was not allowed to do so in PHPMyAdmin, so I deleted assetid from supplier, and added suppid to asset. I want to make suppid a foreign key in asset, but when I try to do so I get this:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`assettracker`.`#sql-15c4_672`, CONSTRAINT `#sql-15c4_672_ibfk_6` FOREIGN KEY (`suppid`) REFERENCES `supplier` (`suppid`) ON DELETE SET NULL ON UPDATE NO ACTION)
Why am I not allowed to do this?
Try this
ALTER TABLE tableName ENGINE = InnoDB;
Does that work?

MySQL: Foreign key constraint getting ignored in InnoDB

I am creating a table called fac_master which has a foreign key which refers to dept_id of dept_master. The table is getting created but foreign key is not getting enforced on this table. I also have a foreign key in dept_master which works very well but not for this table.
create table Dept_Master
( dept_id smallint unsigned auto_increment not null comment 'Department/Branch ID',
dept_name varchar(100) not null comment 'Department Name such as Computer Engineering',
prog_id tinyint unsigned not null comment 'Program ID under which this department falls',
PRIMARY KEY(dept_id),
CONSTRAINT fk_dept FOREIGN KEY(prog_id) REFERENCES Prog_Master(prog_id) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB COLLATE latin1_general_ci;
create table Fac_Master
( fac_id smallint unsigned auto_increment not null comment 'Faculty ID',
dept_id smallint unsigned not null comment 'Department Id of the department in which this faculty works',
fac_name varchar(30) not null comment 'Name of the Faculty',
fac_father_name varchar(30) comment 'Father\'s name of the faculty',
fac_surname varchar(30) comment 'Surname of the faculty',
fac_designation varchar(30) not null comment 'Designation of the faculty',
fac_mail_id varchar(50) comment 'E-mail id of the faculty',
fac_mobile bigint(10) unsigned comment 'Mobile number of the faculty',
fac_address varchar(100) comment 'Permanent Address of the faculty',
fac_status varchar(1) not null comment 'Status of Faculty: A=Active D=Deactive',
fac_joining_date date comment 'Joining Date of the Faculty',
PRIMARY KEY(fac_id),
CONSTRAINT fk_faculty FOREIGN KEY(dept_id) REFERENCES Dept_Master(dept_id) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB COLLATE latin1_general_ci;
When i try to add a value in "prog_id" of "dept_master" which is not present in the "prog_id" of "prog_master" then it gives fk constraint error which is fine but when i try to add a value in "dept_id" of "fac_master" which is not present in the "dept_id" of "dept_master" then it gets added but it should have given a fk constraint error.
I also checked foreign key constraint in information schema and found that foreign key constraint was not there for table fac_master. I am using WAMP Server 2.2 on windows 7 HP 64 bit version.
What is the problem? please help..
Edit:
alter table Fac_Master
add constraint fk_faculty FOREIGN KEY(dept_id) REFERENCES Dept_Master(dept_id) ON DELETE RESTRICT ON UPDATE RESTRICT;
using alter table as shown above works but not when used with create table. What could be the reason for it?
It appears the problem is caused by the way you escape the ' in 'Father\'s name of the faculty'. When you change it in 'Father''s name of the faculty', you'll find the foreign key constraints are correctly created.
Both ways of including a single quote are correct according to the manual, so it is a bug. See this MySQL bug ticket.