Pull value from another table - sql

I want to create two tables that are related. The ITEM table has a primary key of ItemNumber and another important column of UnitPrice. The second Table has the UnitPrice again. I want to populate the UnitPrice column in the ORDER_LINE_ITEM table from the value in the ITEM UnitPrice column but am not sure how to do this. I need to have the UnitPrice in the second table so I can have a calculated column of the ExtendedPrice, unless there is a way to have a calculated column with values from another table.
CREATE TABLE ITEM
(
ItemNumber int IDENTITY(1,1) Not NULL PRIMARY KEY,
ItemName varchar(30) NOT NULL,
OrderDate datetime NOT NULL,
UnitPrice money NOT NULL,
Description text NOT NULL,
);
CREATE TABLE ORDER_LINE_ITEM
(
OrderId int FOREIGN KEY REFERENCES ORDERS(OrderID),
LineNumber int NOT NULL,
ItemNumber int FOREIGN KEY REFERENCES ITEM(ItemNumber) NOT NULL,
Quantity int Not NULL,
UnitPrice money NOT NULL,
ExtendedPrice money AS (Quantity * UnitPrice),
CONSTRAINT pk_OrderLineItem PRIMARY KEY (OrderID,LineNumber)
);

Lets start with the problem at hand, from what you are asking you will just need to give it the foreign key and reference ITEM(UnitPrice).
Insert into table ORDER_LINE_ITEM
CONSTRAINT FK_ORDER_LINE_ITEM_ITEM FOREIGN KEY(UNITPRICE) REFERENCE ITEM(UNITPRICE)
Second thing you need to work on is your overall coding style because you have two different ways of constraining foreign keys and primary keys. This will help with future coding work and if you are working with another coder on a project.

Related

How to create column which is generated automatically in relation to primary key which is the foreign key fro

In SQL Server Management Studio, I am creating this table:
CREATE TABLE Purchase
(
PurchaseID INT NOT NULL
FOREIGN KEY REFERENCES Product(ProductID) PRIMARY KEY,
TotalQuantity INT NOT NULL,
Price AS (PurchaseID.PRICE),
TotalPrice AS (TotalQuantity*Price),
SalesAssistantID INT NOT NULL
FOREIGN KEY REFERENCES SalesAssistant(SalesAssistantID),
CashierID INT NOT NULL
FOREIGN KEY REFERENCES Cashier(CashierID)
)
Above code only represents what I want to achieve (Price AS (PurchaseID.PRICE)), Price should be created whenever the PurchaseID is specified so that TotalCost can also function automatically, I could not solve this problem. How to do it?
PurchaseID int identity(1,1) Primary key
This makes purchaseID primary key, and (1,1) Means it will start at 1 and increment by 1.

There are no primary or candidate keys in the referenced table error

I have a problem with combining foreign keys to different tables. For example I made a table Customers and a Table invoices. I want a foreign key from Customers to invoices so I can get the name and everything of the Customer:
Create table code of Customers:
Create Table Customers
(
customerID int IDENTITY(100,1) NOT NULL,
customer_email varchar(30) NOT NULL,
username varchar(255) NOT NULL,
password varchar(50) NOT NULL,
firstname varchar(255) NOT NULL,
lastname varchar(255) NOT NULL,
insertion varchar(10) NULL,
phonenumber int NULL,
streetname varchar(20) NOT NULL,
number int NOT NULL,
zipcode varchar(10) NOT NULL,
city varchar(255) NOT NULL,
Constraint pk_Customers
PRIMARY KEY (customerID, customer_email, username)
)
Create table code of Invoices:
Create Table Invoices
(
invoiceID int IDENTITY(1000,1) NOT NULL,
customer_email varchar(30) NOT NULL,
customerID int NOT NULL,
creationdate datetime NOT NULL DEFAULT GETDATE(),
totalAmount decimal(5,2) NOT NULL,
Constraint pk_Invoices
PRIMARY KEY (invoiceID, customer_email,creationdate)
)
The foreign key code that I want to use:
ALTER Table Invoices
ADD Constraint fk_Customers_Invoices
FOREIGN KEY (customerID) REFERENCES Customers (customerID)
ON UPDATE CASCADE
ON DELETE NO ACTION
It throws the following error:
There are no primary or candidate keys in the referenced table 'Customers' that match the referencing column list in the foreign key 'fk_Customers_Invoices'.
How can I add my foreign key?
I think it's because your primary key is a composite key:
customerID, customer_email, username
This suggests that it is only the combination of these three fields that will uniquely identify a customer, and the foreign key would need to reference all three fields.
If customerID is unique, then it should be the primary key for the table and your foreign keys would be able to use it as a reference.
For what purpose are the other fields included in the primary key?
Since your Customers table defines this primary key:
Constraint pk_Customers
PRIMARY KEY (customerID, customer_email, username)
any table that wants to reference Customers must provide all three columns of that primary key. That's the way FK constraints work.
So from your Invoices tables, you must provide all 3 columns that make up the primary key of Customers - not just one. You can never refernce only part of a primary key - it's the whole key or nothing....
ALTER Table Invoices
ADD Constraint fk_Customers_Invoices
FOREIGN KEY (customerID) REFERENCES Customers (customerID)
ON UPDATE CASCADE
ON DELETE NO ACTION
You can either:
change the PK for Customers to be just CustomerID which would make a whole lot more sense since it's an identity column
or you could add the other two columns in the Customers PK to yoru table Invoices

