CIT 111: Introduction to Databases

SQL Views

Benefits of Using Views

View Example

The following code creates a view city_country

CREATE VIEW city_country AS
SELECT ci.name AS city_name, co.name AS country_name
FROM city ci
    JOIN country co
    ON ci.CountryCode = co.Code;

Statements Explained

  1. CREATE VIEW city_country AS
    • Create a new VIEW object and give it the name city_country.
    • The AS statement precedes the query that will be assigned to the VIEW
  2. SELECT ci.name AS city_name, co.name AS country_name
    • Only the columns defined in the SELECT statement will be available to the VIEW
    • It is a good idea to provide column alias in the select because the VIEW will not have access to the underlying table structure.
  3. FROM city ci
        JOIN country co
        ON ci.CountryCode = co.Code;
    • The JOIN statement of the SELECT.

Using the New View

Once you have created a VIEW, you can run SQL statements using the VIEW as if it were a table. Screen capture of view used in select statement.

Creating views that can be used with and UPDATE statement

If you use any of the following statements in your view, you will NOT be able to use the view in an UPDATE statement. The view will be read-only

Useful Links: