CIS 4720 · Chapter 5 · lab7, lab7b, and Project 7 · Lab guide

Chapter 5 in practice: building students_db with keys, joins, and views

The Chapter 5 review explains the ideas. This page shows what those ideas look like when you actually type them into MySQL, using the same students_db database we built across lab7, lab7b, and Project 7. Every section has runnable SQL, the output you should see, and the error you get when something goes wrong. The next assignment builds directly on this page, so work through the examples, not just the headings.

Before any SQL

The lab workflow, and why it is built this way

The lab PCs are wiped every night. Your database, your SQLTools connection, your GitHub sign in, and anything on the desktop are gone by morning. Your .sql file is the only thing that survives, and only if it lives somewhere other than the PC.

That single fact explains every setup step in the last three assignments. The file is the real product of your work. The database is something you rebuild from the file each time you sit down.

Where each piece of your work lives, and whether it survives the night.
ThingWhere it livesSurvives?
Your .sql fileA folder inside OneDrive, synced by the OneDrive appYes
Your .sql file on GitHubA public repository with a web addressYes, and it is what you hand in
The students_db databaseThe MySQL server on the lab PCNo, rebuild it from the file
SQLTools connection.vscode/settings.json in the folder you openedOnly if the folder is on OneDrive
VS Code GitHub sign in, Git settingsThe lab PCNo

The startup routine, every time

  1. Sign in to the OneDrive app (the cloud icon in the system tray), not the website. Make folders in File Explorer under OneDrive so the app pushes them up. Folders made in the browser may take a long time to appear on the PC.
  2. Create the empty database at the command prompt, before opening VS Code.
  3. Open the folder (not just the file) in VS Code and add the SQLTools connection: server localhost, port 3306, database students_db, user root.
  4. Run the file once to rebuild every table, row, and view.
C:\> mysql -u root -p
Enter password:            -- nothing appears as you type, that is normal

mysql> CREATE DATABASE students_db;
mysql> SHOW DATABASES;
mysql> EXIT;

If Windows says 'mysql' is not recognized, change into the MySQL program folder first:

cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"
mysql -u root -p

ERROR 1049 (42000): Unknown database 'students_db' is not a VS Code problem and not a problem with your file. It means step 2 did not happen. SQLTools connects to a database that exists; it never creates one for you.

For the tools themselves (VS Code, SQLTools, the MySQL driver) see the SQL lab tools page.

Comments

Comments switch statements off, and label your work

A comment is text MySQL ignores. You use comments for two separate jobs: explaining what a statement does, and turning a statement off without deleting it.

Line comments: two dashes and a space

-- This whole line is ignored.
-- SELECT * FROM STUDENT;      this statement is switched off
SELECT * FROM STUDENT;         -- a comment can also follow a statement
# MySQL also accepts a hash sign, but stick with two dashes, which every database understands

The space after the dashes matters in MySQL. --this with no space is not treated as a comment and gives you a syntax error. Write -- this.

Use the keyboard shortcut. Select any number of lines and press Ctrl + /. VS Code puts -- in front of every selected line. Press it again on the same lines to take them off. This is the method to use for switching off whole sections.

Block comments, and the trap in them

/* Everything between these markers is ignored,
   however many lines it covers.
   SELECT * FROM STUDENT;
*/

Block comments do not nest. MySQL starts ignoring at the first /* and starts reading again at the very next */, whatever sits between them. Here is what goes wrong:

/*                                   -- you meant to switch off everything below
CREATE TABLE STUDENT ( ... );
/* sample rows, added in lab7b */    -- this inner */ ends your outer comment HERE
INSERT INTO STUDENT VALUES (...);    -- so this runs anyway
*/                                   -- leftover marker: ERROR 1064 syntax error near '*/'

Line comments cannot nest wrongly because each line stands on its own. That is why every assignment tells you to use Ctrl + / instead.

Labeling a step: the graded pattern

Your instructor opens one long file with dozens of statements. A heading comment with the step number tells them which statement answers which step, and a comment above each statement says what it is for. Both are graded.

-- =================================================================
-- PROJECT 7 STEP 6. Create the COURSE table
-- =================================================================

-- holds the classes the school offers. course_id is the primary key,
-- so two classes can never share an id and it can never be empty
CREATE TABLE COURSE (
    course_id     INT          NOT NULL,
    course_code   VARCHAR(10)  NOT NULL,
    course_title  VARCHAR(50)  NOT NULL,
    credits       INT,
    dept          VARCHAR(30),
    PRIMARY KEY (course_id)
);

-- confirm course_id shows PRI in the Key column
DESCRIBE COURSE;
A comment that earns the point says why, not just what.
CommentVerdict
-- creates a table called COURSERepeats the SQL back. Does not earn the point.
-- step 6A label, but says nothing about the statement.
-- holds the classes on offer, with course_id as the key so no two classes share an idSays what the table is for and why the key is there. Earns the point.
-- should fail with 1452 because student 99 does not existStates the expected result before you run it. Exactly right for a test statement.

Rebuilding from the file

Run once, read the errors, then comment out

CREATE and INSERT build things. Once built, running them again can only fail. SELECT only reads, so it is safe to run as often as you like.

The starter file students_db_backup.sql is organized in sections: a header, then the CREATE TABLE (Section 2), the INSERT rows (Section 3), the CREATE VIEW (Section 4), and read only checks (Section 5). The first run builds everything:

First run, last two results
students  average_gpa
       5         3.43

Tables_in_students_db  Table_type
STUDENT                BASE TABLE
STUDENT_GPA            VIEW

Run the identical file a second time and you get seven errors. None of them means anything is broken; each one is the database protecting data that already exists:

Second run
ERROR 1050 (42S01): Table 'STUDENT' already exists
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
ERROR 1062 (23000): Duplicate entry '2' for key 'PRIMARY'
ERROR 1062 (23000): Duplicate entry '3' for key 'PRIMARY'
ERROR 1062 (23000): Duplicate entry '4' for key 'PRIMARY'
ERROR 1062 (23000): Duplicate entry '5' for key 'PRIMARY'
ERROR 1050 (42S01): Table 'STUDENT_GPA' already exists
What each code is telling you.
CodeMeaning
1050A table or view with that name already exists. CREATE will not quietly replace something that holds your data.
1062A row with that primary key value is already in the table. The primary key refuses a duplicate.

So select from the first line of Section 2 down to the last line of Section 4, press Ctrl + /, and run again. Zero errors, and Section 5 still returns its results. After commenting, that part of the file looks like this:

-- -- SECTION 2. Create the table
-- CREATE TABLE STUDENT (
--     student_id   INT          NOT NULL,
--     first_name   VARCHAR(30)  NOT NULL,
--     ...
-- );
-- INSERT INTO STUDENT VALUES (1, 'Ana', 'Reyes', ...);

Keep the commented lines. Do not delete them. They are how you rebuild from nothing on a freshly wiped PC: select them, press Ctrl + / again, run, and comment them back out.

The same pattern applies to everything you add

Project 7 adds more one time statements: two CREATE TABLEs, thirteen INSERTs, two CREATE VIEWs, and several statements that are supposed to fail. Once each has run and you have read the result, comment it out so the next run of the file is clean. Leave the SELECTs, DESCRIBEs, and SHOW statements switched on.

You will also see a second approach in real projects. Instead of commenting statements out, scripts are written to be safe to rerun: DROP TABLE IF EXISTS ENROLLMENT; before the CREATE, or CREATE OR REPLACE VIEW instead of CREATE VIEW. That is useful to recognize, but in this class the commenting approach is what is graded, because it shows you understand which statements build and which only read.

Section 5.1

Look at your schema

In MySQL, a schema and a database are the same thing. students_db is the container that holds your tables and views.

-- confirm which schema this connection is pointed at
SELECT DATABASE() AS my_schema;

-- list everything in the schema, and say which are tables and which are views
SHOW FULL TABLES;
Output
my_schema
students_db

Tables_in_students_db  Table_type
STUDENT                BASE TABLE
STUDENT_GPA            VIEW

Plain SHOW TABLES lists views mixed in with tables and gives no way to tell them apart. FULL adds the Table_type column. A base table stores rows; a view stores only a SELECT statement.

More ways to look around

-- every database on this server, including MySQL's own system ones
SHOW DATABASES;

-- switch the current schema without reconnecting
USE students_db;

-- only the views, using the same Table_type column
SHOW FULL TABLES WHERE Table_type = 'VIEW';

-- the same information from the data dictionary, which MySQL calls information_schema
SELECT table_name, table_type
FROM   information_schema.tables
WHERE  table_schema = 'students_db';

That last query reads the data dictionary, the metadata the DBMS keeps about every object. It is the same idea as the system catalog from Chapter 3, and it is where SHOW and DESCRIBE get their answers.

Section 5.2

Read the data types

DESCRIBE shows each column's type, whether it may be NULL, and which column is the key.

-- show the column names, types, and key of the STUDENT table
DESCRIBE STUDENT;
The STUDENT table, and why each type was chosen.
ColumnTypeWhy
student_idintA whole number with no decimal part. Key column shows PRI.
first_namevarchar(30)Text of varying length, up to 30 characters
last_namevarchar(30)Same. This is the one we widen in Section 5.4.
majorvarchar(40)Longer text, because some major names are long
gpadecimal(3,2)Exactly the shape of a grade average, stored exactly
enrolled_ondateA real date the database can sort and compare

Reading DECIMAL(p,s)

The first number is the total digits, the second is how many of them sit after the decimal point. Subtract to get the digits before the point.

Working out the largest value each type can hold.
TypeBefore the pointAfterLargest valueGood for
DECIMAL(3,2)129.99A GPA
DECIMAL(5,2)32999.99A percentage score like 100.00
DECIMAL(7,2)5299999.99A product price (lab7 PRODUCT table)
DECIMAL(10,2)8299999999.99Salaries, invoice totals
-- a GPA of 10.50 needs two digits before the point, which DECIMAL(3,2) does not have
INSERT INTO STUDENT_COPY (student_id, first_name, last_name, gpa)
VALUES (50, 'Too', 'High', 10.50);
-- ERROR 1264 (22003): Out of range value for column 'gpa' at row 1

Choosing a type for a new column

Ask: is it a count, money, a date, or text? Will anyone ever do arithmetic on it?
ValueTypeReason
Course credits (3, 4)INTA whole number count
A letter grade (A, B, C)CHAR(1)Always exactly one character
A term like Fall 2026VARCHAR(15)Short text that varies in length
A course code like CIS4720VARCHAR(10)Has digits, but you never add course codes together
A phone number or zip codeCHAR or VARCHARNever used in arithmetic, and a leading zero must be kept
Tuition owedDECIMAL(8,2)Money must be exact; FLOAT and DOUBLE can drift
Date of birthDATESorting, comparing, and date math all work
A yes or no flagCHAR(1)Store Y or N (MySQL also accepts BOOLEAN, stored as 0 or 1)

Dates go in as text in 'YYYY-MM-DD' form, and MySQL converts them: '2026-08-24'.

Section 5.3

Create a table by copying another one

CREATE TABLE ... AS SELECT builds a new table and fills it in one statement. The new table gets one column for each column the SELECT returns.

-- make a practice copy of STUDENT holding only four columns, so we can
-- change its structure without touching the real table
CREATE TABLE STUDENT_COPY AS
SELECT student_id, first_name, last_name, gpa
FROM   STUDENT;

-- five rows, four columns. major and enrolled_on were not selected, so they were left behind
SELECT * FROM STUDENT_COPY;

-- print the full definition MySQL actually built
SHOW CREATE TABLE STUDENT_COPY;

