-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04-database-objects-solutions.sql
More file actions
102 lines (87 loc) · 2.13 KB
/
Copy path04-database-objects-solutions.sql
File metadata and controls
102 lines (87 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
-- Solutions 04: Database Objects
-- 1.
CREATE OR REPLACE FUNCTION get_sales_by_category(p_category VARCHAR)
RETURNS TABLE (
order_id VARCHAR,
order_date DATE,
product_name VARCHAR,
sales DECIMAL,
profit DECIMAL
)
LANGUAGE sql
AS $$
SELECT
order_id,
order_date,
product_name,
sales,
profit
FROM superstore
WHERE category = p_category
ORDER BY order_date, order_id;
$$;
-- 2.
CREATE OR REPLACE PROCEDURE refresh_region_sales_summary()
LANGUAGE plpgsql
AS $$
BEGIN
DROP TABLE IF EXISTS region_sales_summary;
CREATE TABLE region_sales_summary AS
SELECT
region,
SUM(sales) AS total_sales,
SUM(profit) AS total_profit,
COUNT(*) AS total_orders
FROM superstore
GROUP BY region;
END;
$$;
CALL refresh_region_sales_summary();
-- 3.
CREATE INDEX IF NOT EXISTS idx_superstore_customer_id
ON superstore(customer_id);
CREATE INDEX IF NOT EXISTS idx_superstore_region_order_date
ON superstore(region, order_date);
-- 4.
CREATE OR REPLACE VIEW vw_customer_order_summary AS
SELECT
customer_id,
customer_name,
COUNT(DISTINCT order_id) AS total_orders,
SUM(sales) AS total_sales,
SUM(profit) AS total_profit
FROM superstore
GROUP BY customer_id, customer_name;
-- 5.
DROP MATERIALIZED VIEW IF EXISTS mv_sales_by_state;
CREATE MATERIALIZED VIEW mv_sales_by_state AS
SELECT
state,
region,
SUM(sales) AS total_sales,
SUM(profit) AS total_profit
FROM superstore
GROUP BY state, region;
REFRESH MATERIALIZED VIEW mv_sales_by_state;
-- 6.
CREATE TABLE IF NOT EXISTS superstore_update_audit (
audit_id BIGSERIAL PRIMARY KEY,
row_id INTEGER,
action_type VARCHAR(20),
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE OR REPLACE FUNCTION log_superstore_update()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO superstore_update_audit (row_id, action_type)
VALUES (NEW.row_id, 'UPDATE');
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS trg_superstore_update ON superstore;
CREATE TRIGGER trg_superstore_update
AFTER UPDATE ON superstore
FOR EACH ROW
EXECUTE FUNCTION log_superstore_update();