Rana Maninder Singh
Lesson 9 of 11SQL & DBMS (MySQL)

CTE & Views

Lesson opener

In one line: What a VIEW is and when to use it (vs writing the same SELECT every time).

Why it matters: Building views on empty tables gives you empty views - and you waste time debugging logic that was fine all along.

Before this lesson: Sub-queries

Before you start

ResourceLink
PreviousSub-queries
NextWindow functions
Lab data/data/customers.csv, /data/sales.csv


What you will learn

  • What a VIEW is and when to use it (vs writing the same SELECT every time)
  • How to create, change, and remove views in MySQL
  • Views without joins, with one join, with multiple joins, and with aggregates
Types of databases
Types of databases

What is a VIEW?

A VIEW is a saved SELECT statement with a name. When you query the view, the database runs that SELECT and shows you the result.

IdeaPlain English
Not a copy of dataThe view does not store rows like a table (usually). It stores the recipe (the query).
Looks like a tableYou can SELECT * FROM view_name like any table.
ReusableReport writers, Power BI, and teammates use the same logic without copying SQL.
Simpler & saferHide columns you do not want shared (e.g. hide internal IDs, show only summary columns).

Analogy: A view is like a saved filter/report in Excel — the source data stays in the tables; the view is how you prefer to look at it.

VIEW vs CTE (WITH):

VIEWCTE (WITH)
Lives in databaseYes — until you DROP itNo — only for that one query
Reuse tomorrowYesNo
Good forDashboards, Power BI, standard reportsOne long query, easier to read once

Deep dive on joins and aggregates first: Joins, Aggregate functions.


Lab tables (reminder)

This module uses customers and sales (same as earlier SQL modules). If needed:

[Sanity-check lab data loaded]

WHY: Building views on empty tables gives you empty views — and you waste time debugging logic that was fine all along.

WHEN: You open a fresh Workbench session and want to confirm imports landed before creating views.

USE learnings_lab;
-- Import from /data/customers.csv and /data/sales.csv (see setup module)
SELECT COUNT(*) FROM customers;
SELECT COUNT(*) FROM sales;

Breaking it down:

Use this when: First thing after setup — quick "are we good?" before CREATE VIEW.


Create, save, edit, and delete a VIEW

Create (save) a new view

[Save high-value customer filter]

WHY: Pasting the same WHERE total_revenue >= 1000 into every report invites drift — one person changes the threshold, others don't.

WHEN: Finance and BI both need "high value customers" with identical rules.

CREATE VIEW vw_high_value_customers AS
SELECT customer_id, segment, total_revenue
FROM customers
WHERE total_revenue >= 1000;

Breaking it down:

Use this when: A filter + column list will be reused across scripts or dashboards.

Query the view (use it like a table)

[Read from a saved view]

WHY: After you save the view, teammates shouldn't need the underlying WHERE — they query by name like any table.

WHEN: You're pulling the high-value list sorted by revenue for a weekly export.

SELECT * FROM vw_high_value_customers
ORDER BY total_revenue DESC;

Breaking it down:

Use this when: The logic is already in the view; you only add sort, filter, or LIMIT on top.

Edit the view definition (MySQL)

MySQL does not use ALTER VIEW ... AS for full rewrites in beginner workflows. Replace the definition:

[Update view definition in place]

WHY: Renaming and recreating views breaks downstream reports — CREATE OR REPLACE keeps the same name with new columns or rules.

WHEN: Product asks to add tenure_months to the high-value customer view without changing the view name in Power BI.

CREATE OR REPLACE VIEW vw_high_value_customers AS
SELECT customer_id, segment, total_revenue, tenure_months
FROM customers
WHERE total_revenue >= 1000;

Breaking it down:

Use this when: View logic or columns change but the view name stays wired into BI tools.

Run SELECT * again — you will see the new column. Same name, updated logic.

See what is inside a view

[Inspect stored view SQL]

WHY: SELECT * shows data, not the recipe — when results look wrong you need the actual definition someone saved.

WHEN: A view returns unexpected rows and you need to copy the exact SQL for code review.

SHOW CREATE VIEW vw_high_value_customers;

Breaking it down:

