---
title: "Postgres Views Reference: CREATE VIEW to Materialized"
description: "A Postgres view is a named SELECT stored in the database; it holds no data and runs its query every time you read it."
canonical: "https://www.aifordatabase.com/blog/postgres-views-reference/"
author: "Dhrumil Barot"
author_bio: "Dhrumil is an enterprise analytics expert. Dhrumil built AI for Database so anyone on a team can get answers from live company data in plain English, without waiting on a data team."
published: 2026-12-03
updated: 2026-12-03
---

# Postgres Views Reference: CREATE VIEW to Materialized

**TL;DR:** A Postgres view is a named `SELECT` stored in the database; it holds no data and runs its query every time you read it. Use `CREATE OR REPLACE VIEW` to define it, a materialized view when you need stored results you refresh on a schedule, and `security_invoker = true` when row-level security must apply. AI for Database can query your views in plain English, so a clean reporting view becomes something the whole team can ask questions of without writing SQL.

[Try AI for Database free at aifordatabase.com](https://app.aifordatabase.com/signup)

Postgres views are saved queries you can select from like a table. `CREATE VIEW name AS SELECT ...` creates one; the view is not physically materialized, so PostgreSQL rewrites every query against it into a query against the base tables ([PostgreSQL CREATE VIEW docs](https://www.postgresql.org/docs/current/sql-createview.html)). Simple single-table views are automatically updatable. A materialized view (`CREATE MATERIALIZED VIEW`) stores the result on disk and only changes when you run `REFRESH MATERIALIZED VIEW`. Views exist to give a complex join a name, to hide sensitive columns, and to keep one definition of a metric that every report reuses.

## Postgres views at a glance

| Task | Statement | Notes |
| --- | --- | --- |
| Create a view | `CREATE VIEW v AS SELECT ...;` | Fails if `v` exists |
| Create or change | `CREATE OR REPLACE VIEW v AS ...;` | Same columns, same order and types; new columns only at the end |
| Rename columns | `CREATE VIEW v (a, b) AS ...;` | Or alias in the SELECT |
| Temporary view | `CREATE TEMP VIEW v AS ...;` | Dropped at session end |
| Recursive view | `CREATE RECURSIVE VIEW v (cols) AS ...;` | Column list required |
| Enforce WHERE on writes | `... WITH CASCADED CHECK OPTION;` | CASCADED is the default |
| Use caller's permissions | `WITH (security_invoker = true)` | PostgreSQL 15+, makes RLS apply |
| Drop | `DROP VIEW IF EXISTS v;` | `CASCADE` also drops dependent views |
| List views | `\dv` or `SELECT * FROM pg_views;` | Also `information_schema.views` |
| Materialized view | `CREATE MATERIALIZED VIEW mv AS ...;` | Stores rows, can be indexed |
| Refresh | `REFRESH MATERIALIZED VIEW CONCURRENTLY mv;` | Needs a unique index |

![A view stores a query, a materialized view stores the result of that query](https://cdn.sanity.io/images/upsr56wu/production/dd682bd9a73bd4586ec44d71438a655d3c4b1a16-1344x326.png?w=1280)

FIG 01 — A materialized view skips steps 2 and 3 and returns rows saved at the last refresh.

## How do you create a view in Postgres?

You create a view with `CREATE VIEW name AS` followed by any `SELECT` or `VALUES` query. Here is a reporting view that turns an orders table into monthly revenue:

```
CREATE VIEW monthly_revenue AS
SELECT date_trunc('month', o.created_at)::date AS month,
       c.country,
       count(*)              AS orders,
       sum(o.amount_cents) / 100.0 AS revenue
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
GROUP BY 1, 2;

SELECT * FROM monthly_revenue WHERE month >= '2026-01-01' ORDER BY month;
```

Name every computed column. `CREATE VIEW vista AS SELECT 'Hello World';` produces a column called `?column?` of type `text`, which the docs call "bad form" ([source](https://www.postgresql.org/docs/current/sql-createview.html)).

One trap: `SELECT *` is expanded when the view is created. Columns you add to the table later do not appear in the view until you replace it.

### CREATE OR REPLACE VIEW rules

`CREATE OR REPLACE VIEW` swaps the query in place and keeps grants and dependent objects. The new query must return the same column names, in the same order, with the same data types; it may add columns at the end. Breaking that rule gives errors such as `cannot drop columns from view` or `cannot change name of view column`. To remove or reorder columns, `DROP VIEW` and create it again (with `CASCADE` if other views depend on it).

```
-- allowed: new column appended at the end
CREATE OR REPLACE VIEW monthly_revenue AS
SELECT date_trunc('month', o.created_at)::date AS month,
       c.country,
       count(*) AS orders,
       sum(o.amount_cents) / 100.0 AS revenue,
       count(DISTINCT o.customer_id) AS buyers
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
GROUP BY 1, 2;
```

## Can you update a Postgres view?

Yes, if it is simple. PostgreSQL makes a view automatically updatable for `INSERT`, `UPDATE`, `DELETE` and `MERGE` when all of these hold ([docs](https://www.postgresql.org/docs/current/sql-createview.html)):

1.  Exactly one entry in `FROM`, and it is a table or another updatable view.
2.  No `WITH`, `DISTINCT`, `GROUP BY`, `HAVING`, `LIMIT` or `OFFSET` at the top level.
3.  No `UNION`, `INTERSECT` or `EXCEPT` at the top level.
4.  No aggregates, window functions or set-returning functions in the select list.

So `monthly_revenue` above is read-only (it joins and groups), while this one is writable:

```
CREATE VIEW active_customers AS
SELECT id, email, plan
FROM customers
WHERE status = 'active'
WITH CASCADED CHECK OPTION;

UPDATE active_customers SET plan = 'team' WHERE id = 42;   -- works
INSERT INTO active_customers (email, plan) VALUES ('a@b.com', 'pro');
-- fails if the new row would have status <> 'active'
```

Without `CHECK OPTION`, an insert through the view can create rows the view itself cannot see. `LOCAL` checks only this view's condition; `CASCADED` (the default when you write just `WITH CHECK OPTION`) also checks the views underneath. For views that fail the rules, write `INSTEAD OF` triggers that translate the write to the base tables.

## View security: owner rights vs security\_invoker

By default PostgreSQL checks access to the base tables with the permissions of the view's owner, not the person querying. That is useful (grant `SELECT` on the view, not the table) and dangerous: on Supabase, a view created by a privileged role bypasses the row-level security of the tables it reads ([Supabase views guide](https://supabase.com/docs/guides/database/views)). Set `security_invoker` to check the querying role instead:

```
CREATE VIEW customer_summary WITH (security_invoker = true) AS
SELECT id, country, plan, created_at
FROM customers;              -- email and phone deliberately left out

ALTER VIEW monthly_revenue SET (security_invoker = true);
GRANT SELECT ON customer_summary TO reporting;
```

With `security_invoker`, the reader needs privileges on the view and on every table it reads. Leaving out sensitive columns, as above, is the simplest way to give an analyst or a tool read access without exposing personal data. Our guide to [giving AI read-only database access](https://www.aifordatabase.com/blog/give-ai-read-only-database-access/) uses this pattern.

## What is the difference between a view and a materialized view?

A view stores the query; a materialized view stores the result. Reading a view always returns current data and costs whatever the query costs. Reading a materialized view is as fast as reading a table, but the data is as old as the last refresh.

|  | View | Materialized view |
| --- | --- | --- |
| Stores rows | No | Yes, on disk |
| Data freshness | Always current | As of last `REFRESH` |
| Read speed | Same as the underlying query | Table speed, can add indexes |
| Can be indexed | No | Yes |
| Writable | Simple views, automatically | Never |
| Good for | Naming joins, hiding columns, one metric definition | Slow aggregates for dashboards |

```
CREATE MATERIALIZED VIEW daily_signups AS
SELECT created_at::date AS day, count(*) AS signups
FROM users
GROUP BY 1;

CREATE UNIQUE INDEX ON daily_signups (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_signups;
```

`CONCURRENTLY` lets reads continue during the refresh, but it only works when the materialized view has at least one `UNIQUE` index on plain columns with no `WHERE` clause, and it cannot be combined with `WITH NO DATA` ([REFRESH docs](https://www.postgresql.org/docs/current/sql-refreshmaterializedview.html)). A plain refresh is usually faster for large changes but can block readers. PostgreSQL has no built-in refresh schedule; use `pg_cron` or an external scheduler (see [how to schedule a Postgres query](https://www.aifordatabase.com/blog/postgres-schedule-query/)).

![A view returns live rows while a materialized view returns rows saved at the last refresh](https://cdn.sanity.io/images/upsr56wu/production/199092af91ed46911d498b5f51a5121b9959ff10-1344x410.png?w=1280)

FIG 02 — Rows added after the refresh appear only after the next REFRESH.

## Do views slow down queries?

A plain view adds no cost of its own. The planner inlines the view's query into yours, so `SELECT * FROM monthly_revenue WHERE country = 'IN'` is planned like the full query with that filter, and indexes on the base tables still apply. Views get slow when they hide expensive work (several joins, `DISTINCT`, aggregates over millions of rows) that every caller pays for, or when views are stacked on views until nobody can read the plan. Check with [EXPLAIN](https://www.aifordatabase.com/blog/postgresql-explain-query/). If the expensive part does not need to be live, move it into a materialized view; if it does, fix the query and its indexes first, because a materialized view is not a fix for an inefficient query (Supabase makes the same point).

## Managing views: list, rename, drop

```
-- list views in the current database
SELECT schemaname, viewname FROM pg_views
WHERE schemaname NOT IN ('pg_catalog', 'information_schema');

-- show a view's definition
SELECT pg_get_viewdef('monthly_revenue', true);

ALTER VIEW monthly_revenue RENAME TO revenue_by_month;
ALTER VIEW revenue_by_month RENAME COLUMN buyers TO unique_buyers;
DROP VIEW IF EXISTS revenue_by_month CASCADE;
```

In psql, `\dv` lists views and `\dm` lists materialized views.

## Querying Postgres views with AI for Database

Views are the best interface between a database and the people who read it: they give business names to messy joins and keep the revenue definition in one place. AI for Database connects to [PostgreSQL](https://www.aifordatabase.com/databases/postgresql/) read-only and treats your views like tables, so a teammate can ask "revenue by country for the last six months from monthly\_revenue" and get the table or chart, with the SQL it ran shown underneath. Answers can be pinned to a dashboard that refreshes on a schedule, and action workflows can watch a view, for example "when daily signups drop below 50, send a Slack alert". A practical setup:

1.  Build reporting views (like `monthly_revenue` and `customer_summary`) that leave out personal data.
2.  Create a reporting role with `SELECT` on those views only.
3.  Connect AI for Database with that role, so every question is limited to what the views expose.

AI for Database does not create or refresh materialized views for you; you define those in Postgres and it reads them like any other relation.

D

Written by [Dhrumil Barot](https://www.aifordatabase.com/about/#founder)

Dhrumil is an enterprise analytics expert. Dhrumil built AI for Database so anyone on a team can get answers from live company data in plain English, without waiting on a data team.

[LinkedIn](https://www.linkedin.com/in/bdhrumil)[X](https://x.com/fyidhrumil)

## Frequently Asked Questions

### How do you create a view in Postgres?

Run CREATE VIEW view\_name AS SELECT ...;. Use CREATE OR REPLACE VIEW to change an existing view, as long as the columns keep their names, order and types.

### What is the difference between a view and a materialized view?

A view runs its query on every read and is always current. A materialized view stores the result, reads at table speed, can be indexed, and is only as fresh as its last REFRESH MATERIALIZED VIEW.

### Can you update a Postgres view?

Yes, when the view reads one table or updatable view and has no DISTINCT, GROUP BY, HAVING, LIMIT, OFFSET, set operations, aggregates or window functions. Other views need INSTEAD OF triggers.

### Do views slow down queries?

No, a plain view is inlined into your query and uses the base tables' indexes. It is only slow when its own query is slow; materialize it or tune that query.

### Does a Postgres view respect row-level security?

Only when it is created with security\_invoker = true (PostgreSQL 15 and later). Otherwise the base tables are read with the view owner's rights.

### Why are new table columns missing from my view?

SELECT was expanded when the view was created. Re-run CREATE OR REPLACE VIEW to pick up the new columns. Ready to let your team ask questions of your Postgres views? \[Try AI for Database free at aifordatabase.com\](https://app.aifordatabase.com/signup)

Read next

*   [HOW TO BUILD A CUSTOMER 360 VIEW FROM YOUR DATABASE WITHOUT SQL →](https://www.aifordatabase.com/blog/customer-360-view-from-database/)
*   [POSTGRES DATE BETWEEN REFERENCE: RANGES AND TIMESTAMPS →](https://www.aifordatabase.com/blog/postgres-date-between/)
*   [JSON EXTRACT IN MYSQL: JSON\_EXTRACT, -> AND ->> REFERENCE →](https://www.aifordatabase.com/blog/json-extract-mysql/)

Source: https://www.aifordatabase.com/blog/postgres-views-reference/
