SQL. How I can create 2 or more foreign keys in a table? [duplicate] - sql

This question already has answers here:
There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key
(4 answers)
Closed yesterday.
I want to create a table, that stores available books based on a QUANTITY value. If quantity > 0 this book is available. But I have an error:
Msg 1776, Level 16, State 0, Line 48
There are no primary or candidate keys in the referenced table 'BOOK_INFO' that match the referencing column list in the foreign key 'FK_QUANTITY'.
Msg 1750, Level 16, State 1, Line 48
Could not create constraint or index. See previous errors.
Code (the problem is table 'AVAILABLE_BOOKS'):
CREATE TABLE BOOKS
(
ID INT IDENTITY PRIMARY KEY,
BOOK_NAME VARCHAR(30) NOT NULL,
BOOK_AUTHOR VARCHAR(30) NOT NULL
)
CREATE TABLE BOOK_INFO
(
BOOK_ID INT PRIMARY KEY FOREIGN KEY REFERENCES BOOKS(ID),
QUANTITY INT DEFAULT 1 NOT NULL,
PRICE DECIMAL(5,2) NOT NULL,
CONSTRAINT CHECK_PRICE CHECK (PRICE > 0),
CONSTRAINT CHECK_QUANTITY CHECK (QUANTITY > 0)
)
CREATE TABLE ABAILABLE_BOOKS
(
BOOK_ID INT PRIMARY KEY,
QUANTITY INT DEFAULT 1 NOT NULL,
CONSTRAINT FK_BOOK_ID FOREIGN KEY (BOOK_ID) REFERENCES BOOKS(ID),
CONSTRAINT FK_QUANTITY FOREIGN KEY (QUANTITY) REFERENCES BOOK_INFO(QUANTITY),
CONSTRAINT CHECK_QUANTITY CHECK (QUANTITY > 0)
)
I was trying to change field declaration (QUANTITY INT -> QUANTITY INT DEFAULT 1 NOT NULL) ,
and many other things that didn't help.

You need to create an UNIQUE index on BOOK_INFO(QUANTITY)
CREATE TABLE BOOKS (
ID INT IDENTITY PRIMARY KEY,
BOOK_NAME VARCHAR(30) NOT NULL,
BOOK_AUTHOR VARCHAR(30) NOT NULL
)
CREATE TABLE BOOK_INFO (
BOOK_ID INT PRIMARY KEY FOREIGN KEY REFERENCES BOOKS(ID),
QUANTITY INT DEFAULT 1 NOT NULL,
PRICE DECIMAL(5,2) NOT NULL,
CONSTRAINT CHECK_PRICE CHECK (PRICE > 0),
CONSTRAINT CHECK_QUANTITY CHECK (QUANTITY > 0)
)
CREATE UNIQUE INDEX IX_BOOK_INFO_QUANTITY ON BOOK_INFO(QUANTITY)
CREATE TABLE ABAILABLE_BOOKS
(
BOOK_ID INT PRIMARY KEY,
QUANTITY INT DEFAULT 1 NOT NULL,
CONSTRAINT FK_BOOK_ID FOREIGN KEY (BOOK_ID) REFERENCES BOOKS(ID),
CONSTRAINT FK_QUANTITY FOREIGN KEY (QUANTITY) REFERENCES BOOK_INFO(QUANTITY),
CONSTRAINT ABAILABLE_BOOKS_CHECK_QUANTITY CHECK (QUANTITY > 0)
)

Related

How primary key in one table connect to other table with the same primary key?

How primary key in one table connect to another table with the same primary key?
I am trying to make it like this, which those two primary key in the table of CustomerCreditCard is connect to the table of Customer and table of Credit card]
https://i.stack.imgur.com/lIBUE.png
--3
CREATE TABLE Customer
(
CustomerID INT IDENTITY PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
);
--5
CREATE TABLE CreditCard
(
CreditCardNumber VARCHAR(16) PRIMARY KEY,
CreditCardOwnerName VARCHAR(50) NOT NULL,
);
--6
CREATE TABLE CustomerCreditCard
(
CreditCardNumber VARCHAR(16) NOT NULL,
CustomerID INT IDENTITY NOT NULL,
PRIMARY KEY(CreditCardNumber, CustomerID)
);
--6
CREATE TABLE CustomerCreditCard
(
CreditCardNumber VARCHAR(16) NOT NULL,
CustomerID INT NOT NULL,
CONSTRAINT pk_CustomerCreditCard
PRIMARY KEY(CreditCardNumber,CustomerID ),
CONSTRAINT fk_CustomerCreditCard_CreditCardNumber
FOREIGN KEY(CreditCardNumber)
REFERENCES CreditCard(CreditCardNumber)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_CustomerCreditCard_CustomerID
FOREIGN KEY(CustomerID)
REFERENCES Customer(CustomerID)
ON DELETE CASCADE ON UPDATE CASCADE
);
To solve the problem of this question, add the foreign key to the table that has two primary keys, then reference to other tables that you want to connect with the same primary key.

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

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

