-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05_schema_enhancements.sql
More file actions
47 lines (34 loc) · 1.2 KB
/
Copy path05_schema_enhancements.sql
File metadata and controls
47 lines (34 loc) · 1.2 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
-- Constraints
-- Ensure postal codes are numeric
ALTER TABLE tbl_events
ADD CONSTRAINT chk_postal_code CHECK (postal_code ~ '^[0-9]+$');
-- Ensure event_date is not in the past
ALTER TABLE tbl_events
ADD CONSTRAINT chk_event_date CHECK (event_date >= CURRENT_DATE);
-- Make company names unique
ALTER TABLE tbl_companies
ADD CONSTRAINT unique_company_name UNIQUE (name);
-- ============================
-- Indexes
-- Index on event_date for faster queries by date
CREATE INDEX idx_event_date ON tbl_events(event_date);
-- Index on company_id for faster joins
CREATE INDEX idx_event_company ON tbl_events(company_id);
-- Index on category_id for category-based reports
CREATE INDEX idx_event_category ON tbl_events(category_id);
-- ============================
-- Views
-- View: Popular Events
-- Shows top 5 events by click_count
CREATE OR REPLACE VIEW popular_events AS
SELECT event_name, click_count
FROM tbl_events
ORDER BY click_count DESC
LIMIT 5;
-- View: Events per Company
-- Summarizes how many events each company organizes
CREATE OR REPLACE VIEW events_per_company AS
SELECT c.name AS company_name, COUNT(e.id) AS total_events
FROM tbl_companies c
JOIN tbl_events e ON c.id = e.company_id
GROUP BY c.name;