0

I have three tables for managing stock levels - Product, ProductGender and ProductType. I also have a table called OrderItem that defines what is being ordered from the database.

After I have my program insert values into the OrderItem table, it identifies how much is to be ordered after the user inserts the amount into a field.

My question is - how do I subtract the amount of stock ordered from the amount of stock in the table ProductType? I know I will need some form of DELETE statement but I'm not sure quite how to craft a sufficient statement.

2
  • what is the connection between product type table and order item table? Commented Mar 29, 2015 at 17:53
  • Product ID is used in both tables. ProductID defines the name, amount, size etc. Commented Mar 29, 2015 at 18:21

2 Answers 2

1

You probably need an UPDATE rather than an DELETE. That being said, I would not advise to update the stock after having accepted the order. I feel it more manageable the other way around: update the stock, and accept the order only if there was enough items.

Something like that:

--> client place an order for 20 item id XXXX:

UPDATE ProductType SET amount = amount - 20
 WHERE amount >= 20 AND item_id = 'XXXX';
 ^^^^^^^^^^^^^^^^^^
Please note that "guard" clause

That statement will either update 0 or 1 row. 1 row means "ok, stock updated". 0 means "not enough items left in stock". This is especially important in multi-user environment where you can have several concurrent updates of your stock for the same item.

After that only:

--> If 1 row updated

INSERT INTO OrderItem(..., amount) VALUES (....., 20);

Finally, in a real world application, you need to wrap all those statements in a transaction in case of unexpected failure after the stock update.

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

Comments

0

I dont know correctly what you are expecting.Assuming

If table ProductType --> type1 amount

Then inserting to table OrderItem n items of type1.So assuming that you have to decrease that much amount from ProductType

When you insert n amount into OrderItem,

Here you can use UPDATE

UPDATE OrderItem SET column_name = column_name - n WHERE ...

Update

update the stock, and accept the order only if there was enough items, is the good process steps.

Hope this helps

2 Comments

How do I refer to the ProductType table in the UPDATE statement? Would it be something along the lines of "UPDATE OrderItem SET amountordered = ProductType.amountinstock - n WHERE amountordered=?"
why dont you try to put a variable amount to decrease or inrease?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.