Skip to content

Product Sales Update πŸš€ΒΆ

Prerequisites: SQL UPDATE Statement, PL/SQL Basics

Mentor's Note: In a real shop, the "Total Amount" on a shelf doesn't update itself. You need a bit of logic to multiply the Price and Quantity. This lab shows you how to automate that update in your database! πŸ’‘


🌟 The Scenario: The Candy Shop 🍬¢

Imagine you are managing a candy shop inventory.

  • The Data: You have Price per unit ($2) and Quantity Sold (5). πŸ“¦
  • The Logic: The Total Sale column is currently empty. You need to calculate \(2 \times 5 = 10\). βš™οΈ
  • The Result: The database record is updated automatically with the correct total. βœ…

πŸ“– Concept ExplanationΒΆ

1. Derived ColumnsΒΆ

A Derived Column is a column whose value comes from other columns. We usually don't store them, but sometimes we "materialize" them (save them) to make reporting faster. πŸƒβ€β™‚οΈπŸ’¨

2. The Transaction RuleΒΆ

Whenever you change data using UPDATE, you should either COMMIT (save permanently) or ROLLBACK (undo if there's a mistake).


🎨 Visual Logic: The Update Cycle¢

graph LR
    A[Table Record πŸ“‹] --> B[Get Price & Qty πŸ“₯]
    B --> C{Calculate Total βš™οΈ}
    C --> D[UPDATE Table Record βœ…]
    D --> E[COMMIT Changes 🏁]

πŸ’» Implementation: The Sales LabΒΆ

-- πŸ›’ Scenario: Closing the day at the candy shop
-- πŸš€ Action: Updating the Total_Sale for a specific product

DECLARE
    v_prod_id  NUMBER := &ID;
    v_price    NUMBER;
    v_qty      NUMBER;
    v_total    NUMBER;
BEGIN
    -- πŸ” 1. Fetch current values
    SELECT unit_price, quantity_sold 
    INTO v_price, v_qty
    FROM products
    WHERE product_id = v_prod_id;

    -- βš™οΈ 2. Logic: Multiply
    v_total := v_price * v_qty;

    -- πŸ”„ 3. Update the record
    UPDATE products
    SET total_sales = v_total
    WHERE product_id = v_prod_id;

    DBMS_OUTPUT.PUT_LINE('Product ' || v_prod_id || ' updated! Total: $' || v_total);
    COMMIT;
EXCEPTION
    WHEN NO_DATA_FOUND THEN
        DBMS_OUTPUT.PUT_LINE('❌ Error: Product ID not found.');
END;
/

πŸ“Š Sample Dry RunΒΆ

Product ID: 501 | Price: 10 | Qty: 4

Step Action Logic Result
1 Fetch Data Get 10 and 4 v_price=10, v_qty=4 πŸ“¦
2 Calculate 10 * 4 v_total=40 βš™οΈ
3 Update SET total=40 Row 501 updated! βœ…

πŸ“‰ Complexity AnalysisΒΆ

  • Time Complexity: \(O(1)\) - Single row lookup and update. ⏱️
  • Space Complexity: \(O(1)\) - Constant memory usage. πŸ’Ύ

🎯 Practice Problems¢

Easy Level 🟒¢

  • Modify the block to also apply a 5% Discount to the Total Sale if the quantity sold is greater than 100.

Medium Level 🟑¢

  • Use a Cursor to update the total_sales for ALL products in the table at once.

πŸ’‘ Interview Tip πŸ‘”ΒΆ

"Interviewers often ask: 'Why store total_sales if you can calculate it in a SELECT?' Answer: For huge tables, calculating every time is slow. Storing it (pre-calculation) makes reports run faster!"


πŸ“ˆ Learning PathΒΆ