-2

I have two tables:

Product

Columns: Product ID (PK), Product Name

Order

Columns: Order ID (PK), Order Name

I would like to store which Product Id for each order.

Is it better to create another table:

ProductOrder table:

Order ID (FK), Product ID(FK)

or add an additional column in the Order table:

Order ID (PK), Order Name, Product ID (FK)

Edit: Order can only contain one product.

3
  • 1
    Usually created an additional table OrderItems (ItemID_PK,OrderId_FK, ProductId_FK, Amount,Price, ...). Commented Jan 17 at 16:42
  • thanks @ValNik, an order contains only one product/item. Do I still need an extra table? Commented Jan 17 at 17:11
  • I think, if several products in order, extra table is mandatory. Commented Jan 17 at 18:05

2 Answers 2

2

The best approach depends on the nature of the relationship between Product and Order in your application. If there is any possibility of an order containing multiple products now or in the future, option 1 (ProductOrder table) is the better choice. It keeps your database design normalized and avoids potential issues if your requirements change in futuer. Option 2 (Order Table)can be a simpler and efficient solution at this moment but normalization often wins in most cases where scalability and flexibility are priorities!

Sign up to request clarification or add additional context in comments.

1 Comment

"It keeps your database design normalized " - not necessarily.
0

My suggestion is a mix of @ValNik 's comment and @Daniele 's answer:

CREATE TABLE orders (
-- these columns, plus any needed at order level
  order_id INT NOT NULL PRIMARY KEY
, cust_id  INT NOT NULL FOREIGN KEY REFERENCES(customer)
, order_ts       TIMESTAMP NOT NULL
, order_discount DECIMAL(10,2)
, order_pctoff   DECIMAL(3)
);

CREATE TABLE orderitem (
-- these columns come to mind, there might be others - at item level
  order_id INT NOT NULL FOREIGN KEY REFERENCES(orders)
, prod_id  INT NOT NULL FOREIGN KEY REFERENCES(products)
, quantity      INT NOT NULL
, item_discount DECIMAL(10,2)
, item_pctoff   DECIMAL(3)
, PRIMARY KEY (order_id,prod_id)
);

2 Comments

thanks, an order contains only one product/item. Do we still need OrderItem table?
In that case - that's a rare use case, one order per product chosen. But then, just add the foreign key to the order. One order, one product/one product, many orders, i.e, many-to-one, that's just a foreign key column. It's many-to-many that requires a dedicated table.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.