SQL Server : code created and not sure why it is not processing - foreign key problem? - sql

CREATE TABLE THREE_GIRLS_COFFEE_HUT
(
ShopName Char NOT NULL,
PhoneNumber Char(12) NOT NULL,
Address Char(20) NOT NULL,
City Char(20) NOT NULL,
State Char(2) NOT NULL,
ZipCode Char(5) NOT NULL,
CONSTRAINT ShopPK PRIMARY KEY (ShopName)
);
CREATE TABLE EMPLOYEE
(
EmployeeID Int NOT NULL IDENTITY(1,1),
EmployeeName Char(30) NOT NULL,
PhoneNumber Char(10) NOT NULL,
Address Char(20) NOT NULL,
City Char(20) NOT NULL,
State Char(2) NOT NULL,
ZipCode Char(5) NOT NULL,
EmployeeType Char(10) NOT NULL,
ShopName Char (25) FOREIGN KEY REFERENCES THREE_GIRLS_COFFEE_HUT (ShopName)
CONSTRAINT EmployeePK PRIMARY KEY(EmployeeID),
CONSTRAINT EmployeeAK1 UNIQUE(EmployeeName)
);
CREATE TABLE CUSTOMER
(
CustomerID Int NOT NULL IDENTITY(1000,1),
CustomerName Char(30) NULL,
PhoneNumber Char(10) NULL,
EmailAddress Char(30) NOT NULL,
CONSTRAINT CustomerPK PRIMARY KEY(CustomerID),
CONSTRAINT CustomerAK1 UNIQUE(EmailAddress)
);
CREATE TABLE [ORDER]
(
SalesOrderNumber INT NOT NULL IDENTITY (1500,1),
Date Numeric(6) NOT NULL,
Subtotal Numeric(6, 2) NOT NULL,
Tax Numeric(6, 2) NOT NULL,
Total Numeric(6, 2) NOT NULL,
CONSTRAINT OrderPK PRIMARY KEY (SalesOrderNumber),
CONSTRAINT EmpOrdFK FOREIGN KEY(EmployeeID)
REFERENCES EMPLOYEE(EmployeeID)
ON UPDATE CASCADE
ON DELETE NO ACTION,
CONSTRAINT CustOrdFK FOREIGN KEY (CustomerID)
REFERENCES CUSTOMER(CustomerID)
ON UPDATE NO ACTION
ON DELETE NO ACTION
);
CREATE TABLE PRODUCT
(
ProductNumber Int NOT NULL IDENTITY(2000,1),
ProductDescription Char(20) NOT NULL,
QuantityOnOrder Numeric(4) NOT NULL,
QuantityOnHand Numeric(4) NOT NULL,
OrderDate Date NOT NULL,
ExpirationDate Date NOT NULL,
CONSTRAINT ProductPK PRIMARY KEY(ProductNumber),
CONSTRAINT ValidExpDate CHECK (ExpirationDate > OrderDate)
);
CREATE TABLE MENU_ITEM (
ItemNumber Int NOT NULL IDENTITY(3000,1),
ItemDescription Char(30) NOT NULL,
ItemCost Numeric(6,2) NOT NULL,
ProductNumber Int FOREIGN KEY REFERENCES PRODUCT(ProductNumber)
CONSTRAINT MenuPK PRIMARY KEY(ItemNumber),
CONSTRAINT MenuAK1 UNIQUE(ItemDescription),
);
CREATE TABLE ORDER_LINE_ITEM (
SalesOrderNumber INT FOREIGN KEY REFERENCES [ORDER](SalesOrderNumber),
ItemNumber INT FOREIGN KEY REFERENCES MENU_ITEM(ItemNumber),
Quantity Numeric NOT NULL,
UnitPrice Numeric(6,2) NOT NULL,
ExtendedPrice Numeric (6,2) NOT NULL,
);
I got these errors and it will not process- I think I have problem with my foreign key but I am not sure.
Msg 1769, Level 16, State 1, Line 40
Foreign key 'EmpOrdFK' references invalid column 'EmployeeID' in referencing table 'ORDER'.
Msg 1750, Level 16, State 0, Line 40
Could not create constraint or index. See previous errors.

There's no column EmployeeID in the ORDER table, so:
EmpOrdFK FOREIGN KEY(EmployeeID) REFERENCES EMPLOYEE(EmployeeID)
which says, create a foreign key in which Order.EmployeeId references Employee.EmployeeId, can't work.
Did you want to add an EmployeeId column to Order?
(There's also no CustomerId in Order, so the next line
CONSTRAINT CustOrdFK FOREIGN KEY (CustomerID)
would have failed too, except it never got to run because of the first error.)
You probably want to add EmployeeId and CustomerId to the Order table.

