Working with SQL Views

1. Creating Views

FormExample
BasicCREATE VIEW v AS SELECT ...;
ReplaceCREATE OR REPLACE VIEW v AS ...;
With check optionWITH CHECK OPTION — enforce predicates on writes
Security barrier (PG)WITH (security_barrier=true)
DropDROP VIEW [IF EXISTS] v;

2. Querying Views

AspectDetail
Same as tableSELECT ... FROM view WHERE ...
PlannerInlines view definition into outer query
Predicate pushdownUsually works through views

3. Creating Updatable Views

RequirementDetail
Simple SELECTNo JOIN, GROUP BY, DISTINCT, set ops
All NOT NULL cols selectableFor inserts to succeed
INSTEAD OF triggersMake complex views writable manually
WITH CHECK OPTIONBlocks writes that violate view filter

4. Using Views for Security

PatternUse
Column hidingProject only allowed columns
Row filteringWHERE owner = current_user
Aggregation onlyExpose summaries, hide individual rows
Grant on view onlyRevoke base table access from app role

Example: Per-User View

CREATE VIEW my_orders WITH (security_barrier=true) AS
  SELECT id, total, placed_at FROM orders
  WHERE customer_id = current_setting('app.customer_id')::BIGINT;
GRANT SELECT ON my_orders TO app_role;

5. Creating Materialized Views

AspectDetail
PersistentStored on disk as a table
StaleUntil refreshed
IndexableYes — create indexes for fast lookups
WITH DATA / NO DATAPopulate now or empty

6. Refreshing Materialized Views

ModeDetail
REFRESH MATERIALIZED VIEW vExclusive lock, blocks readers
REFRESH ... CONCURRENTLYNon-blocking, requires unique index
ON COMMIT (Oracle)Auto-refresh after committing source change
Incremental refreshOracle FAST refresh; PG via pg_ivm / triggers

7. Indexing Materialized Views

IndexPurpose
Unique indexRequired for CONCURRENTLY refresh
Lookup indexesSame as tables (B-tree, GIN, etc.)
RebuildIndexes are maintained on refresh

8. Dropping Views

FormDetail
DROP VIEW vErrors on dependents
DROP VIEW v CASCADEDrops dependent views/objects
DROP MATERIALIZED VIEWSeparate command

9. Managing View Dependencies

CatalogQuery
PGpg_depend, information_schema.view_table_usage
MySQLinformation_schema.views
OracleDBA_DEPENDENCIES
Rebuild strategyDrop in reverse-dependency order, recreate forward

10. Optimizing View Performance

TipDetail
Simple views inlinePlanner sees through them
Avoid view stackingMulti-level views complicate planner
Materialize hot viewsIf freshness allows
Functional indexesIf view uses expressions