Search code examples
coldfusiontransactionsrdbmsinventoryinventory-management

inventory system: transaction-based or store quantity, update with trigger?


How would you design the data model for an inventory management system in RDBMS?

Would you:

  1. store each purchase & usage, and uses SUM() and GROUP BY to calculate the warehouse quantity on-the-fly?
  2. same as 1, but consolidate the quantity daily, and use the value of the previous day?
  3. quantity as an Int field, update through application layer?
  4. same as 3, but make use of DB trigger?

Transaction-based inventory system seems to be superior in terms of level of details it captures, but it is harder to implement it correctly. Performance will degrade over time.

Quantity-based inventory system seems much easier, but might need extra lockings to make sure the Qty value is ++ or -- correct.

Which one would you choose?


Solution

  • I would most likely go the trigger route, and update the quantity as transactions are pushed into the database. This makes it really easy to see what the current quantity is without need of a bunch of subqueries and calculations.

    If it's done in a trigger, then you can ensure that regardless of where the transaction comes from, the quantities in your stock tables will always be updated (whether there are transactions added via hard INSERTs or via the application).

    If there are logging concerns, then wrap some logging into your trigger to track before/after quantities into a separate logging table.

    A trigger might look like this (not tested):

    CREATE TRIGGER [dbo].[OrderAdded] 
       ON  [dbo].[Orders] 
       AFTER INSERT
    AS 
    BEGIN
        DELCARE @ProductID int; DECLARE @Qty int;
        SET @ProductID = (SELECT ProductID FROM inserted);
        SET @Qty = (SELECT Qty FROM inserted);
        UPDATE StockTable 
        SET Stock = Stock - @Qty
        WHERE ID = @ProductID
    
    END
    

    I don't see that there would be a performance issue to worry about so long as you've got your StockTable properly indexed for the ID and Stock field (I'm of course making all of this up given that you didn't provide any DB information).