When you are mapping foreign key from Order table to Employee table, you have to map on common column in both tables. If you look at order table, which is missing employeeId in
that table.
And also don't call it as ORDER table. ORDER is reserved keyword in SQL server.
References: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql?view=sql-server-ver15

Related

Problems referencing primary key with foreign key

This is code to create the beginnings of a book library database with Microsoft SQL Server Management Studio.
CREATE DATABASE BOOK_LIBRARY
CREATE TABLE LIBRARY_USER
(
usr_id int not null primary key,
f_name varchar(30) not null,
m_init char(1),
l_name varchar(30) not null,
balance decimal(6,2),
join_date date,
addrss_1 varchar(30) not null,
addrss_2 varchar(30),
city varchar(30) not null,
addrss_state char(2) not null,
zip_code varchar(10) not null,
email varchar(30)
);
CREATE TABLE LIBRARY_TRANSACTIONS
(
transaction_id int not null primary key,
maximum_borrow_duration int not null,
strt_date date not null,
actual_return_date date not null,
borrow_usr_id int not null,
foreign key (borrow_usr_id) references LIBRARY_USER(usr_id)
);
CREATE TABLE BOOKS
(
isbn varchar(17) not null primary key,
title varchar(30) not null,
number_of_copies int not null,
Author varchar(30) not null,
Number_of_pages int not null,
publish_year int not null,
book_type varchar(20)
);
CREATE TABLE DIGITAL_BOOKS
(
digital_id int not null primary key,
format varchar(30) not null,
size_mb int not null,
digital_isbn varchar(17) not null,
foreign key(digital_isbn) references BOOKS(isbn)
);
CREATE TABLE PHYSICAL_BOOKS
(
physical_id int not null primary key,
condition varchar(20) not null,
physical_isbn varchar(17) not null,
foreign key(physical_isbn) references BOOKS(isbn)
);
CREATE TABLE BOOK_COPY
(
digi_id int not null,
phys_id int not null,
primary key(digi_id, phys_id),
foreign key(digi_id) references DIGITAL_BOOKS(digital_id),
foreign key(phys_id) references PHYSICAL_BOOKS(physical_id)
);
CREATE TABLE CONTNS
(
trans_id int not null primary key,
digi_id int not null,
phys_id int not null,
foreign key(digi_id) references BOOK_COPY(digi_id),
foreign key(phys_id) references BOOK_COPY(phys_id)
);
Despite me being able to look and see that digi_id and phys_id are in fact primary keys of the book_copy table, I keep getting this error:
Msg 1776, Level 16, State 0, Line 66
There are no primary or candidate keys in the referenced table 'BOOK_COPY' that match the referencing column list in the foreign key 'FK__CONTNS__digi_id__37A5467C'.
Msg 1750, Level 16, State 1, Line 66
Could not create constraint or index. See previous errors.
Am I missing something obvious? I'm just starting out with using this program, so any help is greatly appreciated.
Here:
CREATE TABLE CONTNS
(
trans_id int not null primary key,
digi_id int not null,
phys_id int not null,
foreign key(digi_id) references BOOK_COPY(digi_id),
foreign key(phys_id) references BOOK_COPY(phys_id)
);
You are creating two foreign keys to parent table BOOK_COPY. But that table has a compound primary key (ie a multi-column primary key)
CREATE TABLE BOOK_COPY
(
digi_id int not null,
phys_id int not null,
primary key(digi_id, phys_id), --> here
...
)
As a consequence, you need a compound foreign key:
CREATE TABLE CONTNS
(
trans_id int not null primary key,
digi_id int not null,
phys_id int not null,
foreign key(digi_id, phys_id) references BOOK_COPY(digi_id, phys_id)
);

Error ORA-00904 in SQL developer. Seemly no fix online that works that I can find while creating a table

