Intermediate 30 min read

Process Stock Adjustments (DML)

By the end of this lesson, you'll be able to:

  • Increase stock when a shipment is received
  • Decrease stock when an order ships out, without allowing it to go negative
  • Explain why an adjustment reads the current value before writing a new one

Prerequisites: "Query Low-Stock Items"

Receiving a shipment (increasing stock)

public void receiveShipment(Id warehouseStockId, Decimal quantityReceived) {
    Warehouse_Stock__c stock = [
        SELECT Id, Quantity_On_Hand__c FROM Warehouse_Stock__c WHERE Id = :warehouseStockId
    ];
    stock.Quantity_On_Hand__c += quantityReceived;
    update stock;
}

Reading the record first, then adding to its current value, is exactly Module 19's "Update" lesson pattern — += here is Module 4's compound assignment operator, doing real inventory work.

Shipping an order out (decreasing stock)

public Boolean shipOrder(Id warehouseStockId, Decimal quantityShipped) {
    Warehouse_Stock__c stock = [
        SELECT Id, Quantity_On_Hand__c FROM Warehouse_Stock__c WHERE Id = :warehouseStockId
    ];

    if (stock.Quantity_On_Hand__c < quantityShipped) {
        System.debug('Not enough stock to ship this quantity.');
        return false;
    }

    stock.Quantity_On_Hand__c -= quantityShipped;
    update stock;
    return true;
}

Checking Quantity_On_Hand__c < quantityShipped before subtracting prevents stock from ever going negative — a warehouse can't ship out more than it actually has, and this method returns false rather than silently creating an impossible negative quantity.

Why read-then-write, not a blind overwrite

// DON'T DO THIS
stock.Quantity_On_Hand__c = quantityReceived; // overwrites, doesn't add

Setting the field directly to the shipment quantity would erase whatever stock was already there instead of adding to it — the read-then-modify-then-write pattern (query the current value, change it, update) is what makes an adjustment actually additive rather than destructive.

Exercise

Given a Warehouse_Stock__c already queried with Quantity_On_Hand__c, write code that adds 25 to its quantity and saves the change.

Show hint

stock.Quantity_On_Hand__c += 25; update stock;

APEX

Process Stock Adjustments (DML) Quiz

1. Why does shipOrder check the current quantity before subtracting?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

A stock adjustment is never a blind overwrite — it always reads the current quantity first, then applies a change relative to it, guarding against an impossible negative result.