PostgreSQL Error: relation "products" does not exist

I'm trying to create the following schema
While I execute the following code I get the relation "products" does not exist error.
CREATE TABLE Orders(
ORDERID serial NOT NULL PRIMARY KEY,
ORDERDATE text NOT NULL default'',
CUSTOMERID serial NOT NULL REFERENCES Customers(CUSTOMERID),
NETAMOUNT text NOT NULL default'',
TAX text NOT NULL default'',
TOTALAMOUNT text NOT NULL default''
);
CREATE TABLE Orderlines(
ORDERLINEID serial NOT NULL,
ORDERID serial NOT NULL REFERENCES Orders(ORDERID),
PROD_ID serial NOT NULL REFERENCES Products(PROD_ID),
QUANTITY text NOT NULL default'',
ORDERDATE text NOT NULL default'',
PRIMARY KEY(ORDERLINEID,ORDERID)
);
CREATE TABLE Products(
PROD_ID serial NOT NULL PRIMARY KEY,
CATEGORY text NOT NULL references Products(CATEGORY),
TITLE text NOT NULL default'',
ACTOR text NOT NULL default'',
PRICE text NOT NULL default''
);
I am doing this in http://sqlfiddle.com/ if it has anything to do with it.
When the table orderlines is created, the create table for the products table has not been executed. You need to add the foreign keys after all tables have been created.
You should only defined the primary key columns as serial, not the foreign key columns - they will be referencing the generated values from the target table. You don't want to generate a new value for the FK column when you insert.
The foreign key:
CATEGORY text NOT NULL references Products(CATEGORY)
is wrong because of two reasons: First because category is not the primary key of the products table. And secondly because it doesn't make sense that the category column references itself. You probably wanted to reference the categories table.
You script is also missing the customers table.
And you are choosing the wrong data types.
Number or dates should NEVER be stored in text (or varchar) columns.
Putting all that together, the script should be something like this:
create table customers
(
customerid serial primary key,
.... other columns
);
create table categories
(
category serial primary key,
categoryname text not null
);
CREATE TABLE Orders
(
ORDERID serial NOT NULL PRIMARY KEY,
ORDERDATE date NOT NULL, -- no text here!
CUSTOMERID integer NOT NULL, --- NO serial here!
NETAMOUNT decimal (22,4) NOT NULL, -- no text here!
TAX decimal(18,2) NOT NULL, -- no text here!
TOTALAMOUNT decimal (24,4) NOT NULL -- no text here!
);
CREATE TABLE Orderlines
(
ORDERLINEID serial NOT NULL,
ORDERID integer NOT NULL, -- NO serial here!
PROD_ID integer NOT NULL, -- NO serial here!
QUANTITY integer NOT NULL,
ORDERDATE date NOT NULL, -- NO text here!
PRIMARY KEY(ORDERLINEID,ORDERID)
);
CREATE TABLE Products
(
PROD_ID serial NOT NULL PRIMARY KEY,
CATEGORY integer NOT NULL references categories,
TITLE text NOT NULL,
ACTOR text NOT NULL,
PRICE decimal (18,2) NOT NULL
);
alter table orderlines add foreign key (orderid) REFERENCES Orders(ORDERID);
alter table orderlines add foreign key (prod_id) REFERENCES products(prod_id);
alter table orders add foreign key (customerid) REFERENCES Customers(CUSTOMERID);

record addition in sql

I am making an inventory management system.
I wanted to enter products which were bought by the customer in product_sale table.
create table product_sale(
recipt# int primary key identity(1001,1),
product_id int,
product_name varchar(50),
brand_name varchar(50),
prchase_date date,
purchase_time time,
gross_price int,
discount_price int,
retail_price int,
quantity int,
)
the problem is that one customer can buy several items, and they will be inserted in multiple rows but as recipt# is primary key,so the other record will be added on another recipt#
so what should I do either should remove primary key contraint from recipt#
or something more preferred....
--Product info--
CREATE TABLE PRODUCT
(
PRODUCTID INT NOT NULL,
PRODUCT_NAME VARCHAR2(20) NOT NULL,
CONSTRAINT PRODUCT_PK PRIMARY KEY(PRODUCT_ID)
);
--sales info--
CREATE TABLE SALES
(
RECIPT_ID SMALLINT DEFAULT (0) NOT NULL,
PRODUCTID INT DEFAULT (0) NULL,
CONSTRAINT SALES_PK PRIMARY KEY(RECIPT_ID),
CONSTRAINT SALES_PRODUCT_FK FOREIGN KEY(PRODUCTID) REFERENCES PRODUCT(PRODUCT_NAME)
);
Edit[1]: since you elaborated more, I would always want to have two different tables because you want a list of your inventory on one table then on the second table you would want the sales. This helps keep all the clutter away from the view you wish to seek.
Mu suggestion is you should denormalize this table by separating order item and receipt ID. Think this is classic example and you can find lots of examples in web.
For example http://www.tomjewett.com/dbdesign/dbdesign.php?page=manymany.php