The copy has no PRIMARY KEY. Read the SHOW CREATE TABLE output and the PRIMARY KEY (student_id) line is missing. Copying this way brings the columns and the rows and leaves keys and indexes behind. In MySQL the column types and NOT NULL settings do carry over; primary keys, foreign keys, unique keys, and AUTO_INCREMENT do not.

Without a key the copy will accept duplicates the real table would refuse:

-- this succeeds on the copy, because nothing stops a second student 1
INSERT INTO STUDENT_COPY VALUES (1, 'Second', 'Ana', 3.00);

-- now there are two rows with student_id 1. Clean it up before moving on
DELETE FROM STUDENT_COPY WHERE first_name = 'Second';

Variations you should be able to write

-- copy only some rows: a WHERE clause filters what gets copied
CREATE TABLE HONOR_ROLL AS
SELECT student_id, first_name, last_name, gpa
FROM   STUDENT
WHERE  gpa >= 3.50;

-- rename columns on the way in: the alias becomes the new column name
CREATE TABLE STUDENT_NAMES AS
SELECT student_id AS id,
       CONCAT(first_name, ' ', last_name) AS full_name
FROM   STUDENT;

-- copy the structure only, with zero rows: no row can satisfy 1 = 0
CREATE TABLE STUDENT_EMPTY AS
SELECT * FROM STUDENT WHERE 1 = 0;

-- MySQL shortcut that copies the structure INCLUDING the primary key, but no rows
CREATE TABLE STUDENT_SHELL LIKE STUDENT;

-- fill a table that already exists: INSERT ... SELECT, not CREATE TABLE AS
INSERT INTO STUDENT_SHELL
SELECT * FROM STUDENT;

Copies are snapshots. STUDENT_COPY is a separate table. Changing a GPA in STUDENT afterward does not change STUDENT_COPY, and the other way round. That is the key difference from a view, which always shows the current data.

Section 5.4

Change a table's structure with ALTER TABLE

ALTER TABLE changes a table that already holds rows: add a column, change a column, drop a column, and add or remove constraints.

-- add a one character honors flag to the end of the copy
ALTER TABLE STUDENT_COPY ADD COLUMN honors CHAR(1);

-- give last names room for 50 characters, repeating NOT NULL so the rule is kept
ALTER TABLE STUDENT_COPY MODIFY COLUMN last_name VARCHAR(50) NOT NULL;

-- put back the primary key that the copy did not inherit
ALTER TABLE STUDENT_COPY ADD PRIMARY KEY (student_id);

-- check the result: honors at the end, last_name is varchar(50), student_id is PRI
DESCRIBE STUDENT_COPY;

Now prove the key works. Write the expected result in the comment above it:

-- should fail with 1062, because student 1 already exists and the key now refuses duplicates
INSERT INTO STUDENT_COPY VALUES (1, 'Duplicate', 'Row', 0.00, NULL);
-- ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

Notice the INSERT supplies five values, because STUDENT_COPY has five columns right now (the four copied ones plus honors). After the next statement it has four again.

-- remove the honors column and everything stored in it; there is no undo
ALTER TABLE STUDENT_COPY DROP COLUMN honors;

MODIFY replaces the whole column definition. It does not adjust one part. If you write MODIFY COLUMN last_name VARCHAR(50) without NOT NULL, you have quietly removed the NOT NULL rule and the column starts accepting empty values. Always write out the full definition you want.

More ALTER TABLE forms

Try these on a throwaway copy, so STUDENT_COPY keeps the four columns the next section expects.

-- a scratch table for experimenting
CREATE TABLE STUDENT_PRACTICE AS SELECT * FROM STUDENT_COPY;

-- add a column with a default, so existing rows get a value instead of NULL
ALTER TABLE STUDENT_PRACTICE ADD COLUMN status VARCHAR(10) NOT NULL DEFAULT 'active';

-- add a column at a specific position instead of at the end (MySQL)
ALTER TABLE STUDENT_PRACTICE ADD COLUMN middle_initial CHAR(1) AFTER first_name;

-- rename a column and keep its type (MySQL 8)
ALTER TABLE STUDENT_PRACTICE RENAME COLUMN middle_initial TO mi;

-- add a rule: a GPA must be between 0 and 4 (enforced in MySQL 8.0.16 and later)
ALTER TABLE STUDENT_PRACTICE ADD CONSTRAINT chk_gpa CHECK (gpa BETWEEN 0 AND 4);

-- the copy has no key yet, so add one, then remove it again
ALTER TABLE STUDENT_PRACTICE ADD PRIMARY KEY (student_id);
ALTER TABLE STUDENT_PRACTICE DROP PRIMARY KEY;

-- rename the whole table
RENAME TABLE STUDENT_PRACTICE TO STUDENT_SCRATCH;

-- remove the scratch table completely when you are done
DROP TABLE STUDENT_SCRATCH;

Why the status column above can be NOT NULL. Adding a NOT NULL column to a table that already has rows needs a value for every existing row. The DEFAULT 'active' supplies one. Without a default, MySQL quietly fills the column with an empty value for its type (an empty string, or 0), and other databases refuse the statement outright. The safe habit is to add it as NULL, fill it with UPDATE, then MODIFY it to NOT NULL.

ALTER TABLE at a glance.
GoalSyntax
Add a columnADD COLUMN name TYPE
Change type or widthMODIFY COLUMN name NEWTYPE [NOT NULL]
Remove a columnDROP COLUMN name
Add a primary keyADD PRIMARY KEY (col)
Add a foreign keyADD CONSTRAINT fk_name FOREIGN KEY (col) REFERENCES PARENT (col)
Remove a foreign keyDROP FOREIGN KEY fk_name
Add a check ruleADD CONSTRAINT chk_name CHECK (condition)

Section 5.5

Change the data: INSERT, UPDATE, DELETE

These change rows, not structure. Run them one at a time with a SELECT between each, so you can watch each one land.

-- add a sixth student to the copy
INSERT INTO STUDENT_COPY VALUES (6, 'Omar', 'Faruqi', 3.10);
SELECT * FROM STUDENT_COPY WHERE student_id = 6;