Problem with Constraint or Index SQL when Creating a Table

I'm currently working on an assignment and have run into an issue.
I get an error:
Msg 8135, Level 16, State 0, Line 41
Table level constraint or index does not specify column list, table 'Sessions'.
I've run through it a million times, but I cannot find out where the issue arises. I believe I AM specifying the columns in both table-level statements, so I am at a loss.
Here is the code:
CREATE TABLE Class
(
-- Column specifications and constraints--
ClassID NCHAR(6) NOT NULL,
ClassDescription NVARCHAR(50) NOT NULL,
--Table constraints--
CONSTRAINT pk_Class_ClassID
PRIMARY KEY (ClassID) --ClassID is the primary key in the Class table, done as a table constraint
)
CREATE TABLE Riders
(
-- Column specifications and constraints--
RiderID INT NOT NULL IDENTITY(10, 1) --RiderID auto-fills in the value, starting at 10, incrementing by 1
CONSTRAINT pk_Riders_RiderID PRIMARY KEY, --RiderID is the primary key in the Riders table
[Name] NVARCHAR(50) NOT NULL
CONSTRAINT chk_Riders_Name CHECK (LEN([Name]) > 4), --Name must be longer than 4 letters
ClassID NCHAR(6) NULL,
--Table constraints--
CONSTRAINT fk_Riders_Class
FOREIGN KEY (ClassID) REFERENCES Class (ClassID)
)
CREATE TABLE [Sessions]
(
-- Column specifications and constraints--
RiderID INT NOT NULL,
BikeID NCHAR(6) NOT NULL,
SessionDate DATETIME NOT NULL
CONSTRAINT chk_Sessions_SessionDate CHECK (SessionDate > '1 Sep 2017'), --SessionDate must be AFTER September 1, 2017
Laps INT NULL,
-- Table constraints--
CONSTRAINT pk_Sessions_RiderID_BikeID_SessionDate
PRIMARY KEY (RiderID, BikeID, SessionDate), --RiderID, BikeID, SessionDate is the composite primary key for the Sessions table
INDEX CI_Sessions_RiderID_BikeID ON [Sessions] (RiderID, BikeID) --Index RiderID and BikeID
)
CREATE TABLE Bikes
(
-- Column specifications and constraints--
BikeID NCHAR(6) NOT NULL
CONSTRAINT chk_Bikes_BikeID CHECK (BikeID LIKE '[0-9][0-9][0-9][HYS]-[AP]') --BikeID in format ###X-A # = 0 - 9, X = H(Honda), Y(Yamaha), S(Suzuki), A = A(AM), P(PM)
CONSTRAINT pk_Bikes_BikeID PRIMARY KEY, --BikeID is the primary key in the Bikes table
StableDate DATE NOT NULL
CONSTRAINT def_Bikes_StableDate DEFAULT GETDATE()
)
ALTER TABLE [Sessions]
ADD CONSTRAINT chk_Sessions_Laps CHECK (Laps >= 10)
ALTER TABLE [Sessions]
ADD CONSTRAINT fk_Sessions_Riders
FOREIGN KEY (RiderID) REFERENCES Riders (RiderID)
ALTER TABLE [Sessions]
ADD CONSTRAINT fk_Sessions_Bikes
FOREIGN KEY (BikeID) REFERENCES Bikes (BikeID)
Any help is appreciated!!
Just remove ON [Sessions] from index definition and write as:
CREATE TABLE [Sessions]
(
--Field specifications and constraints--
RiderID int not null,
BikeID nchar(6) not null,
SessionDate datetime not null
constraint chk_Sessions_SessionDate check (SessionDate > '1 Sep 2017'), --SessionDate must be AFTER September 1, 2017
Laps int null,
--Table constraints--
constraint pk_Sessions_RiderID_BikeID_SessionDate primary key (RiderID, BikeID, SessionDate), --RiderID, BikeID, SessionDate is the composite primary key for the Sessions table
INDEX CI_Sessions_RiderID_BikeID (RiderID, BikeID) --Index RiderID and BikeID
)
You can check which indexes are created using following script:
SELECT OBJECT_NAME(object_id) AS table_name,
name AS index_name,
type, type_desc
FROM sys.indexes
WHERE object_id = OBJECT_ID(N'dbo.Sessions', N'U');
Demo here..
This error can occur if you use the keyword "Index" or "index" as a column name in your sql table. To fix this, use "indx" or something else.

