SQL - Views

Fatima Alam - Dec 1 '23 - - Dev Community

Creating Views

CREATE VIEW CustomerView AS
SELECT CustomerID, Name, Address
FROM Customers;
Enter fullscreen mode Exit fullscreen mode

Querying Views

After a view has been created, it can be used in the FROM clause of a SELECT statement, as if it’s an actual table.

SELECT *
FROM CustomerView;
Enter fullscreen mode Exit fullscreen mode

Updating Views

CREATE OR REPLACE VIEW CustomerView AS
SELECT CustomerID, Name, Address, Phone
FROM Customers;
Enter fullscreen mode Exit fullscreen mode

Dropping Views

To delete a view, use the DROP VIEW statement:

DROP VIEW CustomerView;
Enter fullscreen mode Exit fullscreen mode

If Exists

DROP VIEW IF EXISTS view_name;
Enter fullscreen mode Exit fullscreen mode

Restrictions
There are a few restrictions to bear in mind when working with views. SQL views can’t:

1. Contain a ORDER BY clause in the view definition
2. Be indexed
3. Have triggers or default values.

Modifying Data through VIEW

In some cases, you can modify the data of the underlying tables via a VIEW.

Syntax:

UPDATE view_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Enter fullscreen mode Exit fullscreen mode
UPDATE customer_view
SET country = 'USA'
WHERE customer_name = 'John Doe';
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .