Selected topic
Views
Prefer practical output? Use related tools below while reading.
A view in SQL is a virtual table based on the result of a query. It's a way to simplify complex queries and present data in a more user-friendly format. However, when underlying tables change, views can become outdated, requiring updates to reflect these changes.
### 1. Modifying the Underlying Tables
If changes to underlying tables do not affect the view's definition, simply update the tables as needed. This approach is straightforward but may require manual effort to ensure data consistency.
sql
-- Update an underlying table
ALTER TABLE customers
ADD COLUMN email VARCHAR(255);### 2. Recreating the View
When changes to underlying tables impact the view's definition, recreate the view with the updated query. This technique ensures that the view accurately reflects the changed data.
sql
-- Original view creation (simplified for example)
CREATE VIEW customer_info AS
SELECT c.customer_id, c.name, o.order_date
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id;-- Update underlying tables and recreate the view with updated query
ALTER TABLE customers ADD COLUMN email VARCHAR(255);
DROP VIEW customer_info;
CREATE VIEW customer_info AS
SELECT c.customer_id, c.name, c.email, o.order_date
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id;