Problem with Constraint or Index SQL when Creating a Table - sql

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.

Related

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

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

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)

SQL Server : there are no primary or candidate keys in the referenced table

I using SQL Server 2008, and when I try create a new table, in existing DB, this error appears:
There are no primary or candidate keys in the referenced table 'parceria_conta_corrente_ao' that match the referencing column list in the foreign key 'R_795'.
This table exists:
And I try create a new table with this code:
CREATE TABLE parceria_item_resgate_rateio_aux
(
id_parceria_item_resgate_rateio_aux int NOT NULL IDENTITY,
dt_conta_corrente DATETIME NOT NULL ,
id_periodo BIGINT NOT NULL ,
id_ao bigint NOT NULL ,
id_gr_cliente int NOT NULL ,
id_cliente BIGINT NOT NULL ,
data_importacao_cli_gr_cli DATETIME NOT NULL ,
hp2 varchar(50) NOT NULL ,
hp2_filho varchar(50) NOT NULL ,
valor_nc decimal(18,2) NULL ,
datetime_inclusion datetime NOT NULL ,
status int NULL ,
CONSTRAINT XPKparceria_item_resgate_ PRIMARY KEY CLUSTERED
(id_parceria_item_resgate_rateio_aux ASC,
dt_conta_corrente ASC,
id_periodo ASC,
id_ao ASC,
id_gr_cliente ASC,
id_cliente ASC,
data_importacao_cli_gr_cli ASC,
hp2 ASC),
CONSTRAINT R_795 FOREIGN KEY(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2)
REFERENCES parceria_conta_corrente_ao(dt_conta_corrente, id_periodo, id_ao, id_gr_cliente, id_cliente, data_importacao_cli_gr_cli, hp2)
ON DELETE CASCADE
ON UPDATE CASCADE
)
go
Where is the problem?
You need to create a unique index on the referenced table:
CREATE UNIQUE INDEX UX_parceria_conta_corrente_ao
ON parceria_conta_corrente_ao
(
dt_conta_corrente,
id_periodo,
id_ao,
id_gr_cliente,
id_cliente,
data_importacao_cli_gr_cli,
hp2
)
EDIT:
I guess the columns are not in the same order, columns in primary key must be in the same order than the columns in the foreing key.
If you execute the following:
CREATE TABLE T
(
C1 int NOT NULL,
C2 int NOT NULL,
PRIMARY KEY (C1, C2)
)
CREATE TABLE T2
(
id INT NOT NULL,
C1 int NOT NULL,
C2 int NOT NULL,
CONSTRAINT FK1 FOREIGN KEY (C2, C1) REFERENCES T(C2, C1)
)
You get the following error:
Msg 1776, Level 16, State 0, Line 9 There are no primary or candidate
keys in the referenced table 'T' that match the referencing column
list in the foreign key 'FK1'. Msg 1750, Level 16, State 0, Line 9
Could not create constraint or index. See previous errors.

Understanding how a Primary Key of one Table can be a Foreign Key too

I've been given the code below:
-- Create Customers table
CREATE TABLE Customers
(
cust_id char(10) NOT NULL ,
cust_name char(50) NOT NULL ,
cust_address char(50) NULL ,
cust_city char(50) NULL ,
cust_state char(5) NULL ,
cust_zip char(10) NULL ,
cust_country char(50) NULL ,
cust_contact char(50) NULL ,
cust_email char(255) NULL
);
-- Create OrderItems table
CREATE TABLE OrderItems
(
order_num int NOT NULL ,
order_item int NOT NULL ,
prod_id char(10) NOT NULL ,
quantity int NOT NULL ,
item_price decimal(8,2) NOT NULL
);
-- Create Orders table
CREATE TABLE Orders
(
order_num int NOT NULL ,
order_date datetime NOT NULL ,
cust_id char(10) NOT NULL
);
-- Create Products table
CREATE TABLE Products
(
prod_id char(10) NOT NULL ,
vend_id char(10) NOT NULL ,
prod_name char(255) NOT NULL ,
prod_price decimal(8,2) NOT NULL ,
prod_desc varchar(1000) NULL
);
-- Create Vendors table
CREATE TABLE Vendors
(
vend_id char(10) NOT NULL ,
vend_name char(50) NOT NULL ,
vend_address char(50) NULL ,
vend_city char(50) NULL ,
vend_state char(5) NULL ,
vend_zip char(10) NULL ,
vend_country char(50) NULL
);
-- Define primary keys
ALTER TABLE Customers WITH NOCHECK ADD CONSTRAINT PK_Customers PRIMARY KEY CLUSTERED (cust_id);
ALTER TABLE OrderItems WITH NOCHECK ADD CONSTRAINT PK_OrderItems PRIMARY KEY CLUSTERED (order_num, order_item);
ALTER TABLE Orders WITH NOCHECK ADD CONSTRAINT PK_Orders PRIMARY KEY CLUSTERED (order_num);
ALTER TABLE Products WITH NOCHECK ADD CONSTRAINT PK_Products PRIMARY KEY CLUSTERED (prod_id);
ALTER TABLE Vendors WITH NOCHECK ADD CONSTRAINT PK_Vendors PRIMARY KEY CLUSTERED (vend_id);
-- Define foreign keys
ALTER TABLE OrderItems ADD
CONSTRAINT FK_OrderItems_Orders FOREIGN KEY (order_num) REFERENCES Orders (order_num),
CONSTRAINT FK_OrderItems_Products FOREIGN KEY (prod_id) REFERENCES Products (prod_id);
ALTER TABLE Orders ADD
CONSTRAINT FK_Orders_Customers FOREIGN KEY (cust_id) REFERENCES Customers (cust_id);
ALTER TABLE Products ADD
CONSTRAINT FK_Products_Vendors FOREIGN KEY (vend_id) REFERENCES Vendors (vend_id);
I have a couple of questions:
What's the purpose of the Composite Key in table Orders?
Since order_num is a Primary Key as well as Foreign Key, I can't
understand how it can be Clustered in one table and
Non-Clustered in another.
Also, I don't understand the purpose of WITH NOCHECK when defining
the Primary Keys.
Thanks
What does order_item mean? From the look of things, you can remove it from the PK.
An FK basically says "the value here must be one of the values in that other table". Think of a dropdown box: the list of available choices is provided that the column in the REFERENCES ... (...) clause. CLUSTERED has no impact on it. You can make an FK references non-primary key column too.
When you create the primary key, SQL Server checks the table to ensure that the PK column contains no duplicate value. WITH NOCHECK disables check on existing data, but will check for any new data coming into the table. Its usage is not recommended.

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)