In SQL, a view serves as a virtual table generated from the output of an SQL query. It mimics the structure of a physical table, comprising rows and columns. The fields within a view are sourced from one or more actual tables within the database.
You can add SQL statements and functions to a view and present the data as if the data were coming from one single table.
A view is created with the CREATE VIEW
statement.
CREATE VIEW view_name AS SELECT column1, column2, … FROM table_name WHERE condition; |
Please note: A view presents current data at all times! Each time a user queries it, the database engine reconstructs the view.
The SQL below generates a view displaying all customers from Brazil:
CREATE VIEW [Brazil Customers] AS SELECT CustomerName, ContactName FROM Customers WHERE Country = ‘Brazil’; |
We can query the view above as follows:
SELECT * FROM [Brazil Customers]; |
The following SQL generates a view that selects each product from the “Products” table with a price higher than the average price:
CREATE VIEW [Products Above Average Price] AS SELECT ProductName, Price FROM Products WHERE Price > (SELECT AVG(Price) FROM Products); |
We can perform a query on the aforementioned view in the following manner:
SELECT * FROM [Products Above Average Price]; |
The CREATE OR REPLACE VIEW statement can be used to update a view.
CREATE OR REPLACE VIEW view_name AS SELECT column1, column2, … FROM table_name WHERE condition; |
The following SQL adds the “City” column to the “Brazil Customers” view:
CREATE OR REPLACE VIEW [Brazil Customers] AS SELECT CustomerName, ContactName, City FROM Customers WHERE Country = ‘Brazil’; |
The DROP VIEW statement is used to delete a view.
DROP VIEW view_name; |
The following SQL statement deletes the “Brazil Customers” view:
DROP VIEW [Brazil Customers]; |