Views, Materialized Views, Functions, Triggers, and Procedures
Use PostgreSQL database objects to simplify access, centralize logic, and support repeatable data operations.
Inside this chapter
- Why Database Objects Matter
- Views and Materialized Views
- Functions and Triggers
- Procedure and Maintenance Use Cases
Series navigation
Study the chapters in sequence for the clearest path from beginner PostgreSQL concepts to advanced query design and production operations. Use the navigation at the bottom of every page to move chapter by chapter.
Why Database Objects Matter
Not all useful logic belongs in application code. Some logic is better centralized in reusable database objects, especially when many services or reports depend on the same business rules. PostgreSQL provides powerful database-side capabilities for these scenarios.
Views and Materialized Views
CREATE VIEW active_customers AS
SELECT customer_id, full_name, email
FROM customers
WHERE is_active = TRUE;
A standard view simplifies repeated query patterns. A materialized view stores the result physically and can help performance for repeated reporting workloads, though it needs refresh management.
Functions and Triggers
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at := CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Functions can encapsulate logic, and triggers can react to row changes. These tools are powerful, but advanced teams use them carefully so hidden behavior does not make systems hard to reason about.
Procedure and Maintenance Use Cases
PostgreSQL procedures and server-side functions can help with recurring jobs, controlled updates, and domain-specific data operations. They are particularly useful when multiple applications rely on the same core data behavior and need a consistent database-side implementation.