SQL Views
Here is a clear, practical, and complete guide to SQL Views, including syntax, behavior, updatable vs. non-updatable views, and examples for MySQL, PostgreSQL, SQL Server, and Oracle.
β What Is a SQL VIEW?
A VIEW is a virtual table created from a SQL query.
A view:
-
Does not store data (unless it’s a materialized view)
-
Is used like a table:
SELECT * FROM view_name; -
Helps simplify complex queries
-
Improves security by restricting sensitive columns
-
Provides abstraction and cleaner code
πΉ Basic Syntax β CREATE VIEW
π₯ Example: Simple View
Use it like a table:
π₯ Example: View with JOIN
π₯ Example: View for Aggregation
π¦ CREATE OR REPLACE VIEW (PostgreSQL, MySQL 8+, SQL Server)
π₯ Update a View (SQL Server)
π₯ Dropping a View
Safe drop:
π₯ Updatable Views (Important!)
Some views allow INSERT, UPDATE, and DELETE on them.
A view is updatable if:
-
Based on a single table
-
No GROUP BY
-
No DISTINCT
-
No aggregate functions
-
No subqueries
-
No UNION
Example (updatable):
Example (NOT updatable):
π₯ WITH CHECK OPTION (Ensures Data Integrity)
Prevents inserting or updating rows that don’t satisfy the view’s WHERE clause.
Now this will FAIL:
π MATERIALIZED VIEWS (PostgreSQL, Oracle, SQL Server Indexed Views)
Materialized views store the query result physically.
-
Faster for large aggregations
-
Must be refreshed
PostgreSQL Example:
Refresh:
π Advantages of Views
β Security
Expose only required columns:
β Simplify complex queries
Use a short SELECT instead of a long JOIN.
β Reusable logic
Write once β use everywhere.
β Reduce code duplication
Business logic centralized in one place.
π Disadvantages of Views
β Can hide performance problems
β Harder to index (views themselves arenβt indexed)
β Complex nested views become unreadable
β Not all views are updatable
π Best Practices
β Prefer CREATE OR REPLACE VIEW for safe updates
β Use meaningful names (e.g., vw_active_users)
β Avoid nested views unless necessary
β Use materialized views for expensive calculations
β Document whether a view is updatable or not
β Index underlying tables for performance
