Skip to main content
Views are virtual tables based on the result of a SQL query. They simplify complex queries, improve security, and in the case of materialized views, can significantly boost performance.

Standard views

Query-based views

Create a view from a Drizzle query:

SQL-based views

Define views with raw SQL for complex queries:

Querying views

Use views like regular tables:

Existing views

Reference views created outside Drizzle:
Use .existing() to tell Drizzle this view already exists and shouldn’t be created during migrations.

PostgreSQL materialized views

Materialized views store query results physically, improving performance for expensive queries:

Basic materialized view

Materialized view with configuration

Materialized view without data

Create the view structure without populating it:
Use withNoData() to create the view structure quickly. Populate it later with REFRESH MATERIALIZED VIEW.

Refreshing materialized views

Materialized views need manual refresh to update their data:
Or use the query builder:

PostgreSQL view options

Security options

boolean
Prevents leaking data through user-defined functions in WHERE clauses
boolean
Executes view with the privileges of the user calling it, not the view owner

Check options

Complete example

When to use views

1

Simplify complex queries

Encapsulate joins and filters into reusable views:
2

Improve security

Expose only necessary columns through views:
3

Optimize performance with materialized views

Cache expensive aggregations:
Standard views don’t improve performance - they’re just stored queries. Use materialized views for performance gains, but remember they need manual refresh.