Sikau

Project: The café’s data · Day 3 · about 40 min

Index, view and transaction

Speed up lookups, save the report as a view, and place an order atomically.

Fast, reusable, all-or-nothing

Three PostgreSQL tools every real app needs: an index so looking up a dish's sales doesn't scan every row, a view so the report is one simple SELECT, and a transaction so an order and its stock change happen together — or not at all.

The script

CREATE INDEX order_items_dish_idx ON order_items (dish_id);

CREATE VIEW dish_revenue AS
SELECT d.name AS dish, SUM(oi.qty * d.price) AS revenue
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
JOIN dishes d ON d.id = oi.dish_id
WHERE o.status = 'served'
GROUP BY d.name;

BEGIN;
WITH new_order AS (
  INSERT INTO orders (customer_id) VALUES (2) RETURNING id
)
INSERT INTO order_items (order_id, dish_id, qty)
SELECT id, 1, 3 FROM new_order;
UPDATE dishes SET stock = stock - 3 WHERE id = 1;
COMMIT;

The rest of this lesson

  • Prove the index helpsexplain
  • The order transactionexplain
  • Half an order?predict
  • Tool for the jobmatch
  • Write the scriptwrite code
  • Badge quizquiz
  • What you builtrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 5 lessons of Project: The café’s data