I just started learning SQL in a book, and I'm stack at understanding the concept of the primary key.
Here I have to explain little about these tables in this db.
The Order table stores customer orders but not order details. Each order is uniquely numbered.
The orderItems table stores the actual items in each order, one row per item per order.
I thought primary key could be used for the identical column in a table, and same values couldn't be inserted.
But I found couple of the same values are inserted in the primary key(order_num, order_items) in orderItems
Related
Dear anyone can help me as i have two tables named as Order and Products which have more than two multiple same fields i want to make relationship among all same fields in both tables
You can see tables in pictures below:
This is quite simple, assuming product_id is a key for items.
Make the column Order.product_id be a FOREIGN KEY to Product.product_id.
Drop all other columns that exist in Products from the table Order.
Note inspired by comment from #WEI_DBA: price and quantity are not really characteristics of product, but of order. These should remain in the Order table and be removed from the Product table instead. Generally, give each table the data which depend on that table's primary key.
I created a new table called Expirations that has it's own unique id, with indentity incrementing, as it's primary key. I also want this table to pull in data from two other tables, so I created a column for the InsuranceId and the LicenseId, making both columns foreign keys to connect them to the data (aka ID) from their respective tables (Insurance and License).
Any idea why my data is not automatically filling in for my Expirations Table? I believe it was created as "many to one" for all of these columns. Not sure if that is correct either, as I want the Expiration table to list all insurance id's and licence id's.
Anyone know what I am doing wrong here?
Foreign keys don't mean that a table gets filled automatically.
Let's say you have a person table and a company table and a company_person table to show which person works in which company. Now you insert three companies and four persons. That doesn't mean that the company_person table gets filled with 3 x 4 = 12 records (i.e. all persons work in all companies). That would make no sense.
Foreign keys merely guarantee that you cannot insert invalid data (i.e. a person that doesn't exist or a company that doesn't exist) into the table in question. You must insert the records yourself.
Basically your expirations table is like a fact table and you want to load data from the dim table which is Insurancetable ( InsuranceId as primarykey) and Licencetable ( Licenceid as PK).
But if you do not have any combination of InsuranceId and licenseId how do you know which insuranceid belongs to which LicenseId.
If your expirations table is empty then you need to first do cross join between the insurancetable and licensetable which is cartesian result but you do not want to do that as it does not make sense in real world.
Hope my explanation helps.
I have a table with some data summary which consist of client_id, location_id, category_id and summary columns. Values of the three id's columns are not unique.
At the moment I have created a composite key from client_id, location_id, category_id using primary keys. Those three columns will uniquely identify rows.
My question is, if I still should include unique primary key for that table for example column with auto-increment id ?
That depends completely on your uses of the table. If you don't want to refer to a given row in a query (for example, having a dependent table), the separate PK is unnecessary (eg. if you always ask for statistics for a given client and a given location and a given category). However, if you do have dependent tables, you probably want a separate PK as well.
If your composite key is the primary clustered index then I would say it's not necessary.
Alright so I read from somewhere
Every table should have a primary key
But some of my tables don't seem to behave!
I'd also like to know whether the relations as I'm using are fine or I need to dissolve them further, I'm open to suggestions.
The relations are
Dealers(DealerId(PK),DealerName)
Order(DealerId(FK),OrderDate,TotalBill)
Sales(DealerId(FK),ItemType,OrderDate,Quantity,Price)
P.S. I can't make a table named Items(ItemCode,Type,Price) Because the price is variable for different dealers. And all the constraints i.e not null + check that I needed are dealt with already just didn't mention.
1. Are the relations dissolved well?
2. Should I care about setting primary keys in the tables that don't have it already?
Helpful responses appreciated.
In your case, you should add an auto increment integer field to Order and Sales and set that to be the primary key.
In Relational Database Theory, you can sometimes identify a sub-set of the fields to use as a primary key, as long as those columns are non-null and unique. However, (1) the order table cannot have a primary key from DealerID and OrderDate because a dealer could make two orders on the same date. Maybe even for the same amount, which would mean that no sub-set of fields is unique, and (2) even when familiar data can uniquely identify the data, an auto-increment integer can be a good key.
I also think that you want a foreign key from Sales to Order. You are probably using DealerId and OrderDate for joins, but this will not work correctly if a dealer makes two orders on the same date.
Finally, take advice like
Every table should have a primary key
with a grain of salt. Linking tables used for many-to-many relationships can work perfectly fine without a primary key, although a primary key can be an improvement, since it will make deleting records easier, and if you don't have a primary key on a linking table, I would still recommend a unique index on all the fields, in which case that can be the primary key.
Do you really need separate Sales Table ?
Dealers(DealerId(PK),DealerName)
Order(OrderId(PK), DealerId(FK),OrderDate, ItemType, Quantity,Price)
Also,
TotalBill (can be calculated) = Quantity * Price
About the question 1 you should answer this question:
A sale can be made without an order?
If yes, your DealerId(FK) in Sales is alright, assuming that a sale will only exist if a dealer made it.
If no, you should put an OrderId(FK) in Sales, instead of DealerId(FK). If a sale belongs to an order, this order belongs do a dealer, so you already have the relation from dealers to sales.
About the question 2, you should have primary keys on your tables, because this is the way you have to select, update and delete some specific item on your database. Remembering that a primary key is not always an auto increment column.
And about the Items table, if the price is variable to different dealers, so you have an M to N relationship between Dealers and Items, which means you could have an intermediate table like this example:
DealerItemPrices(DealerId(FK), ItemId(FK), Price)
And these two Foreign Keys should be Unique Composite Keys, in this way a Dealer Y can't have two distinct prices to the same item.
Hope it helps!
I have a table where I have to relate groups of primary keys to one another. There is no information about these groups other than that they exist. Specifically, I am storing groups of Editions of Books together, so I can know that a certain set of books are editions of each other.
I currently have a setup where I have an Edition_Group_ISBN column, where one of the ISBN's is arbitrarily chosen to group a set of Editions together.
The typical approach for this problem is to have a separate table like Book_Editions, where I would have an autoincrementing integer primary key like "Edition_Group_ID" linking ISBNs together. I have been told this method is preferable.
However, the problem with implementing that system relates to the loading in of data. How am I to dynamically load in Edition Groups? One solution might be to lock the table and do a transaction on the next ID in the autoincrement. I imagine this would be slower and more cumbersome than my current method, though.
Given the difficulty of inserting data under that system, what is the optimal system to address this problem?
You load in Edition Groups by having an ISBN table foreign key in your Edition Groups table, and then inner-joining your two tables together in your query, using the Primary Key of your ISBN Books table, and the Foreign Key of your Edition Groups table in the join.
ISBN Table
ISBN_ID // Auto-incrementing Primary Key
ISBN
Book_Title
.etc
EDITIONS Table
Edition_ID
FIRST_EDITION_ISBN_ID
ASSOCIATED_ISBN_ID // Foreign Key to ISBN table
Most database systems have a way to return the Primary Key ID of a newly inserted record, so:
NEW_ID = INSERT INTO ISBN (ISBN, BOOK_TITLE)
VALUES (12345678, "The Frog Prince");
SELECT SCOPE_IDENTITY(); // Returns new ID from ISBN table.
INSERT INTO EDITIONS (FIRST_EDITION_ISBN_ID, ASSOCIATED_ISBN_ID)
VALUES (12345678, NEW_ID);