-- raise Omar's grade average after a grade change
UPDATE STUDENT_COPY SET gpa = 3.35 WHERE student_id = 6;
SELECT * FROM STUDENT_COPY WHERE student_id = 6;

-- remove Omar again so the copy is back to five rows
DELETE FROM STUDENT_COPY WHERE student_id = 6;
SELECT COUNT(*) AS rows_left FROM STUDENT_COPY;
Output, in order
student_id  first_name  last_name  gpa
6           Omar        Faruqi     3.10

student_id  first_name  last_name  gpa
6           Omar        Faruqi     3.35

rows_left
5

Name your columns in INSERT

The short form INSERT INTO T VALUES (...) needs one value per column, in table order. If the table's structure changes, the statement breaks:

-- STUDENT_COPY has four columns, but this supplies five
INSERT INTO STUDENT_COPY VALUES (7, 'Lena', 'Ortiz', 3.20, 'Y');
-- ERROR 1136 (21S01): Column count doesn't match value count at row 1

-- naming the columns works no matter how many the table has; unnamed columns get NULL or their DEFAULT
INSERT INTO STUDENT_COPY (student_id, first_name, last_name)
VALUES (7, 'Lena', 'Ortiz');

-- several rows in one statement
INSERT INTO STUDENT_COPY (student_id, first_name, last_name, gpa) VALUES
  (8, 'Sam',  'Lee',   2.90),
  (9, 'Kira', 'Patel', 3.60);

UPDATE and DELETE patterns

-- change two columns in one row
UPDATE STUDENT_COPY SET first_name = 'Samuel', gpa = 3.05 WHERE student_id = 8;

-- change several rows: everyone below 3.00 gets a 0.10 bump
UPDATE STUDENT_COPY SET gpa = gpa + 0.10 WHERE gpa < 3.00;

-- remove a set of rows by a list of ids
DELETE FROM STUDENT_COPY WHERE student_id IN (7, 8, 9);

The WHERE clause is the whole safety net. Leave it off an UPDATE and every row changes. Leave it off a DELETE and the table is emptied (the table itself stays, with no rows). There is no confirmation and, with MySQL's default autocommit, no undo.

The habit that saves you: write the WHERE as a SELECT first. If the SELECT returns exactly the rows you meant, swap SELECT * for UPDATE or DELETE and keep the same WHERE.

-- 1. look first
SELECT * FROM STUDENT_COPY WHERE gpa < 3.00;
-- 2. same WHERE, now change them
UPDATE STUDENT_COPY SET gpa = gpa + 0.10 WHERE gpa < 3.00;

COMMIT and ROLLBACK in MySQL

MySQL runs with autocommit on by default: every statement is committed the moment it finishes, so a plain ROLLBACK afterward has nothing to undo. To get the undo the Chapter 5 review describes, start a transaction first:

-- open a transaction, so nothing is saved until COMMIT
START TRANSACTION;

-- the mistake: no WHERE clause
UPDATE STUDENT_COPY SET gpa = 4.00;
SELECT * FROM STUDENT_COPY;      -- every gpa is 4.00

-- undo everything since START TRANSACTION
ROLLBACK;
SELECT * FROM STUDENT_COPY;      -- original values are back

Use COMMIT; instead of ROLLBACK; to keep the changes. CREATE, ALTER, and DROP commit on their own and cannot be rolled back.

Section 5.6

Views you can write through, and views you cannot

A view holds no data. It is a saved SELECT that runs each time you query it, so a change made through a view lands in the table underneath.

-- the students on the copy with a 3.50 or better, saved under a name
CREATE VIEW HIGH_GPA AS
SELECT student_id, first_name, last_name, gpa
FROM   STUDENT_COPY
WHERE  gpa >= 3.50;

-- two students come back
SELECT * FROM HIGH_GPA ORDER BY gpa DESC;
-- before: Ana is at 3.75 in the real table
SELECT student_id, gpa FROM STUDENT_COPY WHERE student_id = 1;

-- this UPDATE names the VIEW, not the table
UPDATE HIGH_GPA SET gpa = 3.95 WHERE student_id = 1;

-- after: STUDENT_COPY now says 3.95, though the UPDATE never named it
SELECT student_id, gpa FROM STUDENT_COPY WHERE student_id = 1;

That is an updatable view. Each row of HIGH_GPA traces back to exactly one row of STUDENT_COPY, so MySQL knows which row to change.

An aggregate view refuses

-- one summary row worked out from every student
CREATE VIEW GPA_SUMMARY AS
SELECT COUNT(*) AS n, ROUND(AVG(gpa), 2) AS avg_gpa
FROM   STUDENT_COPY;

-- should fail: there is no single row behind an average
UPDATE GPA_SUMMARY SET avg_gpa = 4.00;
-- ERROR 1288 (HY000): The target table GPA_SUMMARY of the UPDATE is not updatable
What makes a view not updatable in MySQL.
Feature in the SELECTWhy it blocks updates
COUNT, SUM, AVG, MIN, MAXOne output row summarizes many base rows
GROUP BY or HAVINGSame reason: rows are collapsed together
DISTINCTOne output row may stand for several identical base rows
UNIONA row could come from either side
A WHERE filterDoes not block updates. HIGH_GPA has one and is updatable.

Updating a row out of its own view

-- allowed, and Ana silently disappears from HIGH_GPA because 3.00 fails the WHERE
UPDATE HIGH_GPA SET gpa = 3.00 WHERE student_id = 1;

-- WITH CHECK OPTION makes the view refuse any change that would push a row out of it
CREATE OR REPLACE VIEW HIGH_GPA AS
SELECT student_id, first_name, last_name, gpa
FROM   STUDENT_COPY
WHERE  gpa >= 3.50
WITH CHECK OPTION;

With the check option in place, an UPDATE through HIGH_GPA that sets a GPA below 3.50 fails with ERROR 1369 (HY000): CHECK OPTION failed.

