9. Views and Roles
Part I: Views
Description
A view is a named, stored query that presents data from one or more underlying tables. It can be accessed like a virtual table: a logical table defined by a SELECT statement, which stores no data of its own (except materialized views).
Syntax
CREATE [OR REPLACE] [TEMP | TEMPORARY] VIEW view_name AS
query
[WITH [CASCADED | LOCAL] CHECK OPTION];
| Parameter | Meaning |
|---|---|
OR REPLACE | If a view with the same name exists, it is replaced |
TEMP / TEMPORARY | The view is dropped automatically at the end of the session |
query | A SELECT or VALUES command providing the columns and rows |
WITH CHECK OPTION | For automatically updatable views: INSERT/UPDATE through the view are checked so new rows satisfy the view's defining condition |
LOCAL | Check only the conditions of this view (not base views, unless they have their own CHECK OPTION) |
CASCADED | Check the conditions of this view and all underlying views (default if neither is given) |
Advantages
- Simplicity: hides complex queries behind a simple name.
- Security: restricts access to specific columns or rows.
- Consistency: the same data presentation across all applications.
Types of Views
- Simple views: based on a single table, with no functions, grouping or aggregation.
- Complex views: include joins, subqueries and aggregations.
- Materialized views: physically store the result set; faster for large datasets or expensive queries, but must be refreshed manually or on a schedule.
Working with Views
-- Create
CREATE VIEW customer_master AS
SELECT customer_id, first_name || ' ' || last_name AS name, email
FROM customer;
-- Query it like a table
SELECT * FROM customer_master WHERE name LIKE 'A%';
-- Change the defining query
CREATE OR REPLACE VIEW customer_master AS
SELECT customer_id, first_name, last_name, email FROM customer;
-- Rename
ALTER VIEW customer_master RENAME TO customer_info;
-- Drop (one or several)
DROP VIEW [IF EXISTS] view_name [CASCADE | RESTRICT];
DROP VIEW IF EXISTS view_name1, view_name2;
Materialized Views
A materialized view caches the result of a complex, expensive query and lets you refresh it periodically. Common in data warehouses and business-intelligence applications.
CREATE MATERIALIZED VIEW view_name AS
query
WITH [NO] DATA;
REFRESH MATERIALIZED VIEW view_name;
DROP MATERIALIZED VIEW view_name;
WITH DATAloads data at creation time.WITH NO DATAflags the view as unreadable until it is loaded withREFRESH MATERIALIZED VIEW.
Part II: Roles
Description
PostgreSQL manages access permissions through roles. A role can be a database user or a group of users, depending on how it is set up. Roles can own objects (tables, functions) and grant privileges on them to other roles.
- Database roles are completely separate from operating-system users.
- Roles are global across the database cluster, not per database.
CREATE ROLE name;
SELECT rolname FROM pg_roles; -- list existing roles
Role Attributes
| Attribute | Meaning | Example |
|---|---|---|
LOGIN | Role can be used to connect (equivalent to a "user") | CREATE ROLE name LOGIN; or CREATE USER name; |
SUPERUSER | Bypasses all permission checks except the right to log in. Dangerous; do most work as a non-superuser. Only a superuser can create one | CREATE ROLE name SUPERUSER; |
CREATEDB | May create databases | CREATE ROLE name CREATEDB; |
CREATEROLE | May create, alter and drop other roles and manage membership (but not superuser roles) | CREATE ROLE name CREATEROLE; |
REPLICATION | May initiate streaming replication (must also have LOGIN) | CREATE ROLE name REPLICATION LOGIN; |
PASSWORD | Password used when the authentication method requires it (password, md5); separate from OS passwords | CREATE ROLE name PASSWORD 'string'; |
Attributes can be changed later:
ALTER ROLE name WITH CREATEDB;
ALTER ROLE name WITH PASSWORD 'new_password';
Role Membership (Groups)
Group users into a role so privileges can be granted or revoked for the whole group.
CREATE ROLE staff;
GRANT staff TO alice, bob; -- add members
REVOKE staff FROM bob; -- remove a member
- Group roles can be members of other group roles.
- The database does not allow circular membership loops.
Dropping Roles and Ownership
DROP ROLE name;
ALTER TABLE bobs_table OWNER TO alice; -- transfer one object
-- Reassign everything owned by a role before dropping it
REASSIGN OWNED BY doomed_role TO successor_role;
DROP OWNED BY doomed_role;
DROP ROLE doomed_role;
Example: Airport Database
Add a new table to the airport database, create users and assign them roles:
CREATE ROLE manager LOGIN PASSWORD 'secret';
CREATE ROLE clerk LOGIN PASSWORD 'secret2';
GRANT SELECT, INSERT, UPDATE, DELETE ON booking TO manager;
GRANT SELECT ON booking TO clerk;
Conclusion
Views simplify and protect data access; roles decide who may see and change which objects. Used together (for example, granting a role access to a view but not to the base table) they provide a flexible security layer.
All rights remain with the original author (Algo-holics). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me