CIS 4720 · Chapter 5 · lab7, lab7b, and Project 7 · Lab guide
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 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.
| Thing | Where it lives | Survives? |
|---|---|---|
| Your .sql file | A folder inside OneDrive, synced by the OneDrive app | Yes |
| Your .sql file on GitHub | A public repository with a web address | Yes, and it is what you hand in |
| The students_db database | The MySQL server on the lab PC | No, rebuild it from the file |
| SQLTools connection | .vscode/settings.json in the folder you opened | Only if the folder is on OneDrive |
| VS Code GitHub sign in, Git settings | The lab PC | No |
localhost, port 3306, database students_db, user root.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.
Rebuilding from the file
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
| Code | Meaning |
|---|---|
| 1050 | A table or view with that name already exists. CREATE will not quietly replace something that holds your data. |
| 1062 | A 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.
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
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.
-- 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
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;
| Column | Type | Why |
|---|---|---|
| student_id | int | A whole number with no decimal part. Key column shows PRI. |
| first_name | varchar(30) | Text of varying length, up to 30 characters |
| last_name | varchar(30) | Same. This is the one we widen in Section 5.4. |
| major | varchar(40) | Longer text, because some major names are long |
| gpa | decimal(3,2) | Exactly the shape of a grade average, stored exactly |
| enrolled_on | date | A real date the database can sort and compare |
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.
| Type | Before the point | After | Largest value | Good for |
|---|---|---|---|---|
| DECIMAL(3,2) | 1 | 2 | 9.99 | A GPA |
| DECIMAL(5,2) | 3 | 2 | 999.99 | A percentage score like 100.00 |
| DECIMAL(7,2) | 5 | 2 | 99999.99 | A product price (lab7 PRODUCT table) |
| DECIMAL(10,2) | 8 | 2 | 99999999.99 | Salaries, 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
| Value | Type | Reason |
|---|---|---|
| Course credits (3, 4) | INT | A whole number count |
| A letter grade (A, B, C) | CHAR(1) | Always exactly one character |
| A term like Fall 2026 | VARCHAR(15) | Short text that varies in length |
| A course code like CIS4720 | VARCHAR(10) | Has digits, but you never add course codes together |
| A phone number or zip code | CHAR or VARCHAR | Never used in arithmetic, and a leading zero must be kept |
| Tuition owed | DECIMAL(8,2) | Money must be exact; FLOAT and DOUBLE can drift |
| Date of birth | DATE | Sorting, comparing, and date math all work |
| A yes or no flag | CHAR(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 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';
-- 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
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.
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.
| Goal | Syntax |
|---|---|
| Add a column | ADD COLUMN name TYPE |
| Change type or width | MODIFY COLUMN name NEWTYPE [NOT NULL] |
| Remove a column | DROP COLUMN name |
| Add a primary key | ADD PRIMARY KEY (col) |
| Add a foreign key | ADD CONSTRAINT fk_name FOREIGN KEY (col) REFERENCES PARENT (col) |
| Remove a foreign key | DROP FOREIGN KEY fk_name |
| Add a check rule | ADD CONSTRAINT chk_name CHECK (condition) |
Section 5.5
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
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);
-- 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;
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
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.
-- 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
| Feature in the SELECT | Why it blocks updates |
|---|---|
| COUNT, SUM, AVG, MIN, MAX | One output row summarizes many base rows |
| GROUP BY or HAVING | Same reason: rows are collapsed together |
| DISTINCT | One output row may stand for several identical base rows |
| UNION | A row could come from either side |
| A WHERE filter | Does not block updates. HIGH_GPA has one and is updatable. |
-- 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.
-- 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
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.
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.
JOIN ... ON per link, matching a foreign key to the primary key it references.-- 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';
-- 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.
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.
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
-- 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.
| Join | Returns | Use when |
|---|---|---|
| JOIN (INNER JOIN) | Only rows that match on both sides | You want existing pairings, such as who is taking what |
| LEFT JOIN | Every row from the left table, NULL on the right where no match | Counting including zeros, or finding rows with no match |
| RIGHT JOIN | Every row from the right table | Same 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
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.
-- 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.
-- 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;
-- 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.
-- 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
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.
| github.com in a browser | VS Code, Publish to GitHub | |
|---|---|---|
| Needs Git installed | No | Yes (check with git --version) |
| Needs a sign in stored on the PC | No | Yes, and the lab PC forgets it overnight |
| What you get | An empty repo; you upload files by hand | A repo with your folder's files already in it |
| Used in | lab7, lab7b | Project 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.
cis4720-project7) and choose public.students_db_backup.sql. Leave .vscode unticked.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
Most of these are the database doing its job. Read the number first; it tells you which rule was enforced.
| Code | Message (short) | Cause and fix |
|---|---|---|
| 1049 | Unknown database | The schema does not exist yet. CREATE DATABASE at the command prompt. |
| 1050 | Table already exists | A second run of a CREATE. Comment it out. |
| 1062 | Duplicate entry for key PRIMARY | A row with that key already exists. Usually inserts run twice. |
| 1064 | Syntax error | A typo, a missing comma, -- with no space, or a leftover */ from nested block comments. |
| 1052 | Column is ambiguous | The column exists in two joined tables. Prefix it with an alias, like s.student_id. |
| 1054 | Unknown column | Misspelled column, or a column you dropped or did not copy. |
| 1136 | Column count doesn't match value count | The VALUES list has a different number of values than the table has columns. Name the columns. |
| 1146 | Table doesn't exist | Misspelled name, or the CREATE has not run yet on this PC. |
| 1264 | Out of range value | The number does not fit the type, such as 10.50 in DECIMAL(3,2). |
| 1005 / 1824 | Foreign key incorrectly formed / failed to open referenced table | Child created before parent, or the FK column type does not match the PK type. |
| 1452 | Cannot add or update a child row | The FK value has no matching parent row. Insert the parent first or fix the id. |
| 1451 | Cannot delete or update a parent row | Child rows still point at it. Delete the children first. |
| 1288 | Target table is not updatable | UPDATE through a view with an aggregate, GROUP BY, or DISTINCT. |
| 1369 | CHECK OPTION failed | The change would move a row out of a view created WITH CHECK OPTION. |
For a full command list see the SQL command reference.
Practice
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.
-- =================================================================
-- 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.
-- ================================================================= -- 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.
-- ================================================================= -- 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.
-- =================================================================
-- 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.
-- ================================================================= -- 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.
-- ================================================================= -- 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.
-- ================================================================= -- 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.
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.WHERE right.key IS NULL finds the rows with no match..vscode, and test the URL in a private window.
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
The space after the dashes matters in MySQL.
--thiswith 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
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: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;