primary key to foreign key to foreign/primary - sql

there are tables in database like
tbl_items
item_id item_batch item_name
(primay key = item_id+item_batch)
tbl_transaction(orders)_header
ordre_id employe_id date
(primary key= order_id)
tbl_transaction_(orders)detail
(id)blind order_id item_code item_batch item_qty
(primary key= blind mean identy column) (foreign key = item_code+item_batch from tbl_items)
tbl_warehouse
item_code Item_batch item_qty
primary key(item_code+item_batch)
confusion here
i--foreign key(item_code+item_batch to item_code+item_batch from tbl_transaction_detial )
or this is correct
ii--
foreign key(item_code+item_batch to item_code+item_batch from tbl_items )
the process is as fellow user create new bill whose id and current date will be stored in transaction_header and the item customer buy their detail will be stored in transaction details and then update warehouse table
now if the record exist in transaction header then update warehouse
according to this what will be the correct foreign key relation ship i or ii

So sorting out your first confusion:
Foreign Key of transaction_table will point to Primary key of table_item.
or in better way you can say that.
Foreign Key of transaction_table references Primary key of table_item.
And as per your question:
i) Your transaction_header will not contain any Foreign Key. I mean it do not need any Foreign Key.
ii) Foreign Key from transaction_detail will reference to Primary key of table_item.
iii) Foreign Key of transaction_detail will reference to Primary Key of warehouse.
As change in the transaction_detail is causing changes in warehouse and item_table.
For better understanding read this.

Related

Order management SQL schema