Managing views

-- see the stored SELECT behind a view
SHOW CREATE VIEW HIGH_GPA;

-- change a view's definition without dropping it first
CREATE OR REPLACE VIEW HIGH_GPA AS
SELECT student_id, first_name, last_name, gpa FROM STUDENT_COPY WHERE gpa >= 3.60;

-- remove the view only; STUDENT_COPY and its rows are untouched
DROP VIEW HIGH_GPA;

Project 7, Part 3

Joins put the tables back together

The data is now spread across three tables, which is correct but hard to read. A join matches rows from each table on the key columns they share, for one query.

The three table join

ENROLLMENT sits in the middle, so you join STUDENT to it, then join COURSE to it. Each ON says which columns match.

-- every enrollment written out with the student's name and the class title instead of ids
SELECT s.first_name, s.last_name, c.course_code, c.course_title, e.term, e.grade
FROM   STUDENT s
JOIN   ENROLLMENT e ON s.student_id = e.student_id
JOIN   COURSE     c ON e.course_id  = c.course_id
ORDER BY s.last_name, c.course_code;

Eight rows, one per enrollment. s, e, and c are table aliases. They save typing and they settle which table a column comes from when two tables share a column name: student_id is in both STUDENT and ENROLLMENT, so writing it bare gives ERROR 1052: Column 'student_id' in field list is ambiguous.

How to build any join

  1. List the tables the answer needs. If two of them do not share a key, find the table in between (here, ENROLLMENT).
  2. Write one JOIN ... ON per link, matching a foreign key to the primary key it references.
  3. Add WHERE to filter, ORDER BY to sort, and pick columns last.

Filtering a join

-- everyone taking CIS4720, with their grade
SELECT s.first_name, s.last_name, e.grade
FROM   STUDENT s
JOIN   ENROLLMENT e ON s.student_id = e.student_id
JOIN   COURSE     c ON e.course_id  = c.course_id
WHERE  c.course_code = 'CIS4720';

-- every class Ana Reyes is taking, and how many credits each is worth
SELECT c.course_code, c.course_title, c.credits
FROM   STUDENT s
JOIN   ENROLLMENT e ON s.student_id = e.student_id
JOIN   COURSE     c ON e.course_id  = c.course_id
WHERE  s.last_name = 'Reyes';

-- only the A grades in Fall 2026
SELECT s.last_name, c.course_code
FROM   STUDENT s
JOIN   ENROLLMENT e ON s.student_id = e.student_id
JOIN   COURSE     c ON e.course_id  = c.course_id
WHERE  e.grade = 'A' AND e.term = 'Fall 2026';

Grouping a join

-- total credits each enrolled student is carrying
SELECT s.first_name, s.last_name, SUM(c.credits) AS total_credits
FROM   STUDENT s
JOIN   ENROLLMENT e ON s.student_id = e.student_id
JOIN   COURSE     c ON e.course_id  = c.course_id
GROUP BY s.student_id, s.first_name, s.last_name
ORDER BY total_credits DESC;

-- enrollments per department
SELECT c.dept, COUNT(*) AS enrollments
FROM   COURSE c
JOIN   ENROLLMENT e ON c.course_id = e.course_id
GROUP BY c.dept;
Enrollments per department
dept         enrollments
CIS          5
Mathematics  2
Business     1

Ana's total is 10 credits (3 + 3 + 4). Any column in the SELECT that is not inside an aggregate must appear in GROUP BY.

The outer join keeps rows with no match

Elena Vargas (student 5) has no enrollments, so the plain JOIN above leaves her out entirely. A plain (inner) JOIN only returns rows that match on both sides. LEFT JOIN keeps every row from the table on the left, and fills the right side with NULL where nothing matches.

-- every student and how many classes they take, including students taking none
SELECT s.first_name, s.last_name, COUNT(e.course_id) AS courses_taken
FROM   STUDENT s
LEFT JOIN ENROLLMENT e ON s.student_id = e.student_id
GROUP BY s.student_id, s.first_name, s.last_name
ORDER BY courses_taken DESC, s.last_name;
Output
first_name  last_name  courses_taken
Ana         Reyes      3
Marcus      Bell       2
Priya       Nair       2
Devon       Rao        1
Elena       Vargas     0

COUNT(e.course_id), not COUNT(*). With a LEFT JOIN, Elena still produces one row, with NULL in every ENROLLMENT column. COUNT(*) counts rows, so it would give her 1. COUNT(e.course_id) counts only non NULL values, so she correctly gets 0. Always count a column from the right hand table in an outer join.

Finding the rows with no match

LEFT JOIN plus WHERE right_side.key IS NULL answers "which ones have none?"

-- classes nobody signed up for
SELECT c.course_code, c.course_title
FROM   COURSE c
LEFT JOIN ENROLLMENT e ON c.course_id = e.course_id
WHERE  e.student_id IS NULL;
-- one row: CIS4850 Advanced Python

-- students not enrolled in anything
SELECT s.first_name, s.last_name
FROM   STUDENT s
LEFT JOIN ENROLLMENT e ON s.student_id = e.student_id
WHERE  e.course_id IS NULL;
-- one row: Elena Vargas

See the difference in one query

-- swap both JOINs in the three table join for LEFT JOIN
SELECT s.first_name, s.last_name, c.course_code, e.grade
FROM   STUDENT s
LEFT JOIN ENROLLMENT e ON s.student_id = e.student_id
LEFT JOIN COURSE     c ON e.course_id  = c.course_id
ORDER BY s.last_name;
-- nine rows now: the eight enrollments, plus Elena with NULL in course_code and grade

The second join must also be LEFT. If it were a plain JOIN, Elena's NULL course_id would fail to match COURSE and she would be dropped again.

