A VIEW is a virtual table defined by a SQL query. It encapsulates complex joins and filters, making queries simpler and reusable.
CREATE VIEW active_customers AS SELECT customer_id, customer_name, last_order_date FROM customers WHERE status = 'active';
Now you can query active_customers
like a table:
SELECT * FROM active_customers;
CREATE VIEW dept_sales AS SELECT d.department_name, COUNT(o.order_id) AS orders_count, SUM(o.amount) AS total_sales FROM departments AS d LEFT JOIN orders AS o ON d.department_id = o.department_id GROUP BY d.department_name;
To modify its definition, use CREATE OR REPLACE
:
CREATE OR REPLACE VIEW active_customers AS SELECT customer_id, customer_name, email, last_order_date FROM customers WHERE status = 'active';
DROP VIEW IF EXISTS active_customers;
EXPLAIN
to check how MySQL optimizes view queries.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!