Create a SQL table from an ERD, implementing all constraints - sql

This is the ERD diagram from which I'm to write a SQL query for:

Sql Server
Product Table
CREATE TABLE product
(
productid INT PRIMARY KEY IDENTITY(1, 1),
productname VARCHAR(50),
unitprice NUMERIC(17, 2)
)
Orders Table
CREATE TABLE orders
(
orderid INT PRIMARY KEY IDENTITY(1, 1),
OrderDate Datetime,
productid INT,
FOREIGN KEY (productid) REFERENCES product(productid)
)

This is for Oracle. You can create PRODUCT table similarly without FOREIGN KEY:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderDate date,
ProductID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (ProductID)
REFERENCES PRODUCT(ProductID)
);

CREATE TABLE product
(
ProductId int,
ProductnName varchar(50) not null,
UnitPrice NUMERIC(10, 2)
CONSTRAINT PRIMARY KEY (ProductId)
)
CREATE TABLE orders
(
orderid int auto_increment,
OrderDate Datetime,
ProductId int,
CONSTRAINT PRIMARY KEY (orderid)
CONSTRAINT FOREIGN KEY (ProductId) REFERENCES product(ProductId)
)

Related

Can have in my case foreign key duplicated value?

can have in this case foreign key duplicated value? Or better just have an index on column?
Here is my table structure:
CREATE TABLE customers(
id INT (10) NOT NULL,
name VARCHAR (50) NOT NULL,
city VARCHAR (50) NOT NULL
);
CREATE TABLE orders(
cus_id INT (10) NOT NULL ,
order_date DATETIME NOT NULL
);
CREATE TABLE products(
id INT (5) NOT NULL,
product_name VARCHAR(50) NOT NULL,
product_price INT(10) NOT NULL
);
But in orderitems table (Where I have stored the ordered products, the customer can have multiple products ordered so the foreign key value (cus_id) can be duplicated)
CREATE TABLE ordered_items(
id INT (10) NOT NULL,
cus_id INT (10) NOT NULL,
product_id INT(5) NOT NULL
);
ALTER TABLE customers ADD CONSTRAINT customer_id PRIMARY KEY ( id ) ;
ALTER TABLE orders ADD CONSTRAINT customers_id_fr FOREIGN KEY ( cus_id ) REFERENCES customers ( id );
ALTER TABLE ordered_items ADD CONSTRAINT ordered_items_fr FOREIGN KEY ( cus_id ) REFERENCES customers ( id );
EDIT:
Sorry the ordered_items table have a unique ID column as well.
Yes! you can have multiple value of cus_id inside ordered_items. however, your intention is better served if you replace cus_id by order_id from orders, Thus your relationship would sound like,
a **customer** can have multiple *orders*,
an **order** can have multiple *order items*,
and an **order item** can only have single *product*
your sql would look like this
CREATE TABLE customers(
id INT (10) NOT NULL,
name VARCHAR (50) NOT NULL,
city VARCHAR (50) NOT NULL
);
ALTER TABLE customers ADD CONSTRAINT customer_id PRIMARY KEY ( id ) ;
CREATE TABLE orders(
id INT (5) NOT NULL,
cus_id INT (10) NOT NULL ,
order_date DATETIME NOT NULL
);
ALTER TABLE orders ADD CONSTRAINT order_id PRIMARY KEY ( id ) ;
ALTER TABLE orders ADD CONSTRAINT customers_id_fr FOREIGN KEY ( cus_id ) REFERENCES customers ( id );
CREATE TABLE products(
id INT (5) NOT NULL,
product_name VARCHAR(50) NOT NULL,
product_price DOUBLE NOT NULL
);
ALTER TABLE products ADD CONSTRAINT product_id PRIMARY KEY ( id ) ;
CREATE TABLE ordered_items(
id INT (10) NOT NULL,
order_id INT (10) NOT NULL,
product_id INT(5) NOT NULL
);
ALTER TABLE ordered_items ADD CONSTRAINT ordrItm_id PRIMARY KEY ( id ) ;
ALTER TABLE ordered_items ADD CONSTRAINT ordrItm_order_frK FOREIGN KEY ( order_id ) REFERENCES orders ( id );
ALTER TABLE ordered_items ADD CONSTRAINT ordrItm_prd_frK FOREIGN KEY ( product_id) REFERENCES products ( id );