I have seen many posts regarding the seemingly infamous ORA-00904 yet nothing seems to be helping. I am creating 2 tables (for now, more to come later) which are as follows;
CREATE TABLE Employee(
EmployeeID int NOT NULL,
PRIMARY KEY(EmployeeID),
customerID INT NOT NULL,
CONSTRAINT employee_customer_fk FOREIGN KEY (customerID) REFERENCES Customer(CustomerID),
LastName CHAR(20) NOT NULL,
MiddleInitial CHAR(1),
FirstName CHAR(20) NOT NULL,
Region CHAR(20) NOT NULL,
DateOfHire VARCHAR(20) NOT NULL,
Skill VARCHAR(50) NOT NULL
);
and
CREATE TABLE Customer(
CustomerID INT NOT NULL PRIMARY KEY,
ProjectID INT NOT NULL,
FOREIGN KEY(ProjectID) REFERENCES Project(ProjectID), /*This is yet another table with a foreign key which needs to be sorted*/
CustomerName Char(255) NOT NULL,
PhoneNumber INT NOT NULL,
Region CHAR(255) NOT NULL
);
but every time I run it, I get error;
Error starting at line : 4 in command -
CREATE TABLE Employee(
EmployeeID int NOT NULL,
PRIMARY KEY(EmployeeID),
customerID INT NOT NULL,
CONSTRAINT employee_customer_fk FOREIGN KEY(customerID) REFERENCES Customer(CustomerID),
LastName CHAR(20) NOT NULL,
MiddleInitial CHAR(1),
FirstName CHAR(20) NOT NULL,
Region CHAR(20) NOT NULL,
DateOfHire VARCHAR(20) NOT NULL,
Skill VARCHAR(50) NOT NULL
)
Error report -
ORA-00904: "CUSTOMERID": invalid identifier
00904. 00000 - "%s: invalid identifier"
*Cause:
*Action:
ANY HELP WOULD BE GREATLY APPRECIATED!
Oracle by default converts all names to UpperCase if you don't enquote them. (Edit: At the time of this answer the Foreign Key Constraint in the starting post did contain a quoted column name).
So, your constraint tries to find a column named "customerID" whereas the real name of your column is "CUSTOMERID".
Either enquote your column:
CREATE TABLE Employee(
EmployeeID int NOT NULL,
PRIMARY KEY(EmployeeID),
"customerID" INT NOT NULL,
CONSTRAINT employee_customer_fk FOREIGN KEY ("customerID") REFERENCES customer(CustomerID),
LastName CHAR(20) NOT NULL,
MiddleInitial CHAR(1),
FirstName CHAR(20) NOT NULL,
Region CHAR(20) NOT NULL,
DateOfHire VARCHAR(20) NOT NULL,
Skill VARCHAR(50) NOT NULL
)
Don't use quotes on your FOREIGN KEY constraint:
CREATE TABLE Employee(
EmployeeID int NOT NULL,
PRIMARY KEY(EmployeeID),
customerID INT NOT NULL,
CONSTRAINT employee_customer_fk FOREIGN KEY (customerID) REFERENCES customer(CustomerID),
LastName CHAR(20) NOT NULL,
MiddleInitial CHAR(1),
FirstName CHAR(20) NOT NULL,
Region CHAR(20) NOT NULL,
DateOfHire VARCHAR(20) NOT NULL,
Skill VARCHAR(50) NOT NULL
)
Or use quotes and write it uppercase in your foreign key constraint:
CREATE TABLE Employee(
EmployeeID int NOT NULL,
PRIMARY KEY(EmployeeID),
customerID INT NOT NULL,
CONSTRAINT employee_customer_fk FOREIGN KEY ("CUSTOMERID") REFERENCES customer(CustomerID),
LastName CHAR(20) NOT NULL,
MiddleInitial CHAR(1),
FirstName CHAR(20) NOT NULL,
Region CHAR(20) NOT NULL,
DateOfHire VARCHAR(20) NOT NULL,
Skill VARCHAR(50) NOT NULL
)
As already mentioned, keeping the style consistent is recommended to prevent future problems, so Option 2 would be the easiest solution. Otherwise you need to enquote all columns to be consistent.
/Edit:
I just tried it - this definitely works with Oracle 12C:
CREATE TABLE Customer (
CustomerID INT,
PRIMARY KEY (CustomerID)
)
Followed by:
CREATE TABLE Employee(
EmployeeID int NOT NULL,
PRIMARY KEY(EmployeeID),
customerID INT NOT NULL,
CONSTRAINT employee_customer_fk FOREIGN KEY(customerID) REFERENCES Customer(CustomerID),
LastName CHAR(20) NOT NULL,
MiddleInitial CHAR(1),
FirstName CHAR(20) NOT NULL,
Region CHAR(20) NOT NULL,
DateOfHire VARCHAR(20) NOT NULL,
Skill VARCHAR(50) NOT NULL
)
The referenced table needs to created before the foreign key reference. One method is to create the tables first and then add the foreign key references:
CREATE TABLE Employee (
EmployeeID int NOT NULL,
PRIMARY KEY (EmployeeID),
customerID INT NOT NULL,
LastName CHAR(20) NOT NULL,
MiddleInitial CHAR(1),
FirstName CHAR(20) NOT NULL,
Region CHAR(20) NOT NULL,
DateOfHire VARCHAR(20) NOT NULL,
Skill VARCHAR(50) NOT NULL
);
CREATE TABLE Customer (
CustomerID INT NOT NULL PRIMARY KEY,
ProjectID INT NOT NULL,
-- FOREIGN KEY(ProjectID) REFERENCES Project(ProjectID), /*This is yet another table with a foreign key which needs to be sorted*/
CustomerName Char(255) NOT NULL,
PhoneNumber INT NOT NULL,
Region CHAR(255) NOT NULL
);
alter table Employee add CONSTRAINT employee_customer_fk FOREIGN KEY (customerID) REFERENCES Customer (CustomerID)
Here is a db<>fiddle.
Note that I commented out the foreign key constraint to Project.
Also, in most data models you can just order the table creates -- there are no cycles in the foreign key "linkages". However, because you have not defined Project, I am suggesting this more general approach.

