SQL CREATE VIEW Keyword
In SQL, a view is a virtual table based on the result-set of an SQL statement. It doesn't store data itself; instead, it provides a customized way to view or access data from one or more underlying tables.
Creating a View
Using CREATE VIEW
The CREATE VIEW
command creates a new view. This view acts like a regular table but dynamically reflects the data from the underlying query.
Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example: Creating a View of Brazilian Customers
Syntax
CREATE VIEW BrazilCustomers AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = "Brazil";
Output
A view named 'BrazilCustomers' is created. It shows only the 'CustomerName' and 'ContactName' columns for customers from Brazil.
Querying the View
You can query a view just like a regular table:
Syntax
SELECT * FROM BrazilCustomers;
Output
This query retrieves all data from the 'BrazilCustomers' view, effectively showing only Brazilian customer names and contact names.
CustomerName | ContactName
----------------------------
Maria Santos | Maria Silva
... | ...
Updating a View
Using CREATE OR REPLACE VIEW
The CREATE OR REPLACE VIEW
command lets you modify an existing view. If the view doesn't exist, it creates it; otherwise, it replaces the old definition with the new one.
Example: Adding a Column to the View
Syntax
CREATE OR REPLACE VIEW BrazilCustomers AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = "Brazil";
Output
The 'BrazilCustomers' view is updated to now include the 'City' column along with the customer name and contact name.
Deleting a View
Using DROP VIEW
The DROP VIEW
command removes a view from the database.
Syntax
DROP VIEW BrazilCustomers;
Output
The 'BrazilCustomers' view is deleted from the database.