SQL Views
In SQL, a view is a virtual table. Unlike a regular table that stores data directly, a view is a stored query that presents data from one or more underlying tables as if it were a single table. It doesn't store data itself; it dynamically generates its results whenever it's queried.
Creating Views
Using CREATE VIEW
You create a view using the CREATE VIEW
statement. This statement defines the structure and the underlying query for your view.
Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example: Brazilian Customers View
This creates a view showing only customers from Brazil.
Syntax
CREATE VIEW BrazilCustomers AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
Output
A view named 'BrazilCustomers' is created. It will display the 'CustomerName' and 'ContactName' for all rows in the 'Customers' table where the country is 'Brazil'.
Querying the View
You can query a view like a regular table:
Syntax
SELECT * FROM BrazilCustomers;
Output
This will show the CustomerName and ContactName of all customers from Brazil.
CustomerName | ContactName
-----------------------------
... | ...
Example: Products Above Average Price
This creates a view showing products with a price higher than the average price.
Syntax
CREATE VIEW ProductsAboveAveragePrice AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
Output
Creates a view named 'ProductsAboveAveragePrice'. It shows products whose price is greater than the average price across all products.
Syntax
SELECT * FROM ProductsAboveAveragePrice;
Output
This displays the ProductName and Price for products exceeding the average price.
ProductName | Price
--------------------
... | ...
Updating a View
Using CREATE OR REPLACE VIEW
To modify an existing view, use CREATE OR REPLACE VIEW
. This will replace the old view definition with the new one.
Example: Adding a City Column to the Brazil Customers View
Syntax
CREATE OR REPLACE VIEW BrazilCustomers AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
Output
The 'BrazilCustomers' view is updated to include the 'City' column.
Deleting a View
Using DROP VIEW
To delete a view, use the DROP VIEW
statement.
Syntax
DROP VIEW view_name;
Example: Dropping the Brazil Customers View
Syntax
DROP VIEW BrazilCustomers;
Output
The 'BrazilCustomers' view is deleted.