integrity constraint in Oracle - database

Suppose that a table named SuplProd has the columns supplier and product and two entries: (Sony Ericcson, Xperia) and (Apple, iPhone).
I would like to create a table named Orders with columns supplier, product and quantity.
However, I'd like the combination (supplier, product) of table Orders to be limited to contain only entries from SuplProd.
For example, the entry (Sony Ericcson, Xperia, 1) would be valid for the table Orders whereas (Apple, Xperia, 1) would not.
How is this possible in Oracle?

You should create a foreign key in orders table:
create table SuplProd (
supplier ...,
product ...,
constraint SuplProd_pk
primary key( supplier, product)
)
create table Orders
...
supplier ...,
product ...,
qty,
constraint SuplProd_pk
primary key( ... ),
constraint orders_to_suplprod_fk
foreign key ( supplier, product)
references SuplPRod (supplier, product)
)

Related

How to model this many-many relation in Database?

We have two tables ManagementPlan which tells what type of product model has to be used.Based on this model number, a particular product of that type is assigned to a patient during therapy session.How can we model the many-many relation between Product table and ManagementPlan table
MangamentPlan(
PlanID(PK),
DiagnosisID(FK),
PhysicianID(FK),
PMCModelID,
Objective,
Description,
DateTime
)
Product(
PMCProductID(PK),
ManuProductID(FK),
ManufacturerID(FK),
PMCModelID,
Manufacturer model,
Features description,
PurchaseDate,
Storage Location
)
Add a junction table:
ManagementPlanProduct(PlanID(PK, FK(ManagementPlan)), PMCProductID(PK, FK(Product)))
You need a junction table
ManagementPlanProduct (
PlanID (PK, FK)
PMCProductID (PK, FK)
)
CREATE TABLE ManagementPlanProduct (
PlanID int NOT NULL,
PMCProductID int NOT NULL,
CONSTRAINT PK_mpp PRIMARY KEY CLUSTERED (PlanID, PMCProductID)
);
ALTER TABLE ManagementPlanProduct
ADD CONSTRAINT FK_mpp_mp
FOREIGN KEY (PlanID) REFERENCES ManagementPlan (PlanID)
ON DELETE CASCADE;
ALTER TABLE ManagementPlanProduct
ADD CONSTRAINT FK_mpp_p
FOREIGN KEY (PMCProductID) REFERENCES Product (PMCProductID)
ON DELETE CASCADE;
You can also add other columns to the junction table like quantity, date added, sort order and so on.

SQL creating a join between two tables

I want to create three tables.
Orders (contains an order ID and a customer name)
Products (contains a Product ID, description, and price)
Line Item (contains Order ID, Line Item ID, Product ID, and Quantity)
I want my web app to allow a customer to select an order number, and as a result, it will display the products that are in that order, the quantity of said products, the price of the products, and a total price of order that will be calculated on the fly in my code behind.
My SQL looks like this
CREATE TABLE Products
(
ProductID int NOT NULL,
ProductDescription varchar(MAX) NOT NULL,
ProductPrice smallmoney NOT NULL,
PRIMARY KEY (ProductID)
)
CREATE TABLE Orders(
OrderID int NOT NULL,
CustomerName varchar(MAX) NOT NULL,
PRIMARY KEY (OrderID)
)
CREATE TABLE LineItem(
LineItemID int NOT NULL,
OrderID int NOT NULL FOREIGN KEY REFERENCES Orders(OrderID),
ProductID int NOT NULL FOREIGN KEY REFERENCES Products(ProductID),
Quantity int NOT NULL,
PRIMARY KEY (LineItemID)
)
Here is the database diagram with the relationships.
Here is the result of a select all statement on all the tables
Are my relationships set up correctly for what I want to achieve? I'm sorry if this seems simple but I'm new to this and while the SQL Statements are pretty easy, the way to relate tables is not.
SELECT p.ProductPrice, p.ProductDescription, o.CustomerName, l.Quantity
FROM LineItem AS l
INNER JOIN Products AS p ON l.ProductID=p.ProductID
INNER JOIN Orders AS o ON l.OrderID=o.OrderID
ORDER BY l.LineItemID
will provide combined information from all of these tables. You may add any additional columns which you want to fetch data from.
INNER JOIN and JOIN keywords are syntactic sugar, which have same effect. While you're binding two tables by INNER JOIN, only results which contained in both of these tables will be returned.
With the ON keyword, you are defining the relational columns of tables. For example, in the clause INNER JOIN Products AS p ON l.ProductID=p.ProductID, I'm defining that the data are relational in column ProductID of table Products with column ProductID of table LineItem.
You have a many-to-many relationship between Products and Orders so in the structure of LineItem table I think you already have have the primary key (Product Id,OrderID) and I think you do not need to LocalItemID
CREATE TABLE LineItem(
OrderID int NOT NULL FOREIGN KEY REFERENCES Orders(OrderID),
ProductID int NOT NULL FOREIGN KEY REFERENCES Products(ProductID),
Quantity int NOT NULL,
PRIMARY KEY (OrderID ,ProductID )
)
and you can join the tables using this:
SELECT p.ProductPrice, o.CustomerName, li.Quantity
FROM LineItem AS li
JOIN Products AS p ON li.ProductID=p.ProductID
JOIN Orders ON li.OrderID=o.OrderID

