| Lesson 9 | Calculated Fields |
| Objective | Explain why calculated fields are typically implemented with user views. |
Arithmetic (e.g., extended price):
CREATE OR REPLACE VIEW order_lines_v AS
SELECT ol.order_id,
ol.product_id,
ol.qty * ol.unit_price AS line_total
FROM order_lines ol;
Conditional Labels (e.g., status buckets):
CREATE OR REPLACE VIEW invoice_status_v AS
SELECT i.invoice_id,
CASE
WHEN i.paid_at IS NOT NULL THEN 'PAID'
WHEN CURRENT_DATE > i.due_date THEN 'OVERDUE'
ELSE 'OPEN'
END AS status_label
FROM invoices i;
Aggregates (e.g., order summary):
CREATE OR REPLACE VIEW order_summary_v AS
SELECT o.order_id,
SUM(oi.qty * oi.unit_price) AS order_total
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id;
WITH CHECK OPTION to enforce predicates on DML; CREATE FORCE VIEW for forward-declared views; materialized views for cached results; virtual (generated) columns; function-based indexes.WITH SCHEMABINDING for stable definitions.REFRESH MATERIALIZED VIEW; generated columns; powerful expression indexes for view predicates; views updatable in many cases.Calculated field: A value derived from other columns or expressions at query time.
Virtual table (view): A stored SELECT definition that returns rows from base tables; only the definition is stored, not the result.