Chapter 16: Views

A VIEW is like a saved query that you can treat almost exactly like a real table. You write a complex SELECT once, give it a name, and then you can query that view forever — just like querying a normal table.

Why are views so useful?

  • Hide complexity from users (show only the columns they need)
  • Simplify repeated reports (e.g., monthly sales summary)
  • Improve security (users can query the view but not the underlying tables)
  • Make code cleaner and more maintainable
  • Can sometimes be updatable (you can INSERT/UPDATE/DELETE through the view!)

Today we’ll cover the three main things you need to know about views:

  1. CREATE VIEW – Making a new view
  2. Updatable views – When you can modify data through a view
  3. DROP VIEW – Deleting a view

We’ll use our bookshop database with the books and authors tables.

1. CREATE VIEW – Creating Your First View

Syntax:

SQL

Important: A view does not store data — it’s just a saved query. Every time you query the view, the underlying SELECT runs fresh.

Example 1 – Simple view: All books with author names

SQL

Now you can query it like a table:

SQL

Example 2 – View with aggregation: Books per author summary

SQL

Usage:

SQL

Example 3 – View with CASE and functions (fancy catalog)

SQL

Best Practice Tips for Creating Views:

  • Use clear, descriptive names: vw_book_sales_summary, vw_active_customers
  • Prefix with vw_ or view_ so everyone knows it’s a view
  • Add OR REPLACE to update existing view:
    SQL

2. Updatable Views – When You Can Modify Data Through a View

Some views allow you to INSERT, UPDATE, or DELETE data — and those changes go to the underlying table(s).

Rules for a view to be updatable (most databases):

  • It must be based on one single table (no JOINs, no aggregations)
  • No DISTINCT, GROUP BY, HAVING, UNION, subqueries in SELECT
  • No calculated columns (e.g., price * 1.18)
  • Must include the primary key of the underlying table

Example – Updatable view: Simple view on books table

SQL

Now you can update through the view:

SQL

Non-updatable view example (will fail):

SQL
SQL

Pro Tip: Even if a view is updatable, many teams avoid using updatable views in production — they can be confusing. Use them mainly for SELECT-only purposes.

3. DROP VIEW – Deleting a View

Very simple — and safe! Dropping a view does NOT delete the underlying data — just the saved query.

Syntax:

SQL

Safe version:

SQL

Example:

SQL

What happens to queries that use the view? They will fail with “View does not exist” — so be careful in production!

Full Realistic Workflow Example

SQL

You may also like...

Leave a Reply

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