Use this when: Debugging "why is this row in/out?" — read the saved filter first.

List views in your database

[List all views in the database]

WHY: SHOW TABLES mixes tables and views — you want only saved queries to avoid dropping the wrong object.

WHEN: You're cleaning up old lab views before a demo.

SHOW FULL TABLES WHERE Table_type = 'VIEW';

Breaking it down:

Use this when: Inventorying what's reusable vs base tables in learnings_lab.

Remove a view

[Drop a view safely]

WHY: Orphan views confuse the next person — and CREATE VIEW fails if the name already exists with different logic.

WHEN: You're retiring a practice view before recreating it with a cleaner definition.

DROP VIEW IF EXISTS vw_high_value_customers;

Breaking it down:

Use this when: Resetting lab objects or renaming view workflows from scratch.


Example 1 — VIEW without a JOIN (one table only)

Goal: Everyone who is not churned — simple filter, no joins.

[Active customers view — no join]

WHY: Every analyst rewriting WHERE churned = 0 risks someone forgetting it and inflating active counts.

WHEN: CRM sync and weekly active-customer reports should share one definition of "active."

CREATE OR REPLACE VIEW vw_active_customers AS
SELECT
  customer_id,
  segment,
  total_orders,
  total_revenue
FROM customers
WHERE churned = 0;

Breaking it down:

Use this when: The saved logic is a filter on one table — simplest view pattern.

[Aggregate on top of a view]

WHY: The view gives you filtered rows; grouping still happens in the query that reads it — separation of "who is active" vs "count by segment."

WHEN: Marketing wants active headcount per segment without touching base table filters.

-- Use the view
SELECT segment, COUNT(*) AS active_count
FROM vw_active_customers
GROUP BY segment;

Breaking it down:

Use this when: Base filter lives in the view; report-specific aggregation stays in the SELECT.

What you learn: A view can be as simple as SELECT ... FROM one_table WHERE ....


Example 2 — VIEW with aggregates, still no JOIN

Goal: Revenue by segment — summary on customers only (column total_revenue already exists per customer).

[Segment summary view — aggregates, no join]

WHY: Segment rollups get copy-pasted with slightly different GROUP BY — one view standardizes the grain.

WHEN: Exec summary and Power BI both need segment revenue, count, and average monthly spend from customer master only.

CREATE OR REPLACE VIEW vw_segment_summary AS
SELECT
  segment,
  COUNT(*) AS customer_count,
  SUM(total_revenue) AS segment_revenue,
  AVG(monthly_spend) AS avg_monthly_spend
FROM customers
GROUP BY segment;

Breaking it down:

Use this when: Summary grain is segment and all columns live on one table.

[Sort segment summary from view]

WHY: After the view exists, consumers only need sort — not the full GROUP BY every time.

WHEN: You're building a "segments ranked by revenue" slide from the saved summary.

SELECT * FROM vw_segment_summary ORDER BY segment_revenue DESC;

Breaking it down:

Use this when: The view is your dataset; ORDER BY is report-specific.

What you learn: GROUP BY and SUM / AVG / COUNT inside a view are normal. The view stores the aggregated result shape, not raw order lines.


Example 3 — VIEW with one JOIN (no aggregate)

Goal: Each order with the customer's segment — detail rows, not summed yet.

[Order lines with segment — detail view]

WHY: Joining sales to customers in every ad-hoc query burns time and invites wrong join keys.

WHEN: Analysts filter orders by segment daily but shouldn't re-write the customer join each time.

CREATE OR REPLACE VIEW vw_sales_with_segment AS
SELECT
  s.order_id,
  s.customer_id,
  c.segment,
  s.month,
  s.revenue,
  s.channel,
  s.product_category
FROM sales s
INNER JOIN customers c ON s.customer_id = c.customer_id

Breaking it down:

Use this when: You want denormalized order rows for filtering, not summing yet.

[Filter Gold orders from detail view]

WHY: Segment filter on the view is trivial — no join syntax for the report writer.

WHEN: Gold segment deep-dive on recent order lines for account review.

SELECT * FROM vw_sales_with_segment
WHERE segment = 'Gold'
LIMIT 10;

