Wednesday, December 18, 2024

SQL CREATE OR REPLACE VIEW Keyword

 In SQL, the CREATE OR REPLACE VIEW statement is used to either create a new view or replace an existing view if one with the same name already exists. A view in SQL is essentially a stored query that can be treated as a table. It simplifies complex queries by encapsulating them under a name.

Syntax:

CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
  • CREATE OR REPLACE: If a view already exists with the specified name, it is replaced by the new definition. If the view does not exist, it is created.
  • view_name: The name you want to give to the view.
  • SELECT ...: The query that defines the view, selecting columns and data from one or more tables.

Example:

CREATE OR REPLACE VIEW employee_details AS
SELECT first_name, last_name, department, salary
FROM employees
WHERE salary > 50000;

In this example:

  • If employee_details exists, it will be replaced by this new definition.
  • The view will return the first name, last name, department, and salary for employees earning more than $50,000.

Notes:

  • If you replace a view, it does not change or drop any of the underlying data; only the definition of the view is updated.
  • The view can be queried like a regular table: SELECT * FROM employee_details;

No comments:

Post a Comment