How to consolidate my data for SQL Join Clause

I have to write a query with the following criteria:
Write a query to list the title and artist of ONLY the items that have been ordered. Only list each title once.
Here are the CREATE tables that were made that cannot be changed.
CREATE TABLE artists
(
artist_id INT NOT NULL,
artist_name VARCHAR(30),
CONSTRAINT artist_pk PRIMARY KEY (artist_id)
);
CREATE TABLE items
(
item_id INT NOT NULL,
title VARCHAR(50) NOT NULL,
artist_id INT NOT NULL,
unit_price DECIMAL(9,2) NOT NULL,
CONSTRAINT items_pk PRIMARY KEY (item_id),
CONSTRAINT items_fk_artists
FOREIGN KEY (artist_id) REFERENCES artists (artist_id)
);
CREATE TABLE orders
(
order_id INT NOT NULL,
customer_id INT NOT NULL,
order_date DATE NOT NULL,
shipped_date DATE,
employee_id INT,
CONSTRAINT orders_pk PRIMARY KEY (order_id),
CONSTRAINT orders_fk_customers
FOREIGN KEY (customer_id) REFERENCES customers (customer_id),
CONSTRAINT orders_fk_employees
FOREIGN KEY (employee_id) REFERENCES employees (employee_id)
);
Here is what I have done for my script.
SELECT
items.title, artists.artist_name, orders.order_date
FROM
items
JOIN
orders
JOIN
artists;
Please let me know how I can consolidate.
You should say the structures of tables with respect to keys between tables.

SQL Server - Invalid Table

