When to use view collections
Use view collections when you need to:- Aggregate data from multiple collections
- Create computed fields based on existing data
- Join related data for easier querying
- Generate reports and statistics
- Denormalize data for read performance
- Expose complex SQL queries through the REST API
Creating a view collection
Create a view collection with a SQL query:The query must include an
id column. If your query doesn’t naturally have one, use SQL to create it (e.g., ROW_NUMBER() or alias an existing unique column).Query requirements
Your SQL query must follow these rules:1
Include an id column
Every view must have an
id column for PocketBase to identify records.2
Use valid SQLite syntax
PocketBase uses SQLite, so your queries must be valid SQLite SQL.
3
Reference collections by name
Always use the collection name (not the table name) in your queries.
4
Be mindful of performance
Complex queries can impact performance. Add indexes to source collections.
Field inference
PocketBase automatically infers field types from your query:You don’t manually define fields for view collections. They’re generated from the SQL query when you save the collection.
Complete examples
User statistics view
Product inventory view
Monthly sales report
Working with view collections
Querying views
View collections support all standard list/view operations:Filtering and sorting
You can filter and sort on any field in the view:Updating view queries
To modify a view collection’s query:When you update a view query, PocketBase automatically regenerates the field definitions based on the new query results.
Limitations
- Read-only: No create, update, or delete operations
- No real-time subscriptions: Views don’t support real-time updates
- No file fields: Views cannot have file upload fields
- No relations from other collections: Other collections cannot have relation fields pointing to views (but views can reference any collection)
- Performance: Complex queries can be slow; optimize with indexes on source collections
Common patterns
Denormalized data for performance
Aggregated metrics
Time-based rollups
Best practices
- Performance
- Maintenance
- Security
- Keep queries simple when possible
- Add indexes to frequently joined/filtered columns
- Use
LEFT JOINinstead of subqueries when possible - Avoid
SELECT *- specify only needed columns - Test query performance before deploying
Next steps
Base collections
Learn about standard collections
Auth collections
Add user authentication
API rules
Secure your collections
Indexes
Optimize query performance