In SQL, a view is a virtual table that is based on the result of a SELECT query. It does not store the data itself but provides a way to represent the result of a query as if it were a table.
Views are useful for simplifying complex queries, providing a layer of abstraction, and securing sensitive data.
Views are used to optimize queries by breaking them down into simpler, reusable components.
Simplicity: Views can simplify complex queries by encapsulating them and representing the data simplified manner.
Security: View helps us to restrict access to specific data, exposing only what is necessary.
Reusability: View Statement can be reused in multiple queries, promoting consistency and reducing redundancy.
Maintainability: View helps us to manage schema changes by abstracting the underlying table structure.
CREATE VIEW viewName AS SELECT columnName1, columnName2 FROM tableName WHERE condition;
viewName: The name of the view you want to create.
columnName1, columnName2: The columns you want to include in the view.
tableName: The name of the table or tables from which you are selecting data.
condition: Optional. It specifies any conditions to filter the data.
To create a view, we can use the CREATE VIEW statement followed by the view name and the AS keyword, which succeeds by the SELECT statement that defines the view using the regular table from the database.
CREATE VIEW products_view AS SELECT product_id, product_name, price FROM products WHERE category = "HEALTH_CARE";
After creating a view, we can query it as if it were as regular table.
SELECT * FROM products_view;
To remove a view, We can use the DROP VIEW statement.
DROP VIEW viewName;
DROP VIEW products_view;
with the help of the above statement, we can DROP VIEW from the database.