I am fairly new to SQL and I can't understand why I am receiving an error when establishing foreign keys as I receive an error saying that the destination table is invalid.
Below is the SQL code, any advice on how to fix would be brilliant! :)
The error appears regarding tblFilms and tblCinemaScreens.
CREATE TABLE tblCustomer (
CustomerID int,
CustomerSurname NVARCHAR(25),
CustomerForename NVARCHAR(20),
CustomerAge int,
CustomerPhoneNumber NVARCHAR(12),
CustomerEmailAddress NVARCHAR(100),
CONSTRAINT PK_tblCustomer PRIMARY KEY CLUSTERED (CustomerID)
)
GO
CREATE TABLE tblBookings (
BookingID int,
FilmShowings TIME,
PriceOfFilm MONEY,
DateOfBooking DATE,
FilmID int,
CinemaScreenID int,
CustomerID int,
CONSTRAINT PK_tblBookings PRIMARY KEY CLUSTERED (BookingID),
CONSTRAINT FK_FilmID FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID),
CONSTRAINT FK_CustomerID FOREIGN KEY (CustomerID) REFERENCES tblCustomer(CustomerID)
)
GO
CREATE TABLE tblFilms (
FilmID int,
FilmName VARCHAR(100),
FilmDuration int,
AgeRating VARCHAR(3),
CriticScore int,
FilmDescription NVARCHAR(300),
FilmGenre NVARCHAR(20),
FilmStartScreeningDate DATE,
FlimEndScreeningDate DATE,
CinemaScreenID int,
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
CONSTRAINT FK_tblFilms FOREIGN KEY (CinemaScreenID) REFERENCES tblCinemaScreens(CinemaScreenID)
)
GO
CREATE TABLE tblCinemaScreens (
CinemaScreenID int,
CinemaScreenType NVARCHAR(10),
NumberOfSeats int,
FilmID int,
CONSTRAINT PK_tblCinemaScreens PRIMARY KEY CLUSTERED (CinemaScreenID),
CONSTRAINT FK_tblCinemaScreens FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID)
)
GO
Cinema screens table does not need a film id and you need to create the tables BEFORE referencing them with FK's
CREATE TABLE tblCinemaScreens (
CinemaScreenID int,
CinemaScreenType NVARCHAR(10),
NumberOfSeats int,
FilmID int,
CONSTRAINT PK_tblCinemaScreens PRIMARY KEY CLUSTERED (CinemaScreenID)
GO
CREATE TABLE tblFilms (
FilmID int,
FilmName VARCHAR(100),
FilmDuration int,
AgeRating VARCHAR(3),
CriticScore int,
FilmDescription NVARCHAR(300),
FilmGenre NVARCHAR(20),
FilmStartScreeningDate DATE,
FlimEndScreeningDate DATE,
CinemaScreenID int,
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
CONSTRAINT FK_tblFilms FOREIGN KEY (CinemaScreenID) REFERENCES tblCinemaScreens(CinemaScreenID)
)
GO
CREATE TABLE tblCustomer (
CustomerID int,
CustomerSurname NVARCHAR(25),
CustomerForename NVARCHAR(20),
CustomerAge int,
CustomerPhoneNumber NVARCHAR(12),
CustomerEmailAddress NVARCHAR(100),
CONSTRAINT PK_tblCustomer PRIMARY KEY CLUSTERED (CustomerID)
)
GO
CREATE TABLE tblFilms (
FilmID int,
FilmName VARCHAR(100),
FilmDuration int,
AgeRating VARCHAR(3),
CriticScore int,
FilmDescription NVARCHAR(300),
FilmGenre NVARCHAR(20),
FilmStartScreeningDate DATE,
FlimEndScreeningDate DATE,
CinemaScreenID int,
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
CONSTRAINT FK_tblFilms FOREIGN KEY (CinemaScreenID) REFERENCES tblCinemaScreens(CinemaScreenID)
)
GO
You are trying to create a foreign key on tables before they are made. Comment out the lines in the create table statements that are giving you an error and create the tables. Once the tables are made create the missing foreign keys you need like this:
alter table tblFilms
add CONSTRAINT FK_tblFilms FOREIGN KEY (CinemaScreenID) REFERENCES tblCinemaScreens(CinemaScreenID)
alter table tblBookings
add CONSTRAINT FK_FilmID FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID)
The answer is they should have not direct relationships
A film is shown on 0 or more screens
You need a join table
rblFilmCinema
filmID fk to tblFilms
screenID fk to tblCinemaScreens
composite PK on filmID, screenID
I would change up the schema some to give yourself more flexibility. I would assume that a film can be on more than one cinema screen so I would take CinemaScreenID off of tblFilms and remove the foreign key. You can also remove FilmID from tblBookings since you have the CinemaScreenID already which has the FilmID.. Another thing to consider might be having multiple films on the same CinemaScreen which would be another tabled called tblCinemaScreenFilms and you would put that CinemaScreenFilmID on the tblBookings instead
CREATE TABLE tblFilms (
FilmID int,
...
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
)
GO
CREATE TABLE tblCustomer (
CustomerID int,
...
CONSTRAINT PK_tblCustomer PRIMARY KEY CLUSTERED (CustomerID)
)
GO
CREATE TABLE tblBookings (
BookingID int,
CinemaScreenID int,
CustomerID int,
...
CONSTRAINT PK_tblBookings PRIMARY KEY CLUSTERED (BookingID),
CONSTRAINT FK_CinemaScreenID FOREIGN KEY (CinemaScreenID ) REFERENCES tblCinemaScreens(CinemaScreenID),
CONSTRAINT FK_CustomerID FOREIGN KEY (CustomerID) REFERENCES tblCustomer(CustomerID)
)
GO
CREATE TABLE tblCinemaScreens (
CinemaScreenID int,
FilmID int,
...
CONSTRAINT PK_tblCinemaScreens PRIMARY KEY CLUSTERED (CinemaScreenID),
CONSTRAINT FK_tblCinemaScreens FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID)
)
GO
Option B (preferred)
CREATE TABLE tblCustomer (
CustomerID int,
...
CONSTRAINT PK_tblCustomer PRIMARY KEY CLUSTERED (CustomerID)
)
GO
CREATE TABLE tblFilms (
FilmID int,
...
CONSTRAINT PK_tblFilms PRIMARY KEY CLUSTERED (FilmID),
)
GO
CREATE TABLE tblCinemaScreens (
CinemaScreenID int,
...
CONSTRAINT PK_tblCinemaScreens PRIMARY KEY CLUSTERED (CinemaScreenID)
)
GO
CREATE TABLE tblCinemaScreenFilms (
CinemaScreenFilmID int,
CinemaScreenID int,
FilmID int
CONSTRAINT PK_tblCinemaScreenFilms PRIMARY KEY CLUSTERED (CinemaScreenFilmID),
CONSTRAINT FK_FilmID FOREIGN KEY (FilmID) REFERENCES tblFilms(FilmID),
CONSTRAINT FK_CinemaScreenID FOREIGN KEY (FilmID) REFERENCES tblCinemaScreens(CinemaScreenID)
)
GO
CREATE TABLE tblBookings (
BookingID int,
CustomerID int,
CinemaScreenFilmID int,
...
CONSTRAINT PK_tblBookings PRIMARY KEY CLUSTERED (BookingID),
CONSTRAINT FK_CustomerID FOREIGN KEY (CustomerID) REFERENCES tblCustomer(CustomerID),
CONSTRAINT FK_CinemaScreenFilmID FOREIGN KEY (CinemaScreenFilmID) REFERENCES tblCinemaScreenFilms(CinemaScreenFilmID)
)
GO
You're creating a table - tblFilms - and adding a foreign key to tblCinemaScreens before the second table has been created.
As a help I usually create all tables and then create any foreign key relationships and other constraints.