Which join to reach for.
JoinReturnsUse when
JOIN (INNER JOIN)Only rows that match on both sidesYou want existing pairings, such as who is taking what
LEFT JOINEvery row from the left table, NULL on the right where no matchCounting including zeros, or finding rows with no match
RIGHT JOINEvery row from the right tableSame as LEFT with the tables swapped; most people just reorder and use LEFT

More join practice against a different database: join examples and aggregate examples.

Project 7, Part 4

Save the joins as views

A join worth writing once is worth saving. Wrap it in CREATE VIEW and from then on it is a SELECT * with no join in sight.

STUDENT_SCHEDULE: the three table join

-- the full class schedule saved under a name, so nobody has to write the join again
CREATE VIEW STUDENT_SCHEDULE AS
SELECT s.first_name, s.last_name, c.course_code, c.course_title, e.term, e.grade
FROM   STUDENT s
JOIN   ENROLLMENT e ON s.student_id = e.student_id
JOIN   COURSE     c ON e.course_id  = c.course_id;

-- all eight enrollments
SELECT * FROM STUDENT_SCHEDULE;
-- Ana's three classes
SELECT * FROM STUDENT_SCHEDULE WHERE last_name = 'Reyes';
-- the three students in CIS4720
SELECT * FROM STUDENT_SCHEDULE WHERE course_code = 'CIS4720';

Leave ORDER BY out of the view. Sort when you query the view instead (SELECT * FROM STUDENT_SCHEDULE ORDER BY last_name;). Each query can then sort the way it needs.

COURSE_HEADCOUNT: the outer join with a count

-- students per class, with empty classes counted as zero instead of dropped
CREATE VIEW COURSE_HEADCOUNT AS
SELECT c.course_code, c.course_title, COUNT(e.student_id) AS students_enrolled
FROM   COURSE c
LEFT JOIN ENROLLMENT e ON c.course_id = e.course_id
GROUP BY c.course_id, c.course_code, c.course_title;

-- busiest class first
SELECT * FROM COURSE_HEADCOUNT ORDER BY students_enrolled DESC;
Output
course_code  course_title                 students_enrolled
CIS4720      Database Management and SQL  3
CIS2000      Intro to Programming         2
MATH1600     Calculus I                   2
BUS2100      Principles of Management     1
CIS4850      Advanced Python              0
-- views can be filtered like tables: classes with two or more students
SELECT * FROM COURSE_HEADCOUNT WHERE students_enrolled >= 2;

Which of the two can be written through?

-- should fail 1288: a count has no single row underneath it to change
UPDATE COURSE_HEADCOUNT SET students_enrolled = 99 WHERE course_code = 'CIS4720';
-- ERROR 1288 (HY000): The target table COURSE_HEADCOUNT of the UPDATE is not updatable

STUDENT_SCHEDULE has no aggregate, so MySQL does allow an UPDATE through it, as long as the UPDATE changes columns from only one of the joined tables:

-- changes one ENROLLMENT row: Ana's grade in CIS2000 becomes A
UPDATE STUDENT_SCHEDULE SET grade = 'A'
WHERE  last_name = 'Reyes' AND course_code = 'CIS2000';

DELETE through a view that joins several tables is not allowed in MySQL. When in doubt, make changes to the base tables directly and use views for reading.

Confirm everything is in place

-- every table and view in the schema, labeled by type
SHOW FULL TABLES;
Output after lab7b and Project 7
Tables_in_students_db  Table_type
COURSE                 BASE TABLE
COURSE_HEADCOUNT       VIEW
ENROLLMENT             BASE TABLE
GPA_SUMMARY            VIEW
HIGH_GPA               VIEW
STUDENT                BASE TABLE
STUDENT_COPY           BASE TABLE
STUDENT_GPA            VIEW
STUDENT_SCHEDULE       VIEW

Handing in

Publishing your file to GitHub

GitHub gives your file a public web address. That address is the whole submission. A statement that is not in the uploaded file did not happen, as far as grading goes.

Two routes to a repository.
github.com in a browserVS Code, Publish to GitHub
Needs Git installedNoYes (check with git --version)
Needs a sign in stored on the PCNoYes, and the lab PC forgets it overnight
What you getAn empty repo; you upload files by handA repo with your folder's files already in it
Used inlab7, lab7bProject 7, and your own laptop

The GitHub Pull Requests and Issues extension is a third thing again. It does not create repositories; it lets you review other people's proposed changes inside VS Code.

The VS Code route (Project 7)

  1. Open the project folder in VS Code and save the .sql file (Ctrl + S).
  2. Sign in from the Accounts icon at the bottom of the left bar.
  3. Source Control icon, then Publish to GitHub.
  4. Name it (for example cis4720-project7) and choose public.
  5. Tick only students_db_backup.sql. Leave .vscode unticked.

Changing the file after publishing

Edit and save the file, then in Source Control type a message, click Commit, then Sync Changes (push). On the website route, use Add file, Upload files again; uploading a file with the same name replaces it. Either way, write a commit message that says what changed, such as Add Project 7 joins and views.

Never publish .vscode/settings.json. SQLTools can save your database password there in plain text, and a public repo is readable by anyone. Upload only the .sql file. Also sign out of GitHub in VS Code before leaving a shared PC.

Check it the way your instructor will. Open a private or incognito window (Ctrl + Shift + N), paste the URL, and confirm you can read the file and your comments while signed out. A 404 means the repo is private: Settings, scroll to the bottom, Change repository visibility.

The address looks like https://github.com/yourusername/cis4720-project7. That is what goes in the Canvas box.

Reference

Error codes you have met, and what to do

Most of these are the database doing its job. Read the number first; it tells you which rule was enforced.