Can a foreign key of a table be a part of the composite primary key of the same table?

Suppose I have two tables: A (with columns: a,b,c,d) and B (with columns: x,y,z). Now, (a,b) together make the primary key for table A and x is the primary key of table B. Is it possible to make b a foreign key of table A that refers x from table B?
Please reply ASAP!
Thanks in advance! :-)
Yes, there is no issue with that. A classic example (using MySQL for demonstration purposes) is a database table holding a number of companies and another holding employees which can work for any one of those companies:
create table companies (
id int primary key,
name varchar(20));
create table employees (
id int,
c_id varchar(20) references companies(id),
name varchar(20),
primary key (id, c_id));
insert into companies (id, name) values (1, 'ABC');
insert into companies (id, name) values (2, 'DEF');
insert into companies (id, name) values (3, 'HIJ');
insert into employees (id, c_id, name) values (101, 1, "Allan");
insert into employees (id, c_id, name) values (102, 1, "Bobby");
insert into employees (id, c_id, name) values (101, 2, "Carol");
insert into employees (id, c_id, name) values (101, 3, "David");
Note that the primary key for employees is a composite key made up of the employee ID and company ID. Note also that the company ID is a foreign key constraint on the primary key of companies, the exact situation (functionally) that you asked about.
The query showing who works for what company shows this in action:
select c.id, c.name, e.id, e.name
from companies c, employees e
where c.id = e.c_id
order by c.id, e.id
c.id c.name e.id e.name
---- ------ ---- ------
1 ABC 101 Allan
1 ABC 102 Bobby
2 DEF 101 Carol
3 HIJ 101 David
Can a column in a composite primary key also be a foreign key referencing a primary key of another table? Of course it can. The important question is, when is this a good idea?
The most common scenario is probably the intersection or junction table. Customers can have more than one Address (Shipping, Billing, etc) and Addresses can have more than one Customer using them. So the table CUSTOMER_ADDRESSES has a primary key which references both CUSTOMER and ADDRESS primary key (and for bonus points the ADDRESS_TYPE reference data table too).
My examples use Oracle 12c syntax:
create table customer_address
( customer_id number(38,0) not null
, address_id number(38,0) not null
, address_type_code varchar2(3) not null
, constraint customer_address_pk primary key
(customer_id, address_id, address_type_code)
, constraint customer_address_customer_fk foreign key
(customer_id) references customer(customer_id)
, constraint customer_address_address_fk foreign key
(address_id) references address(address_id)
, constraint customer_address_type_fk foreign key
(address_type_code) references address_type(address_type_code)
);
The second scenario occurs when the primary key of the child table is comprises the parent key and an identifier (usually a number) which is only unique within the parent key. For instance, an Order has an Order Header and some Order Lines. The Order is identified by the Order Header ID and its lines are identified by a monotonically incrementing number. The ORDER_LINE table may look like this:
create table order_line
( order_header_id number(38,0) not null
, order_line_no number(38,0) not null
, product_id number(38,0) not null
, qty number(38,0) not null
, constraint order_line_pk primary key
(order_header_id, order_line_no)
, constraint order_line_header_fk foreign key
(order_header_id) references order_header(order_header_id)
, constraint order_line_product_fk foreign key
(product_id) references product(product_id)
);
Note that we could model ORDER_LINE as another intersection table, with a primary key of (order_header_id, product_id) and relegate order_line_no to the status of ordinary attribute: it depends on the business rules we must represent.
This second scenario is rarer than you might think: composite primary keys are pretty rare in real life. For instance, I think the model presented in that other answer is weak. The chances are we will need to use Employee as a foreign key for a number of relationships (e.g. Manager, Assignment, Sales). Using a composite key for foreign keys is clumsy (more typing!). Furthermore, when we drill into these models we often find that one of the key columns is a natural key rather than a primary key, and so might be subject to change. Cascading changes to natural key columns in composite foreign keys is a PITN.
Hence it is common practice to use a surrogate (or synthetic) primary key, say using a sequence or identify column, and enforce the natural key with a unique constraint. The latter step is often forgotten but it is crucial to maintaining referential integrity. Given a situation in which we need to store details of Employees from several Companies, including the Companies' Employee Identifier we might have an EMPLOYEE table like this:
create table employee
( employee_id number(38,0) generated always as number
, company_id number(38,0) not null
, company_employee_id varchar2(128) not null
, name varchar2(128) not null
, constraint employee_pk primary key
(employee_id)
, constraint employee_uk unique
(company_id, company_employee_id)
, constraint employee_company_fk foreign key
(company_id) references company(company_id)
);
One situation where it is common to find composite primary keys cascaded to dependent tables is in data warehouses and other VLDBs. Here the composite key columns form part of a denormalization strategy to support Partitioning schemes and/or efficient access paths.

