SQL Server - CREATE OR ALTER VIEW Keyword
The SQL Server (Transact-SQL) CREATE OR ALTER VIEW statement is used to update a SQL Server VIEW. A SQL Server VIEW is a virtual table created based on the SQL Server statement. A view contains rows and columns just like a normal table. All SQL Server functions, WHERE, HAVING and JOINs statements can be used to create a SQL Server VIEW.
Syntax
The syntax for using CREATE OR ALTER VIEW statement in SQL Server (Transact-SQL) is given below:
CREATE OR ALTER VIEW view_name AS SELECT column1, column2, column3, ... FROM table_name WHERE condition(s);
Example:
Consider a database table called Employee with the following records:
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
2 | Marry | New York | 24 | 2750 |
3 | Jo | Paris | 27 | 2800 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
6 | Huang | Beijing | 28 | 2800 |
The below mentioned SQL Server statement is used to create a view on Employee table which contains all records of employee whose salary is greater than 2800.
CREATE VIEW Employee_Salary_GT_2800 AS SELECT * FROM Employee WHERE Salary > 2800;
After creating the VIEW, it can be used as mentioned below:
SELECT * FROM Employee_Salary_GT_2800;
This will produce the result as shown below:
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
Here, the CREATE OR ALTER VIEW statement can be used to update the above view. The mentioned below statement is used to update the above view which contains all records of employee whose salary is greater than 2800 and age is greater than 25.
CREATE OR ALTER VIEW Employee_Salary_GT_2800 AS SELECT * FROM Employee WHERE Salary > 2800 AND AGE > 25;
After updating the VIEW, the following query can be used to see its content:
SELECT * FROM Employee_Salary_GT_2800;
This will produce the result as shown below:
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
❮ SQL Server Keywords