SQL / MySQL Intermediate Relational Design · 8 min read

CREATE VIEW for a Roster

Lesson 19 of 33 in the SQL / MySQL learning path.

How do I save a SELECT as a view?

A view is a named SELECT. CREATE VIEW stores the statement, and later queries read the view as if it were a table. MySQL runs the saved SELECT at read time, so the roster picks up a new enrollment without a second copy of the data. This roster joins users, lessons, and enrollments, and it leaves out cancelled rows.

The view in this lesson is created with SQL SECURITY INVOKER. MySQL then checks the caller against the underlying tables. A join view like this one is not insertable, so the roster is for reading and for aggregates. Change the definition with CREATE OR REPLACE VIEW when the SELECT needs a new column.

Syntax & Parameters

Syntax
CREATE OR REPLACE SQL SECURITY INVOKER VIEW roster AS
SELECT
  e.id AS enrollment_id,
  u.name AS student_name,
  l.title AS lesson_title,
  e.status AS enrollment_status
FROM enrollments AS e
INNER JOIN users AS u ON u.id = e.user_id
INNER JOIN lessons AS l ON l.id = e.lesson_id
WHERE e.status <> 'cancelled';

Example

queries.sql
CREATE DATABASE IF NOT EXISTS school
  CHARACTER SET utf8mb4
  COLLATE utf8mb4_unicode_ci;

USE school;

SET NAMES utf8mb4;

DROP VIEW IF EXISTS roster;
DROP TABLE IF EXISTS enrollments;
DROP TABLE IF EXISTS lessons;
DROP TABLE IF EXISTS users;