How to insert multiple rows into an Order table?

So I set up a simple database and I am at the point where I am trying to test that it is working correctly. I am trying to figure out how I get multiple entries into an Order table. I need to have an order# and be able to order multiple items and use multiple shippers and such. I just can't seem to figure out a way to get the data into my DB properly.
Below is how I have my DB set up. Could someone please explain to me how to get the my test data into the DB.
Here are the reference tables:
CREATE TABLE Product_Table (
ProductID INT NOT NULL,
Product_Name char(50) NOT NULL,
Product_Cost number(9,2) NOT NULL,
Product_In_Stock INT NOT NULL,
CONSTRAINT Products_PK PRIMARY KEY (ProductID)
);
CREATE TABLE Payment_Terms_Table (
PayTermNum INT NOT NULL,
Payment_Time_Frame CHAR(20) NOT NULL,
CONSTRAINT Payment_Terms_PK PRIMARY KEY (PayTermNum)
);
CREATE TABLE Shipper_Table (
ShipperNum INT NOT NULL,
Shipper_Name CHAR(50) NOT NULL,
Shipper_Phone CHAR(22) NULL,
CONSTRAINT ShipperNum_PK PRIMARY KEY (ShipperNum)
);
CREATE TABLE Supplier_Table (
SupplierID INT NOT NULL,
Supplier_Name CHAR(50) NOT NULL,
Sup_Address CHAR(50) NOT NULL,
Sup_City CHAR(20) NOT NULL,
Sup_State CHAR(20) NOT NULL,
Sup_Zip CHAR(9) NOT NULL,
Sup_Phone CHAR(22) NULL,
ShipperNum INT NOT NULL,
PayTermNum INT NOT NULL,
CONSTRAINT Supplier_PK PRIMARY KEY (SupplierID),
CONSTRAINT ShipperNum_Relationship FOREIGN KEY (ShipperNum)
REFERENCES Shipper_Table (ShipperNum),
CONSTRAINT PayTermNum_Relationship FOREIGN KEY (PayTermNum)
REFERENCES Payment_Terms_Table (PayTermNum)
);
Here is my Order table:
CREATE TABLE Order_Table (
OrderID INT NOT NULL,
ProductID INT NOT NULL,
SupplierID INT NOT NULL,
Wholesale_Price NUMBER (9,2) NOT NULL,
Units_Ordered INT NOT NULL,
Order_Date DATE DEFAULT SYSDATE NOT NULL,
Order_Received DATE NULL,
CONSTRAINT Order_PK PRIMARY KEY (OrderID),
CONSTRAINT ProductID_Relationship FOREIGN KEY (ProductID)
REFERENCES Product_Table (ProductID),
CONSTRAINT SupplierID_Relationship FOREIGN KEY (SupplierID)
REFERENCES Supplier_Table (SupplierID)
);
Your problem is that you have a defined one table to hold Orders, so you can have only one Item per Order. Normally we handle this scenario by having two tables: a Header with the information for the whole Order and a Line table for each ordered Item.
CREATE TABLE Order_Header (
OrderID INT NOT NULL,
Order_Date DATE DEFAULT SYSDATE NOT NULL,
Order_Received DATE NULL,
CONSTRAINT Order_PK PRIMARY KEY (OrderID)
)
/
CREATE TABLE Order_Line (
OrderID INT NOT NULL,
LineNo INT NOT NULL,
ProductID INT NOT NULL,
SupplierID INT NOT NULL,
Wholesale_Price NUMBER (9,2) NOT NULL,
Units_Ordered INT NOT NULL,
CONSTRAINT Order_Line_PK PRIMARY KEY (OrderID, LineNo),
CONSTRAINT Order_Line_Header_FK FOREIGN KEY (OrderID)
REFERENCES Order_Header (OrderID)
CONSTRAINT ProductID_Relationship FOREIGN KEY (ProductID)
REFERENCES Product_Table (ProductID),
CONSTRAINT SupplierID_Relationship FOREIGN KEY (SupplierID)
REFERENCES Supplier_Table (SupplierID)
)
/
I have declared a composite primary key because it is easier to understand what's happening.
Now that you have two tables you can easily create orders with more than one line.
On the subject of normal practice, an Order should have a CUSTOMER. That would be an attribute of ORDER_HEADER. Also you have a SHIPPER table but don't use it. Again that would probably be an attribute of ORDER_HEADER.
Also your naming convention is ugly. There's no need to include _TABLE: just name the objects for teh things they represent. Likewise your foreign key needs are opaque; it doesn't matter so much in this toy example but in a real database you will find it helpful to specify the child and parent tables in the FK names.