MySQL errors from lab7, lab7b, and Project 7.
CodeMessage (short)Cause and fix
1049Unknown databaseThe schema does not exist yet. CREATE DATABASE at the command prompt.
1050Table already existsA second run of a CREATE. Comment it out.
1062Duplicate entry for key PRIMARYA row with that key already exists. Usually inserts run twice.
1064Syntax errorA typo, a missing comma, -- with no space, or a leftover */ from nested block comments.
1052Column is ambiguousThe column exists in two joined tables. Prefix it with an alias, like s.student_id.
1054Unknown columnMisspelled column, or a column you dropped or did not copy.
1136Column count doesn't match value countThe VALUES list has a different number of values than the table has columns. Name the columns.
1146Table doesn't existMisspelled name, or the CREATE has not run yet on this PC.
1264Out of range valueThe number does not fit the type, such as 10.50 in DECIMAL(3,2).
1005 / 1824Foreign key incorrectly formed / failed to open referenced tableChild created before parent, or the FK column type does not match the PK type.
1452Cannot add or update a child rowThe FK value has no matching parent row. Insert the parent first or fix the id.
1451Cannot delete or update a parent rowChild rows still point at it. Delete the children first.
1288Target table is not updatableUPDATE through a view with an aggregate, GROUP BY, or DISTINCT.
1369CHECK OPTION failedThe change would move a row out of a view created WITH CHECK OPTION.

For a full command list see the SQL command reference.

Practice

Practice set: extend students_db with an INSTRUCTOR table

These tasks use every idea on this page, in the same order the assignments did. Try each one before opening the solution. Label each with a heading and comment every statement, exactly as you would for a graded file.

Task 1. Create a parent table.

Create INSTRUCTOR with instructor_id (whole number, primary key), first_name and last_name (text up to 30, required), dept (text up to 30), and hire_date (a date). Add three instructors, one of whom will teach nothing.

Show solution
-- =================================================================
-- PRACTICE TASK 1. Create the INSTRUCTOR table
-- =================================================================

-- the people who teach the classes. instructor_id is the key so every
-- instructor can be told apart, even two with the same name
CREATE TABLE INSTRUCTOR (
    instructor_id  INT          NOT NULL,
    first_name     VARCHAR(30)  NOT NULL,
    last_name      VARCHAR(30)  NOT NULL,
    dept           VARCHAR(30),
    hire_date      DATE,
    PRIMARY KEY (instructor_id)
);

-- three instructors; Okafor will not be assigned a class, for the outer join later
INSERT INTO INSTRUCTOR VALUES (1, 'Maria', 'Chen',   'CIS',         '2019-08-15');
INSERT INTO INSTRUCTOR VALUES (2, 'James', 'Holt',   'Mathematics', '2015-01-10');
INSERT INTO INSTRUCTOR VALUES (3, 'Ruth',  'Okafor', 'Business',    '2024-08-20');

-- confirm instructor_id shows PRI and hire_date is a date
DESCRIBE INSTRUCTOR;

Task 2. Connect an existing table to it.

COURSE already exists and has rows. Add an instructor_id column to it, attach a foreign key to INSTRUCTOR, then assign Chen to the CIS classes and Holt to Calculus. Leave Business unassigned.

Show solution
-- =================================================================
-- PRACTICE TASK 2. Link COURSE to INSTRUCTOR
-- =================================================================

-- a new column for who teaches each class. no NOT NULL, because the five
-- existing courses have no instructor yet and would break that rule
ALTER TABLE COURSE ADD COLUMN instructor_id INT;

-- make the server check that every instructor_id in COURSE is a real instructor
ALTER TABLE COURSE
  ADD CONSTRAINT fk_course_instructor
  FOREIGN KEY (instructor_id) REFERENCES INSTRUCTOR (instructor_id);

-- look first: these are the rows the next UPDATE will change
SELECT course_id, course_code FROM COURSE WHERE dept = 'CIS';

-- Chen teaches every CIS class
UPDATE COURSE SET instructor_id = 1 WHERE dept = 'CIS';

-- Holt teaches Calculus
UPDATE COURSE SET instructor_id = 2 WHERE course_id = 103;

-- should fail 1452: there is no instructor 9
UPDATE COURSE SET instructor_id = 9 WHERE course_id = 104;

-- check the assignments; BUS2100 should show NULL
SELECT course_code, instructor_id FROM COURSE;

Task 3. Copy and reshape.

Make FALL_ENROLLMENT holding only the Fall 2026 rows of ENROLLMENT. Show that it has no primary key, then add the composite key back and prove it works.

Show solution
-- =================================================================
-- PRACTICE TASK 3. Copy the Fall 2026 enrollments
-- =================================================================

-- a snapshot of this term's enrollments only, as its own table
CREATE TABLE FALL_ENROLLMENT AS
SELECT student_id, course_id, grade
FROM   ENROLLMENT
WHERE  term = 'Fall 2026';

-- six rows should come back (the two Spring rows were filtered out)
SELECT * FROM FALL_ENROLLMENT;

-- no PRIMARY KEY line in the output: the copy left the key behind
SHOW CREATE TABLE FALL_ENROLLMENT;

-- restore the pair of ids as the key, so a student cannot appear twice in a class
ALTER TABLE FALL_ENROLLMENT ADD PRIMARY KEY (student_id, course_id);

-- should fail 1062: student 1 is already in course 101
INSERT INTO FALL_ENROLLMENT VALUES (1, 101, 'B');

Task 4. A four table join.

List every enrollment with the student's name, the course code, and the instructor's last name, sorted by course code.

Show solution
-- =================================================================
-- PRACTICE TASK 4. Who is taking what, from whom
-- =================================================================

-- every enrollment with readable names, following the keys from
-- STUDENT through ENROLLMENT to COURSE and on to INSTRUCTOR
SELECT s.first_name, s.last_name, c.course_code,
       i.last_name AS instructor
FROM   STUDENT s
JOIN   ENROLLMENT e ON s.student_id    = e.student_id
JOIN   COURSE     c ON e.course_id     = c.course_id
JOIN   INSTRUCTOR i ON c.instructor_id = i.instructor_id
ORDER BY c.course_code, s.last_name;

