Question

Lets say I am designing a database data model of an online seller of products such as Amazon, I have a few options:

enter image description here

When inserting rows in OrderLine, to determine each OrderLineID:

select max(OrderLineID) + 1 
from OrderDetail 
where OrderID={OrderID}

OrderLineID will have nice simple small numbers, each row nicely numbered:

OrderID    OrderLineID
-------    -----------
    100              1
    100              2
    100              3
    etc

enter image description here

Option 2: Instead of select max()+1, set column OrderLineID autoincrement.
Advantage - no need for select max()+1
Disadvantage - OrderLineID will not have nice looking small line numbers ie 1,2,3,4 etc, OrderLineID will have very large numbers.


enter image description here

Option 3: Move OrderLineID up to be the first column


Which would be the best data model?

Was it helpful?

Solution

If having same products in an orders lines is not valid, then:
OrderLineID column is redundant, you may use combination of {OrderID , ProductID } as the pk of OrderLine table

If you want to use the surrogate identifier column, having OrderLineID with incremental value, as the only PK column will serve, you may consider having {OrderID , ProductID } as a unique key constraint.

OTHER TIPS

You best bet is to use the auto-increment. Or even better, use 1 sequence for populating every unique id in every table in the database.

Why? When inserting records into the table, you do not want to query the table to find the current id. This is slow and will ultimately error when a handful of process try to insert all at the same time. Sequence generators are designed to quickly return the next value even in multi-user environments.

Personally, I like using 1 sequence generator for the pk id field in each table.

What really matters is that each record is tagged with a unique number. It does not matter if numbers get skipped.

Make sure you enforce uniqueness with a primary key / unique index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top