Database Create table Primary key not found

I have two tables i'm trying to create with foreign keys.
The statements are below
Book_Copy Table
CREATE TABLE book_copy (
bid NUMBER(15) NOT NULL,
isbn VARCHAR(15) NOT NULL,
firstavaib VARCHAR(9) NOT NULL,
outservice VARCHAR(9) NULL,
CONSTRAINT primary_key PRIMARY KEY ( bid,isbn ),
FOREIGN KEY ( isbn )
REFERENCES book_catalog ( isbn )
);
History table
CREATE TABLE history (
bid NUMBER(15) NOT NULL,
mid NUMBER(10) NOT NULL,
FOREIGN KEY ( mid )
REFERENCES member ( mid ),
datetaken VARCHAR(9) NOT NULL,
datereturn VARCHAR(9) NULL,
FOREIGN KEY ( bid )
REFERENCES book_copy ( bid ),
CONSTRAINT primary_key PRIMARY KEY ( bid, datetaken )
);
Now when I run it the first one says table created but i get the following for the second.
CREATE TABLE history (
bid NUMBER(15) NOT NULL,
mid NUMBER(10) NOT NULL,
FOREIGN KEY ( mid )
REFERENCES member ( mid ),
datetaken VARCHAR(9) NOT NULL,
datereturn VARCHAR(9) NULL,
FOREIGN KEY ( bid )
REFERENCES book_copy ( bid ),
CONSTRAINT primary_key PRIMARY KEY ( datetaken )
)
*
ERROR at line 1:
ORA-02270: no matching unique or primary key for this column-list
There are several errors in the statements above and also not all the relevant information was made available.
Your table book_copy has a foreign key reference to the table book_catalog via the isbn column:
CREATE TABLE book_copy (
...
FOREIGN KEY ( isbn )
REFERENCES book_catalog ( isbn )
To proceed, I took the liberty to add a simple one:
CREATE TABLE book_catalog (
isbn VARCHAR(15) NOT NULL,
CONSTRAINT pk_ct PRIMARY KEY (isbn));
And similar, they history table also references another table member via the mid column:
CREATE TABLE history (
...
FOREIGN KEY ( mid )
REFERENCES member ( mid ),
I also create that one in order to proceed:
CREATE TABLE MEMBER (
mid NUMBER(10) NOT NULL,
CONSTRAINT pk_mem PRIMARY KEY (mid));
The error that you get above means what it says: There is no such primary key or unique key on the other table that you try to reference, hence a value cannot be uniquely identified and hence the integrity of the data not verified. So the database stops you from doing so in the first place.
The culprit is that you specify the PRIMARY KEY of your table book_copy to be bid,isbn while your foreign key reference in the history table only references the bid:
CREATE TABLE history (
...
FOREIGN KEY ( bid )
REFERENCES book_copy ( bid ),
So you ask the database to check the integrity on something that is not uniquely identifiable. In order to solve this you have to expand your foreign key of the history table to include the isbn column as well:
So the full DDL looks like this:
CREATE TABLE book_catalog (
isbn VARCHAR(15) NOT NULL,
CONSTRAINT book_catalog_pk PRIMARY KEY (isbn));
CREATE TABLE MEMBER (
mid NUMBER(10) NOT NULL,
CONSTRAINT member_pk PRIMARY KEY (mid));
CREATE TABLE book_copy (
bid NUMBER(15) NOT NULL,
isbn VARCHAR(15) NOT NULL,
firstavaib VARCHAR(9) NOT NULL,
outservice VARCHAR(9) NULL,
CONSTRAINT book_copy_pk PRIMARY KEY ( bid,isbn ),
FOREIGN KEY ( isbn )
REFERENCES book_catalog ( isbn )
);
CREATE TABLE history (
bid NUMBER(15) NOT NULL,
mid NUMBER(10) NOT NULL,
isbn VARCHAR2(15) NOT NULL,
FOREIGN KEY ( mid )
REFERENCES member ( mid ),
datetaken VARCHAR(9) NOT NULL,
datereturn VARCHAR(9) NULL,
FOREIGN KEY ( bid, isbn )
REFERENCES book_copy ( bid, isbn ),
CONSTRAINT history_pk PRIMARY KEY ( bid, datetaken )
);
There is another problem in your DDL above. In Oracle, constraint names are globally unique! That means that whatever you put after CONSTRAINT has to be unique. In the case above you use the same name primary_key for both your tables which will fail with an ORA-02264: name already used by an existing constraint error on creating the history table. You will see that I have given the primary key constraints on the tables more meaningful names.
Err: Foreign key(BID) references Book_Copy(BID)
The primary key of Book_Copy is (BID, DateTaken) not just (BID)
You need a primary or unique constraint in the target table referenced in a FK of another table.
1) Add DateTaken to you FK definition on HISTORY or replace the FK with a CHECK constraint something like (EXISTS (select * from book_copy c where c.BID = BID)

Alter Table syntax Assignment

I have Assignment due in which i'm stuck on a question.
Add a “Sales Detail” table to your database. This table is related to the Orders and Products tables. It shows the product and quantity ordered at least (add other fields if you wish but explain why you added them on your paper).
There is no description of this table on the diagram provided. Use your best database design skills here!
Create Table SalesDetail
(
SaleDetailID int,
ProductID char(5),
ManufactureID char(3) not null,
OrderNo int,
qtyOrdered int
PRIMARY
)
Alter Table SalesDetail
Add FOREIGN KEY (ProductID)
REFERENCES Products(ProductID)
My Error is I can not get it to link SalesDetail table to Products table.
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'Products' that match the referencing column list in the foreign key 'FK__SalesDeta__Produ__5EBF139D'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
Create Table Customers
(
CustomerNo char(4)
Constraint ck_CustomerNoHas4positionsWithNumbers
Check(CustomerNo like'[0-9],[0-9],[0-9],[0-9]'),
Company varchar(50) not null,
CustomerRep char(3),
CreditLimt money default(20000.00),
PRIMARY KEY(CustomerNo)
)
Create Table Salesreps
(
EmployeeNo char(3)
Constraint ck_EmployeeNoHasDigits check(EmployeeNo like'[0-9],[0-9],[0-9]'),
FirstName varchar(25) not null,
LastName varchar(25) not null,
Age int,
SalesRepOffice char(2) not null,
Title varchar(50),
HireDate Date not null,
Manager char(3) not null,
Quota money,
Sales money not null,
PRIMARY KEY(EmployeeNo)
)
Create Table Offices
(
Office char(2) Constraint ck_checkOfficeHasNumbersOnly check(Office like'[0-9],[0-9]'),
City varchar(25) not null,
Region varchar(10) not null,
Manager char(3) not null,
Target money,
Sales money not null
PRIMARY KEY(Office)
)
Create Table Orders
(
OrderNo int,
OrderDate Date not null,
CustomerNo char(4) not null,
SalesRep char(3) not null
PRIMARY KEY(OrderNo)
)
Create Table Products
(
ManufactureID char(3)
Constraint ck_ManufactureIDifItHasLettersOnly check(ManufactureID like'[a-z],[a-z],[a-z]'),
ProductID char(5)
Constraint ck_ProductIDhasTwoLettersAndThreeNumbers check(ProductID like'[0-9],[0-9],[a-z],[a-z],[a-z]'),
Description varchar(50) not null,
Price money not null,
QtyOnHand int not null,
PRIMARY KEY(ManufactureID, ProductID)
)
--Add Foreign Keys to all tables who needs them
Alter Table Customers
Add constraint fk_customerrep
FOREIGN KEY (CustomerRep)
REFERENCES Salesreps(EmployeeNo)
Alter Table Salesreps
Add constraint fk_salesrepoffice
FOREIGN KEY (SalesRepOffice)
REFERENCES Offices(Office),
constraint fk_manager
FOREIGN KEY (Manager)
REFERENCES Salesreps(EmployeeNo)
Alter Table Offices
Add constraint fk_officesmanger
FOREIGN KEY (Manager)
REFERENCES Salesreps(EmployeeNo)
Alter Table Orders
Add constraint fk_customerno
FOREIGN KEY (CustomerNo)
REFERENCES Customers(CustomerNo),
constraint fk_salesrep
FOREIGN KEY (SalesRep)
REFERENCES Salesreps(EmployeeNo)
The table Products has a composite key (ManufactureID, ProductID), so you cannot uniquely identify a product by just the ProductId. Therefore you have to create a composite foreign key that references to both ManufactureId and ProductID:
Alter Table SalesDetail
Add FOREIGN KEY (ManufactureId, ProductID)
REFERENCES Products(ManufactureID, ProductID)
ProductID is not a primary key like the error says. In your code
PRIMARY KEY(ManufactureID, ProductID)
This creates a primary key that both of those columns combined.
The primary key for Products is (ManufactureID, ProductID). So the SalesDetail table should contain both these columns, and both should be part of the foreign key constraint:
Alter Table SalesDetail
Add FOREIGN KEY (ManufactureID, ProductID)
REFERENCES Products(ManufactureID, ProductID)