I am designing a SQL database for sales person of a firm, where each customer will order multiple items from the firm. I want to store this order uniquely to the customer. Which will be linked to customer table.
Customer Table :
Cust_id
Cust_name
Cust_phone
Currently I am thinking of making a separate order table for each order
Order Table:
Product_id
Prod_quantity
Total_amt
but can't figure out how to link it back to customer. Or how to uniquely identify each order table.
I would have done it in NoSQL but data has to be locally stored in SQLite.
Customer may order multiple times so I should be able to identify current and previous orders
Do not create a separate table for each order! That's a very bad design. Relational tables aren't spreadsheets!
Have one table for the orders with a foreign key pointing to the customers. For the items of orders have a linking table with a foreign key to the order and another to the item. That's fairly standard thing (I'm pretty certain you'll find such a classic example in many tutorials about relational database design.). Something along the lines of:
CREATE TABLE customer
(id integer,
name varchar(64),
...
PRIMARY KEY (id));
CREATE TABLE product
(id integer,
name varchar(64),
...
PRIMARY KEY (id));
CREATE TABLE order
(id integer,
customer integer,
...
PRIMARY KEY (id),
FOREIGN KEY (customer)
REFERENCES customer
(id));
CREATE TABLE order_product
(order integer,
product integer,
amount integer,
...
PRIMARY KEY (order,
product),
FOREIGN KEY (order)
REFERENCES order
(id),
FOREIGN KEY (customer)
REFERENCES customer
(id));
(order might be a bad choice for a table or column name in some DBMS as it's also a keyword and thus required quoting. So probably chose something else. I used it just for the sake of clarity.)

SQL Insert into table with 2 non-unique primary keys

I have a table that I need to insert data into.
The table Sales has 4 columns
CustomerValueType_id (int)
Customer_id (int)
Value (NVARCHAR)
Customer_name (NVARCHAR)
The CustomerValueType_id, Customer_id are foreign keys that are not-unique, CustomerValueType_id matches to a value type, while Customer_id matches to the Customer_name.
I need to add additional customer data into the Valuecolumn but how do I ensure that the data matches to the correct CustomerValueType_id and Customer_id and each customer name has to be repeated in the Customer_name
Sales Table
You are trying to do denormalization.
Ideally, in the normalized design, you will just store, parent_ids in
the child table. If you want to see parent_name fields, you have to
get them based on JOIN conditions.
But, here as you are storing both id, name in the child table, I would suggest you to create composite Foreign key in the child table, so that the combination is always present. Also, make this combination as composite primary key in the parent table.
-- Parent Table PRIMARY KEY
ALTER TABLE dbo.CustomerValueType
ADD CONSTRAINT PK_CustomerValueType
PRIMARY KEY CLUSTERED (CustomerValueType_id, Value);
GO
--Child Table FOREIGN KEY
ALTER TABLE dbo.Sales
ADD CONSTRAINT FK_Sales_CustomerValueType
FOREIGN KEY (CustomerValueType_id,Value)
REFERENCES dbo.CustomerValueType(CustomerValueType_id,Value);
GO

Relation from one table to another with two columns in the primary key in SQL Server

I am trying to make a relation from a table to another like the following :
Books
IdBook (primary)
SerialNumber (primary)
NameBook
The other table is :
Qtt
IdQtt (primary)
IdBook
Qtt
How can I make a relation only between Qtt.IdBook and Books.IdBook ?
You meant to create a FOREIGN KEY relationship between the tables on that column like
CONSTRAINT FK_idbook FOREIGN KEY (IdBook)
REFERENCES Books (IdBook)
ON DELETE CASCADE
ON UPDATE CASCADE
But that will not work since you have composite PK in your Books table on IdBook, SerialNumber and thus you need another key column in your Qtt table to refer to both PK column else it would be a PFD (partial functional dependency)
constraint FK_book FOREIGN KEY (IdBook,IdQtt) references Books (IdBook,SerialNumber)
Although it is technically possible to create a UNIQUE constraint on Books.IdBook and a FOREIGN KEY constraint on Qtt.Book referencing that column, this probably won't work with your data model because IdBook alone doesn't uniquely identify a Books row. You need a table like BookTitle keyed by IdBook, with a one-to-many relationship to Books and another one-to-many relationship from BookTitle to Qtt on IdBook.

Relationship between composite keyed table & non primary key table

I have two tables named ORDER_HEAD and ORDER_DETAIL, following is their structure.
ORDER_HEAD:
ORD_ID (PK)
ORD_TYPE (PK)
ORD_DATE
ORD_NET_TOTAL
ORDER_DETAIL:
ODD_ID
ODD_LINE_NO
ODD_PRODUCT_ID
ODD_QTY
I want to form a relationship between the ORD_ID in ORDER_HEAD & ODD_ID in ORDER_DETAIL table. But SQL Server shows an error message:
primary key or unique constraint must be defined for table before it can participate in a relationship
Why am I getting this error ? Is there a way to perform a join between these two columns or is there a problem in my db design ?
If you want to create a relationship from Composite primary key then any reference should also include all the column's in Composite primary key
Schema of ORDER_DETAIL should be
ORDER_DETAIL
============
ODD_ID (Fk)
ORD_TYPE(Fk) -- you need to add this column
ODD_LINE_NO
ODD_PRODUCT_ID
ODD_QTY
Create Foreign key like this.
ALTER TABLE ORDER_DETAIL
ADD CONSTRAINT FK_ORDER_DETAIL
FOREIGN KEY(ODD_ID, ORD_TYPE) REFERENCES ORDER_HEAD(ODD_ID, ORD_TYPE)
UPDATE
After rethinking the problem I think you should achieve your goal by adding reference column ODD_TYPE (like user #NoDisplayName stated) and creating composite PK for your table ORDER_DETAIL consisting of 3 columns (ODD_ID, ODD_TYPE, ODD_LINE_NO), then it would be:
ORDER_DETAIL
============
ODD_ID (PK)
ODD_TYPE (PK)
ODD_LINE_NO (PK)
ODD_PRODUCT_ID
ODD_QTY
in SQL it could be:
ALTER TABLE ORDER_DETAIL ADD CONSTRAINT PK_Order_Detail PRIMARY KEY NONCLUSTERED (ODD_ID, ODD_TYPE, ODD_LINE_NO)
Then, in ORDER_DETAIL table for specific pair (ODD_ID, ODD_TYPE) you would have records being its order lines.
I think that after removing the previous PK, adding the column and setting the above key (even in visual editor) you shouldn't have problems when creating FK between the two tables and mapping the proper columns together.

SQL Server Table Design with Table having foreign key to two other tables

I have Four tables,
DiscountCode which describes a discount.
Bundles which is basically sold as a product so it contains a productcode
Products which are sold as products so it also contains a productcode
ProductDiscount code meant to be used to describe the fact that a Bundle/Product can have multiple discount codes associated with it.
**Discount Code**
Id
Name
Code ex. SUMMER10 ie 10% off summer products
...
**Bundles**
Id
Name
ProductCode *Unique* Ex..ABC123
...
**Products**
Id
Name
ProductCode *Unique* Ex.. XYZ1234
...
**ProductDiscountCode**
DiscountId
ProductCode FK to both Products.ProductCode AND Bundles.ProductCode
Records in ProductDiscountCode:
1 ABC123
1 XYZ1234
1 URS576 <-- prevent this if Prod or Bundle does NOT contain URS576
My question is in regards to the ProductCode in the Ternary table. NOW KEEP IN MIND PELASE SQL IS NOT MY STRONG SUIT! Can/Should the ProductCode column in the ternary table be foreign keyed to TWO Separate tables in an attempt to restrict it's content to a product code that is EITHER contained in the Bundle table OR the Product table, assuming the productcode in bundles and products is unique between the two tables (to be enforced by business rules). Or does the ProductDiscountCode table need the following
**ProductDiscountCode**
DiscountId
ProductCode FK to ProductCode in Product
BundleCode FK to ProductCode in Bundle
OK, it is never a good idea to try to constrain to two differnt FKs for the same field, that is a sign of incorrect design.
Why is bundle a separate table if it is not using the product codes from the product table? WHy not add a column to the product table to identify if the line item is a bundle or an individual product and stopre both there?
If you're going to use a Foreign Key then every value must exist as a key on the other table so you can't constrain your column Product Keys if it's got Bundle Keys in it and vice versa.
If you need to ensure referential integrity then you'll need to have two Nullable columns.
You should probably also have a Check Constraint to make sure that one and only one of the codes is null.
CREATE TABLE ProductDiscountCode
(
DiscountId int,
ProductCode varchar(12) null,
BundleCode varchar(12) null,
CONSTRAINT ProductDiscountCode_PK PRIMARY KEY(DiscountId),
CONSTRAINT FK_ProductDiscountCode_DiscountId FOREIGN KEY (DiscountId) REFERENCES DiscountCode (Id),
CONSTRAINT FK_ProductDiscountCode_BundleCode FOREIGN KEY (BundleCode) REFERENCES Bundle (ProductCode),
CONSTRAINT FK_ProductDiscountCode_ProductCode FOREIGN KEY (ProductCode) REFERENCES Product (ProductCode),
CONSTRAINT ProductCodeExists CHECK (
(ProductCode IS NULL AND BundleCode IS NOT NULL)
OR
(ProductCode IS NOT NULL AND BundleCode IS NULL)
)
)
If for some reason you really need to be able to show the Product Codes as a single column then you could do something along these lines
CREATE TABLE ProductDiscountCode
(
DiscountId int,
SingleProductCode varchar(12) null,
BundleCode varchar(12) null,
ProductCode as ISNULL (SingleProductCode ,BundleCode ) ,
CONSTRAINT ProductDiscountCode_PK PRIMARY KEY(DiscountId),
CONSTRAINT FK_ProductDiscountCode_DiscountId FOREIGN KEY (DiscountId) REFERENCES DiscountCode (Id),
CONSTRAINT FK_ProductDiscountCode_BundleCode FOREIGN KEY (BundleCode) REFERENCES Bundle (ProductCode),
CONSTRAINT FK_ProductDiscountCode_SingleProductCode FOREIGN KEY (SingleProductCode) REFERENCES Product (ProductCode),
CONSTRAINT SingleProductCodeExists CHECK ((SingleProductCode IS NULL AND BundleCode IS NOT NULL) OR (SingleProductCode IS NOT NULL AND BundleCode IS NULL))
)
But you do have to ask yourself first whether using Foreign key restraints is actually necessary in the first place.
Having two columns for product code could speed up your Select queries slightly but by having to decide which column you are storing the product code in the updates, deletes and inserts will be made more complicated.
Please first take a look at the thread: Multiple foreign key constraints on a single column in SQL Server 2008
ProductCode is a FK in Bundle and then you want another foreign key to the same column in ProductDiscountCode. You are double referencing same field and that does not seem to be good designing. You should restrict the values in the table at the moment of the insert, constraints are not meant for all kinds of validations.