CREATE VIEW (Create View)
Last updated: 2026-11-04
CREATE VIEW (Create View)
CREATE VIEW saves a query as a reusable virtual table. A view stores no data of its own: each query expands it back into the underlying SQL, which makes views a natural way to narrow privileges, hide table structure, or reuse a complex query. A materialized view is the opposite — it stores the result and must be explicitly refreshed.
| Kind | command |
|---|---|
| Example Language | SQL |
📝 Syntax
CREATE [OR REPLACE] [TEMP] [RECURSIVE] VIEW <view name> [(<column>, ...)]
AS <query>
[WITH [CASCADED | LOCAL] CHECK OPTION]
⚙️ Parameters
| OR REPLACE | Replaces the definition when the view already exists |
|---|---|
| AS | The query that defines the view |
| CHECK OPTION | Blocks writes that violate the view's condition |
| TEMP | Creates a temporary view that dies with the session |
Returns:No return value. Once it succeeds the view can be queried like a table.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
DROP TABLE
DROP VIEW
CREATE TABLE
INSERT 0 3
CREATE VIEW
region | orders | total
-------+--------+-------
east | 2 | 350.50
west | 1 | 300.00
📌 Key Points
- A view is only an alias for a query: it stores no data and always reads through to the base tables.
- CREATE OR REPLACE VIEW swaps the definition without dropping the view, though column names and types are constrained.
- WITH CHECK OPTION rejects writes through the view that break its WHERE clause — new row violates check option for view.
- Views execute with the definer's rights, but the base table's own privileges still apply.
- A plain view re-runs its SQL on every query, which makes it far slower than a materialized view for expensive aggregations.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QShould I use a view or a materialized view?
AUse a view for small data sets that must reflect the latest rows; use a materialized view when the aggregation is expensive and slightly stale data is acceptable.
QCan a view take parameters?
ANo. The query is fixed at definition time; for parameters, write a function returning a table (RETURNS TABLE).