TutorialsArena

SQL CREATE OR REPLACE VIEW Statement

The CREATE OR REPLACE VIEW statement in SQL is used to either create a new view or update an existing one. Views are virtual tables based on the result set of an SQL query. They don't store data themselves; they dynamically generate their data when queried.



CREATE OR REPLACE VIEW: Definition and Usage

This command is helpful for modifying views without having to drop and recreate them. If the view already exists, its definition is replaced with the new one; otherwise, a new view is created. This simplifies view management, especially when you need to adjust the underlying query of a view.

Syntax

Syntax

CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
      

Example: Updating a View

This example adds the "City" column to an existing view named "Brazil Customers". This assumes that the "Customers" table exists and has the columns mentioned.

Syntax

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

The "Brazil Customers" view is updated. If it didn't exist, it would be created. Now, it includes the CustomerName, ContactName, and City for customers from Brazil.

Querying the Updated View

After updating the view, you can query it as usual:

Syntax

SELECT * FROM [Brazil Customers];
      
Output

CustomerName | ContactName | City
---------------------------------
(Data for Brazilian customers from the Customers table)
      

**Note:** The example output assumes that a table named `Customers` exists with columns `CustomerName`, `ContactName`, `City`, and `Country`, and that some customers are from Brazil. The `(...)` indicates that the actual output will show the data for those customers. If no customers are from Brazil, the output will be an empty dataset.