-- A simple view: customer + their order count
CREATEORREPLACEVIEWcustomer_ordersASSELECTc.id,c.name,count(o.id)ASorder_count,COALESCE(sum(o.total),0)AStotal_spentFROMcustomers_examplecLEFTJOINorders_exampleoONo.customer_id=c.idGROUPBYc.id,c.name;-- Use it like a table
SELECT*FROMcustomer_ordersWHEREtotal_spent>0ORDERBYtotal_spentDESC;-- Simple updatable view (no joins, no aggregates, no DISTINCT)
CREATEORREPLACEVIEWalice_ordersASSELECT*FROMorders_exampleWHEREcustomer_id=1;-- You can INSERT through an updatable view
INSERTINTOalice_orders(id,customer_id,total)VALUES(10,1,99.00);-- WITH CHECK OPTION: refuse INSERTs/UPDATEs that wouldn't satisfy the view's WHERE
CREATEORREPLACEVIEWalice_orders_strictASSELECT*FROMorders_exampleWHEREcustomer_id=1WITHCHECKOPTION;-- This would fail because customer_id = 2 is not in the view's scope
-- INSERT INTO alice_orders_strict (id, customer_id, total) VALUES (11, 2, 1.00);
-- List views
SELECTviewname,definitionFROMpg_viewsWHEREschemaname='public'ORDERBYviewname;-- Drop a view
DROPVIEWIFEXISTSalice_orders;DROPVIEWIFEXISTSalice_orders_strict;DROPVIEWIFEXISTScustomer_orders;