Designing a rudimentary Shopping Cart database

create table [User]
(
UserId int primary key identity(1,1),
FirstName nvarchar(256) not null,
LastName nvarchar(256) not null,
)
create table Product
(
ProductId int primary key identity(1,1),
UnitPrice decimal(18,2) not null, //For catalog purposes.
Name nvarchar(1000) not null,
Description nvarchar(max) not null,
Stock int not null
)
create table [Order]
(
OrderId int primary key identity(1,1),
UserId int foreign key references [User](UserId),
ProductId int foreign key references Product(ProductId),
UnitCost decimal(18,2) not null, //How much it actually cost when the person bought it.
ItemCount int not null,
Subtotal decimal(18,2) not null
)
create table OrderDetail
(
OrderDetailId int primary key identity(1,1),
?
I'm stuck on the database design of the order system.
A user can choose n products to add to a order request. Any suggestions?
Following some advice given here, how would this feel? Any pitfalls?
create table [User]
(
UserId int primary key identity(1,1),
FirstName nvarchar(256) not null,
LastName nvarchar(256) not null,
)
create table Product
(
ProductId int primary key identity(1,1),
UnitPrice decimal(18,2) not null,
Name nvarchar(1000) not null,
Description nvarchar(max) not null,
Stock int not null
)
create table [Order]
(
OrderId int primary key identity(1,1),
UserId int foreign key references [User](UserId),
DateOfOrder datetime not null
)
create table OrderDetail
(
OrderDetailId int primary key identity(1,1),
OrderId int foreign key references [Order](OrderId),
ProductId int foreign key references Product(ProductId),
UnitCost decimal(18,2) not null,
ItemCount int not null,
Subtotal decimal(18,2) not null
)
Typically, you'd have the Order table with the top-level order information (who, when etc) and then an OrderItem (or OrderDetail) table which has a row for each product that forms part of the order including columns like:
OrderId
ProductId
Quantity
etc
Good candidate for a PK on this OrderItem/OrderDetail table would be on OrderId + ProductId.
So where you have columns like ProductId, UnitCost, ItemCount etc in the Order table, those are in the wrong place and should be in the OrderItem/OrderDetail table.
Update:
To set up a compound PK, you can do:
create table OrderDetail
(
OrderId int foreign key references [Order](OrderId),
ProductId int foreign key references Product(ProductId),
...other columns...,
CONSTRAINT PK_OrderDetail PRIMARY KEY(OrderId, ProductId)
)

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)