Coding Bootcamp: Database Views

Database Views

Database View

Advantages of a database View

Advantages of a database View

Disadvantages of a database View

SQL CREATE VIEW Statement

Syntax

CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

SQL CREATE VIEW Examples 1/6

SQL CREATE VIEW Examples 2/6

SQL CREATE VIEW Examples 3/6

SQL CREATE VIEW Examples 4/6

create view V1 (prod, month, sum_amount) as                                    
select prod, month, sum(amount)
from sales
where year=2016
group by prod, month

create view V2(prod, sum_amount) as                            
select prod, sum(amount)
from sales
where year=2016
group by prod

select V1.prod, V1.month, V1.sum_amount/V2.sum_amount
from V1, V2
where V1.prod=V2.prod

SQL CREATE VIEW Examples 5/6

SQL CREATE VIEW Examples 6/6

CREATE VIEW V1 (cust, NYamount) AS
SELECT cust, sum(amount) 
FROM Sales
WHERE state=‘NY’ 
GROUP BY cust
CREATE VIEW V2 (cust, CAamount) AS
SELECT cust, sum(amount) 
FROM Sales
WHERE state=‘CA’ 
GROUP BY cust
CREATE VIEW V3 (cust, NJamount) AS
SELECT cust, sum(amount) 
FROM Sales
WHERE state=‘NJ’ 
GROUP BY cust
SELECT V1.cust, NYamount, 
       CAamount, NJamount 
FROM V1, V2, V3
WHERE V1.cust=V2.cust AND V2.cust=V3.cust

SQL Updating a View 1/2

To update a view, we use the following syntax:

CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

SQL Updating a View 2/2

SQL Dropping a View

Exercises

Exercise 1

Exercise 2

Remove the “last_name” column from the “actor_sample” view

Exercise 3

Exercise 4

Exercise 5


Creative Commons Licence
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.