Breaking it down:

Use this when: Join is hidden; users only write WHERE on friendly column names.

What you learn: Join logic lives inside the view. Users only write SELECT ... FROM vw_sales_with_segment WHERE ....


Example 4 — VIEW with one JOIN + aggregates

Goal: Revenue by segment and month — classic reporting shape (also good for Power BI).

[Segment × month revenue view]

WHY: Month-over-month by segment is the bread-and-butter reporting shape — saving it prevents inconsistent GROUP BY columns.

WHEN: Power BI connects to one table for segment monthly revenue trend.

CREATE OR REPLACE VIEW vw_segment_month_revenue AS
SELECT
  c.segment,
  s.month,
  COUNT(s.order_id) AS order_count,
  SUM(s.revenue) AS revenue
FROM customers c
INNER JOIN sales s ON c.customer_id = s.customer_id
GROUP BY c.segment, s.month;

Breaking it down:

Use this when: BI tools need a star-friendly fact table at segment-month grain.

[Chronological segment-month export]

WHY: Default view order isn't guaranteed — explicit sort for time-series exports.

WHEN: You're CSV-exporting segment-month revenue for an Excel chart.

SELECT * FROM vw_segment_month_revenue
ORDER BY month, segment;

Breaking it down:

Use this when: Human-readable trend tables from the aggregated view.

What you learn: Join + GROUP BY in one saved object. This is the pattern many BI tools connect to.


Example 5 — VIEW with multiple joins (and aggregates)

Goal: Revenue by segment, sales channel, and product category — three dimensions from two tables (customer attributes + order attributes).

[Segment × channel × category rollup]

WHY: Three-way breakdowns mean long GROUP BY lists — one wrong column and channel vs category swaps in the deck.

WHEN: Merchandising wants revenue sliced by segment, channel, and product category in one reusable dataset.

CREATE OR REPLACE VIEW vw_segment_channel_category AS
SELECT
  c.segment,
  s.channel,
  s.product_category,
  COUNT(s.order_id) AS orders,
  SUM(s.revenue) AS revenue
FROM customers c
INNER JOIN sales s ON c.customer_id = s.customer_id
GROUP BY c.segment, s.channel, s.product_category;

Breaking it down:

Use this when: Multi-dimensional reporting from customers + sales without a third products table yet.

[Web channel slice from multi-dim view]

WHY: Channel-specific cuts shouldn't require reopening the join + GROUP BY — filter the view.

WHEN: E-commerce lead wants web revenue by segment and category ranked by dollars.

-- Filter on the view — no need to rewrite the join
SELECT *
FROM vw_segment_channel_category
WHERE channel = 'web'
ORDER BY revenue DESC;

Breaking it down:

Use this when: Standard rollup lives in the view; slices are just WHERE clauses.

What you learn: "Multiple joins" often means many columns from joined tables + GROUP BY on those columns. Here we use one JOIN but three grouping columns from both tables.

If you later add a products table, the same pattern extends:

[Future three-table join pattern]

WHY: When products arrives, the view pattern stays the same — add another JOIN line, don't rethink the approach.

WHEN: You're planning schema growth and want a commented template in the repo.

-- Pattern (when you have a products table):
-- FROM sales s
-- JOIN customers c ON ...
-- JOIN products p ON s.product_id = p.product_id

Breaking it down:

Use this when: Documenting next-step schema without running incomplete SQL.


Example 6 — VIEW with LEFT JOIN (include customers with zero orders)

Goal: Every customer, even if they have no rows in sales.

[Customer order counts — include zeros]

WHY: INNER JOIN in a view would hide zero-order customers from every downstream report forever.

WHEN: Retention dashboard needs order count and sales revenue per customer, including never-bought accounts.

CREATE OR REPLACE VIEW vw_customer_order_counts AS
SELECT
  c.customer_id,
  c.segment,
  COUNT(s.order_id) AS order_count,
  COALESCE(SUM(s.revenue), 0) AS total_sales_revenue
FROM customers c
LEFT JOIN sales s ON c.customer_id = s.customer_id
GROUP BY c.customer_id, c.segment;

Breaking it down:

Use this when: The view must encode "all customers" semantics for every consumer.