This returns seven rows, not eight. Marcus or Priya's BUS2100 enrollment drops out, because BUS2100 has a NULL instructor_id and the plain JOIN to INSTRUCTOR finds no match. Change the last line to LEFT JOIN INSTRUCTOR i ... and the eighth row returns with NULL as the instructor. Alias i.last_name AS instructor because last_name is also a STUDENT column.

Task 5. An outer join that finds what is missing.

(a) List every instructor and how many classes they teach, including zero. (b) List the courses with no instructor.

Show solution
-- =================================================================
-- PRACTICE TASK 5. Teaching load, including nobody
-- =================================================================

-- every instructor with a class count; LEFT JOIN keeps Okafor, and counting
-- c.course_id instead of * gives her 0 rather than 1
SELECT i.first_name, i.last_name, COUNT(c.course_id) AS classes_taught
FROM   INSTRUCTOR i
LEFT JOIN COURSE c ON i.instructor_id = c.instructor_id
GROUP BY i.instructor_id, i.first_name, i.last_name
ORDER BY classes_taught DESC;

-- courses still waiting for an instructor
SELECT course_code, course_title
FROM   COURSE
WHERE  instructor_id IS NULL;
Output for (a)
first_name  last_name  classes_taught
Maria       Chen       3
James       Holt       1
Ruth        Okafor     0

Part (b) needs no join at all, because the missing value is in COURSE itself. Use LEFT JOIN with IS NULL when the missing thing is a row in another table, and plain IS NULL when it is a column in the same table.

Task 6. Save them as views, and test updatability.

Create INSTRUCTOR_LOAD from Task 5(a) and CIS_ROSTER showing student names and grades in CIS classes only. Then try one UPDATE through each.

Show solution
-- =================================================================
-- PRACTICE TASK 6. Two views
-- =================================================================

-- teaching load per instructor, saved so it can be checked any time
CREATE VIEW INSTRUCTOR_LOAD AS
SELECT i.first_name, i.last_name, COUNT(c.course_id) AS classes_taught
FROM   INSTRUCTOR i
LEFT JOIN COURSE c ON i.instructor_id = c.instructor_id
GROUP BY i.instructor_id, i.first_name, i.last_name;

-- every student in a CIS class with their grade, for the CIS department
CREATE VIEW CIS_ROSTER AS
SELECT s.first_name, s.last_name, c.course_code, e.grade
FROM   STUDENT s
JOIN   ENROLLMENT e ON s.student_id = e.student_id
JOIN   COURSE     c ON e.course_id  = c.course_id
WHERE  c.dept = 'CIS';

-- read both
SELECT * FROM INSTRUCTOR_LOAD;
SELECT * FROM CIS_ROSTER ORDER BY course_code, last_name;

-- should fail 1288: the count is an aggregate with no single row under it
UPDATE INSTRUCTOR_LOAD SET classes_taught = 5 WHERE last_name = 'Okafor';

-- allowed: no aggregate, and only an ENROLLMENT column changes
UPDATE CIS_ROSTER SET grade = 'B' WHERE last_name = 'Rao' AND course_code = 'CIS2000';

-- check the base table took the change
SELECT * FROM ENROLLMENT WHERE student_id = 4;

Task 7. Clean up in the right order.

Remove everything the practice set added, leaving students_db as it was after Project 7.

Show solution
-- =================================================================
-- PRACTICE TASK 7. Remove the practice objects
-- =================================================================

-- views first; dropping them never touches any rows
DROP VIEW INSTRUCTOR_LOAD;
DROP VIEW CIS_ROSTER;

-- the snapshot table has no foreign keys pointing at it
DROP TABLE FALL_ENROLLMENT;

-- COURSE points at INSTRUCTOR, so remove that link before INSTRUCTOR can go
ALTER TABLE COURSE DROP FOREIGN KEY fk_course_instructor;
ALTER TABLE COURSE DROP COLUMN instructor_id;

-- nothing references INSTRUCTOR now, so it can be dropped
DROP TABLE INSTRUCTOR;

-- should match the nine objects listed after Project 7
SHOW FULL TABLES;

Trying DROP TABLE INSTRUCTOR; before removing the foreign key fails, for the same reason COURSE cannot be dropped before ENROLLMENT. Task 6 also changed two grades (Rao in CIS2000, and Reyes in CIS2000 if you ran the STUDENT_SCHEDULE example); set them back with UPDATE if you want the original data.

Quick check

If you remember only these

  • The lab PC forgets everything overnight. The .sql file on OneDrive and GitHub is your real work; the database is rebuilt from it.
  • Create the empty database at the command prompt before connecting from VS Code, or you get ERROR 1049.
  • Switch statements off with Ctrl + / line comments. Block comments do not nest and cause 1064.
  • Every step gets a numbered heading, and every statement a comment above it saying why it is there.
  • Run CREATE and INSERT once, then comment them out. 1050 and 1062 on a second run mean the data is being protected, not that something broke.
  • SHOW FULL TABLES tells tables from views; DESCRIBE shows types, NULL, and PRI.
  • DECIMAL(p,s): p digits total, s after the point. DECIMAL(3,2) tops out at 9.99.
  • CREATE TABLE AS SELECT copies columns and rows but no primary or foreign keys. Add them back with ALTER TABLE.
  • MODIFY COLUMN replaces the whole definition, so repeat NOT NULL.
  • Test the WHERE as a SELECT before any UPDATE or DELETE. MySQL autocommits, so ROLLBACK only helps inside START TRANSACTION.
  • A view with a filter is updatable; a view with COUNT, SUM, AVG, GROUP BY, or DISTINCT is not (1288).
  • A bridge table like ENROLLMENT has a composite primary key and one foreign key per parent.
  • Build parents first, delete and drop children first (1005, 1452, 1451).
  • JOIN keeps only matches. LEFT JOIN keeps every left row; count a right side column, not *, so zero shows as 0.
  • LEFT JOIN plus WHERE right.key IS NULL finds the rows with no match.
  • Publish only the .sql file to a public repo, never .vscode, and test the URL in a private window.