CREATE TABLE users (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  name VARCHAR(120) NOT NULL,
  email VARCHAR(254) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uq_users_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE lessons (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  title VARCHAR(160) NOT NULL,
  track VARCHAR(80) NOT NULL,
  published_at DATETIME NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE enrollments (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  lesson_id INT UNSIGNED NOT NULL,
  user_id INT UNSIGNED NOT NULL,
  status VARCHAR(20) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uq_enrollments_lesson_user (lesson_id, user_id),
  CONSTRAINT fk_enrollments_lesson FOREIGN KEY (lesson_id) REFERENCES lessons (id),
  CONSTRAINT fk_enrollments_user FOREIGN KEY (user_id) REFERENCES users (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO users (name, email, created_at) VALUES
  ('Ada Lovelace', 'ada@school.test', '2026-03-01 09:00:00'),
  ('Grace Hopper', 'grace@school.test', '2026-03-14 11:00:00'),
  ('Alan Turing', 'alan@school.test', '2026-03-18 08:30:00');

INSERT INTO lessons (title, track, published_at) VALUES
  ('Algebra I', 'math', '2026-03-02 09:00:00'),
  ('SQL Basics', 'data', '2026-03-10 09:00:00'),
  ('Studio Draft', 'art', NULL);

INSERT INTO enrollments (lesson_id, user_id, status) VALUES
  (1, 1, 'confirmed'),
  (1, 2, 'waitlist'),
  (1, 3, 'cancelled'),
  (2, 1, 'confirmed');

CREATE OR REPLACE SQL SECURITY INVOKER VIEW roster AS
SELECT
  e.id AS enrollment_id,
  u.name AS student_name,
  u.email AS student_email,
  l.title AS lesson_title,
  l.track AS lesson_track,
  e.status AS enrollment_status
FROM enrollments AS e
INNER JOIN users AS u ON u.id = e.user_id
INNER JOIN lessons AS l ON l.id = e.lesson_id
WHERE e.status <> 'cancelled';

SELECT
  enrollment_id,
  student_name,
  student_email,
  lesson_title,
  enrollment_status
FROM roster
ORDER BY lesson_title, student_name;

SELECT lesson_title, COUNT(*) AS confirmed_seats
FROM roster
WHERE enrollment_status = 'confirmed'
GROUP BY lesson_title
ORDER BY lesson_title;

SHOW CREATE VIEW roster;

Expected Output

enrollment_id | student_name | student_email    | lesson_title | enrollment_status
1             | Ada Lovelace | ada@school.test  | Algebra I    | confirmed
2             | Grace Hopper | grace@school.test| Algebra I    | waitlist
4             | Ada Lovelace | ada@school.test  | SQL Basics   | confirmed
3 rows in set

lesson_title | confirmed_seats
Algebra I    | 1
SQL Basics   | 1
2 rows in set

SHOW CREATE VIEW roster prints the SELECT and SQL SECURITY INVOKER.
Alan Turing is cancelled and is not in the view.

Line-by-Line Walkthrough

  1. The script builds users, lessons, and enrollments, including Alan Turing as a cancelled Algebra I row.
  2. CREATE OR REPLACE VIEW roster saves the join. SQL SECURITY INVOKER tells MySQL to check the caller, not only the account that created the view.
  3. The SELECT behind the view joins enrollments to users and lessons and drops cancelled rows inside the view definition.
  4. The column list uses explicit names, so a later query reads student_name and lesson_title rather than the underlying column names.
  5. student_email is part of the view, which means anyone who can read the view is meant to see that address. Leave it out when the screen does not need it.
  6. The first query against roster returns Ada and Grace for Algebra I, and Ada for SQL Basics. Alan is absent because the view filters him.
  7. The count query treats the view like a table. WHERE enrollment_status = 'confirmed' runs on top of the view, so waitlist rows are not counted.
  8. Studio Draft has no enrollment, so it does not appear. A view does not invent rows the SELECT never returned.
  9. SHOW CREATE VIEW prints the saved statement, including SQL SECURITY INVOKER, so you can review the definition later.

Common Pitfalls & Security

A view feels like a table and still runs a query. SQL SECURITY DEFINER, which is the MySQL default when you omit the clause, runs that query with the view owner privileges and can expose emails to an account that cannot read users directly.

  • DEFINER security on a roster that includes student_email lets a restricted account see addresses through the view. INVOKER checks the caller against users, lessons, and enrollments.
  • This join is not insertable. INSERT INTO roster fails. Write to the base tables, then read the view.
  • The cancelled filter is inside the view. A report that must show cancellations needs a different view or a direct query.
  • CREATE OR REPLACE VIEW can change columns that application SQL already names. Review those queries when you replace the definition.
  • A view is not a cache. A heavy join still runs on every read. Start from the base tables with a tighter WHERE when one screen needs a small slice.

Best Practices & Modern Standards

Create a view for a SELECT that several reports share, such as this roster join. List the columns and their aliases yourself so a later ALTER TABLE does not silently change the shape. Use SQL SECURITY INVOKER unless you have a reviewed reason to run the SELECT as the owner.

Keep cancelled rows out of the roster view when every caller agrees they are not active seats. Build a second view when another screen needs them. Query the view with an ordinary SELECT, including aggregates, and keep writes on users, lessons, and enrollments.

Real-World Use

The attendance desk and the Friday enrollment count both need the same active roster: student, email, lesson, and status, without cancelled seats. The registrar saves that join as roster. Both reports select from the view, and a new confirmed enrollment shows up the next time either report runs.

Frequently Asked Questions

Does a view store a second copy of the enrollment rows?

No. MySQL stores the SELECT and runs it when you query the view. New rows in enrollments appear in roster on the next read.

Can I INSERT into the roster view?

No. A view with joins is not insertable. Insert the user, the lesson, and the enrollment into their tables, then select the view.

Who is authorized when the view says SQL SECURITY INVOKER?

The account that runs the SELECT must be allowed to read the underlying users, lessons, and enrollments tables. The view does not lend the owner privileges.

How do I change the saved SELECT?

Run CREATE OR REPLACE VIEW with the new statement. The base tables stay as they are. Queries that used a removed column name need to change with the view.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…