Database Views vs Tables
Views are virtual tables based on queries. They don't store data themselves but provide a simplified or secured window into your actual tables.
Creating a Simple View
CREATE VIEW active_customers AS
SELECT customer_id, name, email, registration_date
FROM customers
WHERE status = 'active' AND deleted_at IS NULL;
Using Views Like Tables
-- Query the view just like a table
SELECT * FROM active_customers
WHERE registration_date >= '2024-01-01';
Complex View with Joins
CREATE VIEW customer_order_summary AS
SELECT
c.customer_id,
c.name,
c.email,
COUNT(o.order_id) as total_orders,
SUM(o.total) as lifetime_value,
MAX(o.order_date) as last_order_date
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.name, c.email;
Views vs Tables
| Views | Tables |
|---|---|
| Virtual (no data storage) | Physical data storage |
| Always show current data | Store historical snapshots |
| Simplify complex queries | Direct data manipulation |
| Security layer (hide columns) | Full data access required |
When to Use Views
- Hide sensitive columns (e.g., salaries, passwords)
- Simplify complex joins for end users
- Create consistent calculated fields
- Maintain backward compatibility when table structure changes
Pro Tip: Use views to abstract complexity and enforce security. For frequently-accessed aggregated data, consider materialized views which cache results for better performance.
← Back to SQL Tips