SQL Views
SQL Views
A view is a virtual table based on the result set of a SQL query. A view does not store data itself (in most databases); it stores the query definition and returns data when queried.
Why Use Views?
- Simplify complex queries (especially with JOINs)
- Reuse common query logic
- Provide a security layer by exposing only selected columns/rows
- Make reporting queries easier to maintain
Create a View
CREATE VIEW view_name AS SELECT column1, column2 FROM table_name WHERE condition;
Example: Active Customers View
CREATE VIEW active_customers AS SELECT id, name, email, country FROM customers WHERE status = 'active';
Query a View
You query a view like a normal table:
SELECT * FROM active_customers ORDER BY name;
Example: View with JOIN
Views are great for hiding JOIN complexity.
CREATE VIEW customer_orders AS
SELECT c.id AS customer_id,
c.name AS customer_name,
o.id AS order_id,
o.order_date
FROM customers AS c
JOIN orders AS o
ON c.id = o.customer_id;
Updateable Views (Important Note)
Some views can be updated (INSERT/UPDATE/DELETE) if they meet certain rules. Views that include complex joins, aggregates, or GROUP BY are often not updateable.
Replace or Change a View
Many systems support CREATE OR REPLACE VIEW. If not available, you can drop and recreate the view.
CREATE OR REPLACE VIEW active_customers AS SELECT id, name, email, country FROM customers WHERE status = 'active';
Drop a View
DROP VIEW active_customers;
Common Mistakes
- Assuming a view stores data (it usually does not)
- Forgetting that views depend on underlying tables and columns
- Using views as a replacement for proper indexing
Best Practice
Use views to standardize common queries and to expose only the data that should be queried. Keep view definitions simple and well-named.
Next Step
Continue with SQL Injection to learn how to protect your application from dangerous SQL attacks.