In SQL, views can be updated, but not all views are updatable. The update views must meet certain criteria, including that the view must not contain any of the following:

  1. Aggregate functions (such as SUM, AVG, and MAX)
  2. GROUP BY clauses
  3. DISTINCT keyword
  4. UNION or UNION ALL operators
  5. Subqueries in the SELECT list or the WHERE clause
  6. Joins involving more than one table

If a view meets these criteria, it can be updated using the standard UPDATE, INSERT, and DELETE statements. When an update is made to the view, the underlying data in the tables that the view is based on is also updated.

Here are some examples of updating views in SQL:

  1. Create a view that displays the employees in a company’s sales department:
CREATE VIEW sales_employees AS
SELECT employee_id, first_name, last_name, job_title
FROM employees
WHERE department_id = 50;
  1. Update the job title of an employee in the sales department:
UPDATE sales_employees
SET job_title = 'Senior Sales Associate'
WHERE employee_id = 101;
  1. Insert a new employee into the sales department:
INSERT INTO sales_employees (employee_id, first_name, last_name, job_title)
VALUES (120, 'Sara', 'Johnson', 'Sales Associate');
  1. Delete an employee from the sales department:
DELETE FROM sales_employees
WHERE employee_id = 102;

Note that in each of these examples, the changes made to the view are reflected in the underlying tables. So if we were to query the employees table after executing these statements, we would see that the changes have been made there as well.Learn SQL Now: Learn From Scratch to Advanced

Leave a Reply

Your email address will not be published. Required fields are marked *