SQL Error: ORA-02267 column type incompatible with referenced column type

Source code for oracle 12c
CREATE TABLE CUSTOMER (
CustomerID Char(20) NOT NULL,
CustomerFirstName Char(20) NOT NULL,
CustomerLastName Char(25) NOT NULL,
CustomerAddress Char(45) NOT NULL,
CustomerEmail Char(100) NOT NULL,
CONSTRAINT Customer_PK Primary Key(CustomerID)
CREATE TABLE EMPLOYEE (
EmployeeID VarChar(10) NOT NULL,
EmployeeFName VarChar(20) NOT NULL,
EmployeeRole VarChar(30) NOT NULL, CONSTRAINT
Employee_PK Primary Key(EmployeeID)
CREATE TABLE PRODUCT (
ProductID VarChar(10) NOT NULL,
ProductName VarChar(20) NOT NULL,
ProductType VarChar(20) NOT NULL,
ProductPrice Number(8,2) NOT NULL,
CONSTRAINT Product_PK Primary Key(ProductID)
CREATE TABLE CUSTORDER (
CustOrderID VarChar(10) NOT NULL,
CustOrderDate Date NOT NULL,
CustShippingStatus VarChar(20) NOT NULL,
SupplierID VarChar(20) NOT NULL,
CONSTRAINT CustOrder_PK Primary Key (CustOrderID),
CONSTRAINT CustOrder_FK FOREIGN KEY(SupplierID)
REFERENCES SUPPLIER(SupplierID)
CREATE TABLE SUPPLIER ( SupplierID Char(10) NOT NULL,
SupplierName Char(20) NOT NULL,
SupplierAddress Char(45) NOT NULL,
CONSTRAINT Supplier_PK Primary Key (SupplierID)
CREATE TABLE INVOICE (
InvoiceID Char(20) NOT NULL,
TotalItems Int NOT NULL,
TotalCost Number(8,2) NOT NULL,
SalesDate Date NOT NULL,
PaymentType VarChar(10) NOT NULL,
ProductID VarChar(10) NOT NULL,
EmployeeID VarChar(10) NOT NULL,
CustomerID Char(20) NOT NULL,
SupplierID Char(10) NOT NULL,
CONSTRAINT Invoice_PK Primary Key(InvoiceID),
CONSTRAINT Invoice_Product_FK Foreign Key(ProductID)
REFERENCES PRODUCT(ProductID),
CONSTRAINT Invoice_Employee_FK Foreign Key(EmployeeID)
REFERENCES EMPLOYEE(EmployeeID),
CONSTRAINT Invoice_Customer_FK Foreign Key(CustomerID)
REFERENCES CUSTOMER(CustomerID),
CONSTRAINT Invoice_Supplier_FK Foreign Key(SupplierID)
REFERENCES SUPPLIER(SupplierID)
You need to align the datatype and length of the referencing column of each foreign key with the column it references in the source table.
In your code, SUPPLIER(SupplierID) is declared as Char(20). On the other hand, referencing column INVOICE(SupplierID) is Char(10) and CUSTORDER(SupplierID) is VarChar(20). If you make these two columns Char(20), you code just works.
Aside: the referenced table must exist at the time when the referencing table is created - your code createst CUSTORDER before SUPPLIER. However I assume that's a typo when writing the question, otherwise you would be getting a different error: ORA-00942: table or view does not exist.
You also have a missing right parentheses at the end of each and every create table statement: I would consider these typos too.
Demo on DB Fiddle

I've created 'Staff' table. In that table it has a self referencing key

create table STAFF
(StaffID TINYINT IDENTITY NOT NULL,
StaffName varchar(20) NOT NULL,
Phone varchar(10) NOT NULL,
Gender char(01),
DoB date NOT NULL,
Mentor TINYINT,
Payment_ID TINYINT NOT NULL,
constraint staff_pk primary key (StaffID),
constraint staff_fk foreign key (Payment_ID) references PAYMENT(Payment_ID),
constraint mentor_fk foreign key (Mentor) references staff(StaffID)
);
when it is executed it gives the following error.
Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted
with the FOREIGN KEY SAME TABLE constraint "mentor_fk". The conflict
occurred in database "F_T", table "dbo.STAFF", column 'StaffID'. The
statement has been terminated.
Create the staff table first. Then add the foreign key:
create table STAFF (
StaffID TINYINT IDENTITY NOT NULL,
StaffName varchar(20) NOT NULL,
Phone varchar(10) NOT NULL,
Gender char(01),
DoB date NOT NULL,
Mentor TINYINT,
Payment_ID TINYINT NOT NULL,
constraint staff_pk primary key (StaffID),
constraint staff_fk foreign key (Payment_ID) references PAYMENT(Payment_ID)
);
alter table staff
add constraint mentor_fk foreign key (Mentor) references staff(StaffID);

SQL invalid identifier?

I finished typing out SQL statements but now I'm getting errors codes when I run it on omega. I keep getting the invalid identifier code...
Here's what I get once I ran it in omega.
SQL>
SQL> --question 14
SQL>
SQL> SELECT to_char(Avg(ProductPrice),'99,999.99') AS Avg_Price
2 FROM Product_mys;
SELECT to_char(Avg(ProductPrice),'99,999.99') AS Avg_Price
*
ERROR at line 1:
ORA-00904: "PRODUCTPRICE": invalid identifier
These are the sql tables where the data is being pulled from
CREATE TABLE Dept_mys (
DeptID Number(3) NOT NULL,
DeptName VARCHAR(20) NOT NULL,
PRIMARY KEY (DeptID)
) ;
CREATE TABLE Commission_mys (
CommClass CHAR(1) NOT NULL,
CommRate Number(2,2) NOT NULL,
PRIMARY KEY (CommClass)
) ;
CREATE TABLE Category_mys (
CatID Number(3) NOT NULL,
catName VARCHAR(20) NOT NULL,
PRIMARY KEY (CatID)
) ;
CREATE TABLE SalesRep_mys (
SalesRepID NUMBER(4) NOT NULL,
SalesRepFName VARCHAR(20) NOT NULL,
SalesRepLName VARCHAR(20) NOT NULL,
DeptID NUMBER(3) NOT NULL,
CommClass CHAR(1) NOT NULL,
PRIMARY KEY (SalesRepID),
FOREIGN KEY (DeptID) REFERENCES Dept_mys,
FOREIGN KEY (CommClass) REFERENCES Commission_mys
) ;
CREATE TABLE Customer_mys (
CustID CHAR(5) NOT NULL,
CustFName VARCHAR(20) NOT NULL,
CustLName VARCHAR(20) NOT NULL,
CustPhone CHAR(10),
SalesRepID NUMBER(4) NOT NULL,
PRIMARY KEY (CustID),
FOREIGN KEY (SalesRepID) REFERENCES SalesRep_mys
) ;
CREATE TABLE Order_mys (
OrderID NUMBER(3) NOT NULL,
OrderDate DATE NOT NULL,
CustID CHAR(5) NOT NULL,
PRIMARY KEY (OrderID),
FOREIGN KEY (CustID) REFERENCES Customer_mys
) ;
CREATE TABLE Product_mys (
ProductID NUMBER(3) NOT NULL,
ProductName VARCHAR(30) NOT NULL,
CatID Number(3) NOT NULL,
PRIMARY KEY (ProductID),
FOREIGN KEY (CatID) REFERENCES Category_mys
) ;
CREATE TABLE OrderDetail_mys (
OrderID NUMBER(3) NOT NULL,
ProductID NUMBER(3) NOT NULL,
ProductQty NUMBER(4) NOT NULL,
ProductPrice NUMBER(6,2) NOT NULL,
PRIMARY KEY (OrderID, ProductID),
FOREIGN KEY (OrderID) REFERENCES Order_mys,
FOREIGN KEY (ProductID) REFERENCES Product_mys
) ;
Your query references Sales_Rep_mys but you create SalesRep_mys. So that's at least some of the problem.
Same with Order_Detail_mys and OrderDetail_mys
Looks like those 2 fixes should do it.