Curriculum
Course: SQL
Login

Curriculum

SQL

SQL References

0/80

MySQL Functions

0/139

SQL Server Functions

0/84

SQL Quick Ref

0/1
Text lesson

SQL Views

SQL CREATE VIEW Statement

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 Syntax

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.

SQL CREATE VIEW Examples

The SQL below generates a view displaying all customers from Brazil:

Example

CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = ‘Brazil’

We can query the view above as follows:

Example

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:

Example

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:

Example

SELECT * FROM [Products Above Average Price]; 

SQL Updating a View

The CREATE OR REPLACE VIEW statement can be used to update a view.

SQL CREATE OR REPLACE VIEW Syntax

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:

Example

CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = ‘Brazil’;

SQL Dropping a View

The DROP VIEW statement is used to delete a view.

SQL DROP VIEW Syntax

DROP VIEW view_name

The following SQL statement deletes the “Brazil Customers” view:

Example

DROP VIEW [Brazil Customers];