In this lesson, you will learn how to encapsulate complex relational algebra expressions into persistent, reusable objects called views.
From Logic to Structure
Up until now, we have treated our joins, filters, and aggregations as transient queries—temporary instructions executed on demand. However, when a specific set operation (like a complex join between Employees, Departments, and Salaries) becomes a foundational part of your business logic, writing that entire SELECT block repeatedly is error-prone and inefficient.
A Relational View acts as a virtual table. It stores the SQL definition of an algebraic operation rather than the physical data itself. When you query a view, the database engine expands your request by "injecting" the underlying relational algebra defined in the view into your query plan.
Creating the Abstract Relation
Imagine you frequently need to see active employees with their department names. Instead of joining these tables every time, you define a view:
CREATE VIEW active_department_staff AS
SELECT e.employee_id, e.name, d.dept_name
FROM employees e
JOIN departments d ON e.dept_id = d.id
WHERE e.is_active = 1;
Once this is executed, active_department_staff behaves exactly like a persistent relation. You can now treat it as a base table in further operations:
SELECT dept_name, COUNT(*)
FROM active_department_staff
GROUP BY dept_name;
Why This Matters
By exposing this as an abstract relation, you achieve two major goals:
- Encapsulation: You hide the complexity of the join paths and filtering logic. If the definition of an "active employee" changes, you update the view definition once, and every report or application using it updates automatically.
- Consistency: Every user or process querying the view is guaranteed to use the exact same relational logic, eliminating the "drift" that occurs when developers manually rewrite the same join conditions.
Even though the view doesn't physically store the results, the database treats the view name as a valid relation in its relational algebra engine, allowing you to build modular, layered queries that are much easier to maintain.
Key Takeaway: Relational views turn complex, repetitive join and filter operations into reusable abstract relations that simplify your code and ensure logical consistency across your database.