How do foreign keys work?

I've mostly used MyISAM tables before, which don't support foreign keys. Looking on stack overflow I didn't find a nice, concise explanation of what a foreign key is actually doing. I'm mostly interested in join tables, where you would have a schema like this:
customers
id category_id
products
id category_id
categories
id
customerproducts
customer_id product_id
If I have foreign keys on customerproducts, it will ensure that only valid customers and only valid products get into that table, but what about if I try to add a Product from the phones category to a customer earmarked as one only interested in copiers? Will this cause the foreign key constraints to be violated?
I'm mostly interested in join tables, where you would have a schema like this:
You wouldn't have a schema like that--it doesn't represent the facts you're interested in. Let's sketch out some tables in SQL. (Tested in PostgreSQL) First, customers and products.
-- Customer names aren't unique.
create table customers (
cust_id integer primary key,
cust_name varchar(15) not null
);
insert into customers values (1, 'Foo'), (2, 'Bar');
-- Product names are unique.
create table products (
prod_id integer primary key,
prod_name varchar(15) not null unique
);
insert into products values
(150, 'Product 1'), (151, 'Product 2'), (152, 'Product 3');
There are different categories for products.
create table categories (
cat_name varchar(15) primary key
);
insert into categories values ('Cable'), ('Networking'), ('Phones');
Each product might appear in several categories.
create table product_categories (
prod_id integer not null references products,
cat_name varchar(15) not null references categories,
primary key (prod_id, cat_name)
);
insert into product_categories values
(150, 'Cable'), (150, 'Networking'), (151, 'Networking'), (152, 'Phones');
A customer might be interested in several categories of products.
create table customer_category_interests (
cust_id integer not null references customers,
cat_name varchar(15) not null references categories,
primary key (cust_id, cat_name)
);
-- Nobody's interested in phones
insert into customer_category_interests values
(1, 'Cable'), (1, 'Networking'), (2, 'Networking');
If I have foreign keys on customerproducts, it will ensure that only
valid customers and only valid products get into that table, but what
about if I try to add a Product from the phones category to a customer
earmarked as one only interested in copiers?
Customers aren't interested in every product in their preferred categories. Note the overlapping foreign key constraints.
create table product_interests (
cust_id integer not null,
prod_id integer not null,
cat_name varchar(15) not null,
foreign key (cust_id, cat_name) references customer_category_interests,
foreign key (prod_id, cat_name) references product_categories,
primary key (cust_id, prod_id, cat_name)
);
insert into product_interests values
(1, 150, 'Cable'), (2, 150, 'Networking');
This next insert will fail, because customer 1 isn't interested in phones.
insert into product_interests values
(1, 152, 'Phones');
ERROR: insert or update on table "product_interests" violates foreign key constraint "product_interests_cust_id_fkey"
DETAIL: Key (cust_id, cat_name)=(1, Phones) is not present in table "customer_category_interests".

multiple prices 1 item

I'm wondering if this would be the best way to build a table for an item that can have more than 1 price. Each product is identified by its model_number. Should I use a prefix before the model_number for each individual seller? I can't use model_number for the primary key. For example:
seller_product_id model_number seller price
SELLER_1_MODEL_NUMBER MODEL_NUMBER seller_1 9.99
SELLER_2_MODEL_NUMBER MODEL_NUMBER seller_2 19.99
For the sake of loose coupling, I suggest you build seperate Items and Price tables, and have another table (called Junction table) Item_Price which maps many items to many prices as you like.
This is called Many-to-Many relationship
Basically, it links an Item with its itemId to a Price with priceId, and stores this link in an Item_Price itemPriceId (or whatever you call the 3rd primary key)
Here's a sample diagram EDIT: sorry about the previous diagram.
Here's a sample SQL DDL of 3 tables, plus 2 junction tables to associate Item to Price, and Seller to Item.
CREATE TABLE Item (
item_id int PRIMARY KEY,
..
..
)
CREATE TABLE Price (
price_id int PRIMARY KEY,
..
..
)
CREATE TABLE Seller (
seller_id int PRIMARY KEY,
..
..
)
-- This is the junction table for Item to Price mapping.
CREATE TABLE Item_Price (
item_id int REFERENCES Item (item_id),
price_id int REFERENCES Price (price_id),
PRIMARY KEY (item_id, price_id)
)
-- This is the junction table for Seller to Item mapping.
CREATE TABLE Seller_Item (
seller_id int REFERENCES Seller (seller_id),
item_id int REFERENCES Item (item_id),
PRIMARY KEY (seller_id, item_id)
)
One attribute that have many properties? Sounds like one-to-many relations... go for a new table have foreign key help you out.
Products
prod_id (PK) | model_no
Sellers
seller_id(PK)|seller_name
Pricing
price_id (PK)|price|prod_id (FK) | seller_id(FK)
yes You can a prefix before the model_number for each individual seller.
If you still have stuff then let me know more clear your problem

Resources