[Find customers who never ordered]

WHY: Zero-order filter is one line on the view — no one forgets LEFT JOIN in their personal script.

WHEN: Win-back campaign needs a list of accounts with order_count = 0.

SELECT * FROM vw_customer_order_counts
WHERE order_count = 0;

Breaking it down:

Use this when: Inactive / never-purchased lists from a view that already handles LEFT JOIN correctly.

What you learn: Join type (LEFT vs INNER) belongs in the view definition so report users do not forget it.


CTE (WITH) — readable one-off queries

Use a CTE when you need clarity inside a single script and do not need the logic saved in the database.

[CTE for segment average customer sales]

WHY: Nested subqueries in FROM work, but WITH rev AS (...) reads top-to-bottom like steps in a recipe.

WHEN: One-off analysis: average per-customer sales total by segment — not worth a permanent view yet.

WITH rev AS (
  SELECT customer_id, SUM(revenue) AS total
  FROM sales
  GROUP BY customer_id
)
SELECT c.segment, AVG(r.total) AS avg_customer_sales
FROM customers c
JOIN rev r ON c.customer_id = r.customer_id
GROUP BY c.segment;

Breaking it down:

Use this when: One script, multiple logical steps, readability beats saving a view.

Tip: If you run the same CTE every day, turn it into a VIEW.


Views and Power BI

Connect Power BI to MySQL and pick the view as a table — it behaves like a pre-built dataset. See SQL + Power BI.


Common mistakes

MistakeFix
View name already existsUse CREATE OR REPLACE VIEW or DROP VIEW first
SELECT from view is slowAdd indexes on base table join/filter columns
Expect to INSERT into any viewSimple views sometimes allow it; aggregated views are read-only
Duplicate column names in SELECTAlias columns: c.segment AS customer_segment

Essential commands

Command / actionWhat it does
CREATE VIEW name AS SELECT ...Save a new view.
CREATE OR REPLACE VIEW name AS ...Create or update view definition (edit).
SELECT * FROM view_name;Query a view like a table.
SHOW CREATE VIEW view_name;See the stored SQL.
SHOW FULL TABLES WHERE Table_type = 'VIEW';List all views.
DROP VIEW IF EXISTS view_name;Delete a view.
WITH name AS (SELECT ...) SELECT ...CTE — temporary, one query only.

Practice

Before each query, name the three SQL beats — Source → Pattern → Result (SQL translation of Input → Logic → Output — see sql2). For views/CTEs, Source is the base table(s); Pattern is CREATE VIEW / WITH … AS; Result is the saved or one-off shape you will query next.

Do this now:

  1. Create vw_active_customers (no join) — worked model below.
  2. Create vw_segment_month_revenue (join + aggregates).
  3. Run SHOW CREATE VIEW on one of them.
  4. Change a view with CREATE OR REPLACE (add one column).
  5. Write one CTE report, then optional: convert it to a view.
  6. Save all scripts as 09_cte_view.sql.

Example framing for task 1:

-- Source: customers (customer_id, segment, total_orders, total_revenue, churned)
-- Pattern: CREATE OR REPLACE VIEW (filter only; no JOIN)
-- Result: reusable active-customer rows (churned = 0) queryable like a table

CREATE OR REPLACE VIEW vw_active_customers AS
SELECT
  customer_id,
  segment,
  total_orders,
  total_revenue
FROM customers
WHERE churned = 0;

Framing prompts for the harder tasks (put blank comments in 09_cte_view.sql and fill them before each statement):

  1. Source: ___

Pattern: ___

Result: ___

  1. Source: ___

Pattern: ___

Result: ___

  1. Source: ___

Pattern: ___

Result: ___

  1. Source: ___

Pattern: ___

Result: ___

Checklist

  • [ ] I can explain what a VIEW is (saved SELECT, not a data copy)
  • [ ] I created a view without a join
  • [ ] I created a view with a join
  • [ ] I created a view with GROUP BY / aggregates
  • [ ] I used CREATE OR REPLACE to edit a view
  • [ ] I queried a view with a simple WHERE / ORDER BY
  • [ ] I know when to use a VIEW vs a CTE