0
0
MySQLquery~5 mins

Dropping and altering views in MySQL

Choose your learning style9 modes available
Introduction
Views help you see data in a simple way. Sometimes you need to change or remove these views to keep your data clear and useful.
When you want to remove a view that is no longer needed.
When you want to change the way a view shows data without deleting it.
When you fix mistakes in a view's design.
When you update a view to include new columns or filter data differently.
When cleaning up old views to keep the database organized.
Syntax
MySQL
DROP VIEW view_name;

ALTER VIEW view_name AS SELECT ...;
Use DROP VIEW to completely remove a view from the database.
Use ALTER VIEW to change the query that defines the view without deleting it.
Examples
This removes the view named 'employee_view' from the database.
MySQL
DROP VIEW employee_view;
This changes 'employee_view' to show only active employees with their id and name.
MySQL
ALTER VIEW employee_view AS SELECT id, name FROM employees WHERE active = 1;
Sample Program
First, we create a view showing id, name, and department. Then, we change it to show only id and name for employees in Sales. Next, we select all data from the updated view. Finally, we remove the view.
MySQL
CREATE VIEW employee_view AS SELECT id, name, department FROM employees;

ALTER VIEW employee_view AS SELECT id, name FROM employees WHERE department = 'Sales';

SELECT * FROM employee_view;

DROP VIEW employee_view;
OutputSuccess
Important Notes
Dropping a view removes it completely; you cannot use it after that unless recreated.
Altering a view changes its definition but keeps the view name and permissions intact.
Make sure no important queries depend on a view before dropping it.
Summary
Use DROP VIEW to delete a view you no longer need.
Use ALTER VIEW to update what data the view shows.
Always check your view changes to avoid breaking other parts of your database.