loading

SQL Views

SQL CREATE VIEW Statement

A view in SQL is a virtual table created from a SQL statement’s result set.

A view has rows and columns, exactly like a table in the real world. A view contains fields that come from one or more actual database tables.

A view can have SQL statements and functions added to it so that the data is displayed as though it is from a single table.

CREATE VIEW Syntax

				
					CREATE TABLE Orders (
    ID int NOT NULL,
    OrderNumber int NOT NULL,
    OrderDate date DEFAULT GETDATE()
);
				
			

Note: Current data is always displayed in a view! Each time a user requests a view, the database engine recreates it.

SQL CREATE VIEW Examples

A view displaying all of the Brazilian clients is created using the SQL below:

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 creates a view that selects every product in 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 query the view above as follows:

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 removes a view.

SQL DROP VIEW Syntax

				
					DROP VIEW view_name;
				
			

The following SQL drops the “Brazil Customers” view:

Example

				
					DROP VIEW [Brazil Customers];
				
			
Share this Doc

SQL Views

Or copy link

Explore Topic