CIS 4720 · Chapter 5, Sections 5.7 and 5.8 · In Class Lab 5d, In Class Lab 5e, Project 9 · Concept checklist
These three assignments moved work out of your hands and into the database: the server picks the keys, a function does the arithmetic, and triggers keep totals and logs current without anyone remembering to. This page lists the ideas you should now be able to explain in your own words. It does not repeat the lab answers. If a section here feels unfamiliar, go back to that step in your own lab file, and use the Chapter 5 review (5.7 to 5.9) and the lab guide for syntax.
All three assignments
Every assignment started with the same small problem, and you should understand why the routine solves it.
information_schema works because every MySQL server has it, and from that connection you can create your own.IF NOT EXISTS. It makes the statement safe to run again: the second time, it quietly does nothing instead of failing.USE is not enough on its own. USE changes the current database for one connection only. A tool that opens a new connection forgets it. A second SQLTools connection with the database already set removes that risk.SELECT DATABASE(); answers "where are my statements going right now?" Use it whenever a table seems to have disappeared.Section 5.7
A primary key has one job: identify a row, forever. The question is whether a value from the real world can be trusted with that job.
A natural key is a value the outside world already gives you: an email address, a phone number, a course code, a parcel number. A surrogate key is a number the database invents only to identify the row. It means nothing to anybody, and that is exactly why it works.
| A primary key should be | Natural key | Surrogate key |
|---|---|---|
| Unique | Usually, until two people share a phone or an email gets reassigned | Always; the server hands out each number once |
| Never empty | Not always; a new student may not have an email yet | Always; the server fills it in |
| Never changing | No. People, agencies, and businesses change these values | Yes; there is never a business reason to change it |
| Controlled by you | No. Someone outside your organization owns it | Yes |
| Small and fast to join on | Often long text | A plain integer |
The most important row is "never changing." A primary key is copied into every table that points at it, as a foreign key. Change the key in one place and every copy everywhere is now wrong. The next section shows what that looks like in real life.
Case study
A local example of what happens when a natural key you do not control changes underneath you.
Every piece of land in a California county is identified by an Assessor's Parcel Number (APN). In Stanislaus County the number is built from the assessor's map book, the page in that book, and the parcel on that page, so 043-003-001 means book 43, page 3, parcel 1. The county uses it to send property tax bills, and it is printed on deeds, permits, and maps.
Because the APN looked permanent and was already on every document, many outside organizations made it the primary key of their own property tables: city permit systems, water and irrigation districts, utility billing, title and escrow companies, appraisers, real estate data services, and GIS map layers. Their tables looked something like this:
-- the design that caused the trouble: someone else's number as the key CREATE TABLE PROPERTY ( apn CHAR(11) NOT NULL, -- e.g. '043-003-001' owner_name VARCHAR(60), address VARCHAR(80), PRIMARY KEY (apn) ); CREATE TABLE WATER_ACCOUNT ( account_no INT NOT NULL, apn CHAR(11) NOT NULL, -- foreign key copy of the APN PRIMARY KEY (account_no), FOREIGN KEY (apn) REFERENCES PROPERTY (apn) );
But an APN is not permanent. It belongs to the county, and the county changes it when parcels are split, combined, or resurveyed, and when map pages are reorganized. When Stanislaus County changed parcel numbers, every outside system keyed on the old numbers had a problem, because their key had changed without them.
| Problem | What it looked like |
|---|---|
| Every foreign key had to change | The APN was copied into accounts, permits, inspections, payments, and notes. Changing one parcel meant finding and updating every table that held a copy, in the right order, without breaking a foreign key rule along the way. A foreign key with ON UPDATE CASCADE can help inside one database, but not in spreadsheets, other systems, or paper files. |
| Joins quietly stopped matching | Each new county file arrived with new numbers. An inner join between the county data and an agency's own table simply dropped every renumbered parcel, with no error. Reports came out short and nobody was warned. Finding the missing rows took an outer join with an IS NULL test. |
| History split in two | Payments and permits from before the change sat under the old number, newer ones under the new number. The same property now looked like two properties, so totals were split or counted twice. |
| Splits and merges | One parcel divided into two needs one old key to become two new ones. Two parcels combined need two keys to become one. A primary key cannot express "this row used to be that row," so the link between old and new records was lost. |
| Retired numbers could come back | If a number that was retired is later given to a different parcel, old records keyed on it now point at the wrong land. |
| Format mismatches | Some systems stored 043-003-001 with dashes, some 043003001 without, and some stored it as a number, which silently drops the leading zero and turns it into 43003001. Matching across systems failed even when the parcel had not changed. |
| Expensive restructuring | Changing which column is the primary key means dropping and recreating foreign keys, adding a new column to every child table, copying values across, and rebuilding indexes. On a live system that is downtime and risk. |
Organizations that went through this moved to an AUTO_INCREMENT surrogate key and demoted the APN to an ordinary column. The APN is still stored, still searchable, and can still be required to be unique, but nothing points at it.
-- the surrogate key never changes, so foreign keys never need to CREATE TABLE PROPERTY ( property_id INT NOT NULL AUTO_INCREMENT, apn CHAR(11), -- the county's current number, as text owner_name VARCHAR(60), address VARCHAR(80), PRIMARY KEY (property_id), UNIQUE (apn) ); -- every number the county has ever used for this property CREATE TABLE PROPERTY_APN_HISTORY ( property_id INT NOT NULL, apn CHAR(11) NOT NULL, valid_from DATE, valid_to DATE, PRIMARY KEY (property_id, apn), FOREIGN KEY (property_id) REFERENCES PROPERTY (property_id) );
Now a renumbering is one UPDATE to one column of one row, plus a line in the history table. Water accounts, permits, and payments point at property_id, which never moves, so none of them change. Old and new numbers both lead to the same property through the history table, and the APN is stored as text, so leading zeros survive.
The general rule: if a value is owned by someone else, can be empty, or could ever change, it should not be your primary key. Store it as data, put a UNIQUE constraint on it if it must not repeat, and let the database generate the key.
Section 5.7, Labs 5d and 5e
You should be able to predict the next id without running anything.
information_schema.tables. The value shown is the next number to be handed out, and NULL means the table has no counter at all. MySQL caches those numbers, and ANALYZE TABLE refreshes them.Lab 5d
If the server picked the id, you need a way to ask what it picked.
Lab 5d
The question is not just "how do I join," but "who disappears when I do?"
Section 5.8, Lab 5d and Project 9
A function saves a rule on the server, once, so every query that needs the rule calls the same code.
You should be able to read a function line by line and say what each clause is for:
| Part | What you should know about it |
|---|---|
| Parameters | Each one has a name and a data type. Prefixing them (such as p_) keeps them from being confused with column names, which would make a WHERE clause compare a column to itself. |
| RETURNS | The type of the one value that comes back. A function always returns exactly one value; a view returns rows. |
| DETERMINISTIC | A promise that the same input always gives the same output. A function that reads tables is not truly deterministic, because the data can change. MySQL does not check, and the labs use it so the function can be created; on a production server you would declare NOT DETERMINISTIC. |
| READS SQL DATA | Says the function queries tables but never changes them. Leaving out both this and DETERMINISTIC gives error 1418. |
| BEGIN ... END | Wraps the body. Every statement inside ends with its own semicolon. |
| DECLARE | Creates a local variable that exists only while the function runs. |
| SELECT ... INTO | Stores a query's single result in a variable instead of displaying it. |
| RETURN | Hands the answer back to whatever called the function. |
SHOW CREATE FUNCTION shows the stored code, SHOW FUNCTION STATUS WHERE Db = '...' lists the functions in a database, and DROP FUNCTION removes one so it can be created again.All three assignments
A function or trigger is one statement, however many lines and semicolons it contains.
mysql command prompt program, which splits typing at every semicolon. VS Code sends the whole block at once, so it is not needed, and the server rejects it with error 1064. Examples from books and websites usually include it; you should know to remove it and the $$ after END.-- must be followed by a space or tab to count as a comment. A paste that loses the space turns the comment into code. # needs no space.Section 5.8, Labs 5d, 5e, and Project 9
A trigger is code the server runs by itself when a row in one table is inserted, updated, or deleted. Nobody calls it, so nobody can forget it.
For any trigger, you should be able to name its four parts and explain each choice:
| Decision | What you should understand |
|---|---|
| Timing: BEFORE or AFTER | A BEFORE trigger runs while the row is on its way in, so it can change the row with SET NEW.column, for example filling in a missing date or tidying text. An AFTER trigger runs once the row is saved, so it cannot change that row (error 1362), but anything it queries can now see the new row. That is why a trigger that recalculates a total must be AFTER. |
| Event: INSERT, UPDATE, or DELETE | In MySQL each trigger watches one event. Covering every way the data can change takes one trigger per event. Lab 5d left the DELETE case uncovered on purpose, and a total went stale until Lab 5e closed the gap. |
| Level: FOR EACH ROW | The body runs once for every row the statement affects. A statement that inserts five rows fires the trigger five times. |
| Action: BEGIN ... END | The body can hold several statements and do several jobs, such as updating another table and writing a log line. A trigger on one table is allowed to change a different table. |
| Trigger on | NEW | OLD |
|---|---|---|
| INSERT | The row being added | Does not exist |
| UPDATE | The values going in | The values being replaced |
| DELETE | Does not exist (error 1363) | The row that was removed |
Labs 5e and Project 9
Two column types and two functions that look alike but answer different questions: "what day?" and "exactly when?"
| Type | Stores | Written as | Use it for |
|---|---|---|---|
| DATE | A calendar day only, no time | '2026-10-29' | Birthdays, due dates, the day a payment was made, the day a student attended |
| DATETIME | A day and a time of day, to the second | '2026-10-29 14:05:37' | Log entries, sign in times, anything where the order of events within one day matters |
Both are written year first, as YYYY-MM-DD, with the time as a 24 hour clock after a space. Typing them that way, in quotes, is how you insert one by hand. Because they are real date types rather than text, MySQL can sort them, compare them, and do arithmetic on them.
| Function | Returns | Example result | Matches |
|---|---|---|---|
| CURDATE() | Today's date | 2026-10-29 | A DATE column |
| NOW() | Today's date and the current time | 2026-10-29 14:05:37 | A DATETIME column |
-- try both side by side; the answers depend on when you run it
SELECT CURDATE() AS today, NOW() AS right_now;
Neither takes anything inside the parentheses, but the parentheses are required: they are what tell MySQL this is a function call and not a column name. CURRENT_DATE and CURRENT_TIMESTAMP are standard SQL names for the same two values, and you may see them in other examples.
A payment only needs to know which day it was made, so DATE and CURDATE() are enough. A log is different. If three payments are added and one is removed on the same afternoon, a DATE column would show four entries all on the same day with no way to tell their order. DATETIME with NOW() records the exact second of each one, so the log reads as a timeline.
00:00:00. It looks like everything happened at midnight, which makes a log useless for ordering events.-- works: a DATE column compared with today's date SELECT * FROM attendance WHERE attended_on = CURDATE(); -- finds nothing: a DATETIME almost never equals midnight exactly SELECT * FROM payment_log WHERE logged_on = CURDATE(); -- works: take just the date part of the DATETIME first SELECT * FROM payment_log WHERE DATE(logged_on) = CURDATE(); -- also works, and is how you ask for a range of days SELECT * FROM payment_log WHERE logged_on >= '2026-10-01' AND logged_on < '2026-11-01';
When a DATETIME is compared with a plain date, MySQL treats the date as midnight on that day. A log entry at 14:05 does not equal midnight, so the second query returns no rows even though entries were written today. DATE() strips the time off so the comparison is day to day.
| Function | Does | Example |
|---|---|---|
| DATE(dt) | The date part of a DATETIME | DATE(NOW()) |
| CURTIME() | The current time only | 14:05:37 |
| DATE_ADD(d, INTERVAL n DAY) | A date n days later (also MONTH, YEAR) | DATE_ADD(CURDATE(), INTERVAL 30 DAY) |
| DATEDIFF(a, b) | Number of days from b to a | DATEDIFF(CURDATE(), paid_on) |
| DATE_FORMAT(d, pattern) | Display a date in another style | DATE_FORMAT(paid_on, '%m/%d/%Y') |
Whose clock? CURDATE() and NOW() read the database server's clock and time zone, not the clock of the person typing. On the lab PCs the server is the same machine, so they agree. On a hosted database in another time zone, "today" can roll over at a different hour than you expect.
Project 9
Project 9 is less about new syntax than about two design decisions you should be able to defend.
A view calculates its answer fresh every time, so it can never be out of date. A total stored in a column, like a running total of payments, is faster to read but is only correct at the moment it was written. Once you store a derived value, you take on the job of keeping it correct after every insert, update, and delete. Triggers do that job automatically. Recalculating the whole total with a function, instead of adding or subtracting the one amount, means the same call gives the right answer whether a row was added or removed.
Everywhere else this term, a foreign key protected the link between tables. A log is the exception. Its whole purpose is to remember things that happened, including rows that were later deleted. A foreign key would either refuse the delete or force the log entry to be removed with it, and a log that loses its entries is no log at all. Knowing when not to add a constraint is part of design too.
Reference
| Error | What it is telling you |
|---|---|
| 1064 near 'DELIMITER' | A command prompt instruction was sent to the server. Remove it. |
| 1064 on DECLARE, SET, IF | Only part of a block was sent. Select the whole thing. |
| 1046 | No database selected. Check SELECT DATABASE(). |
| 1005, errno 150 | A foreign key points at a column that does not exist or is not a key. |
| 1452 | A child row names a parent that does not exist. |
| 1701 | TRUNCATE refused because a foreign key points at the table. |
| 1304 / 1359 | The function / trigger already exists. Drop it, then create it again. |
| 1305 | The function does not exist here: it never ran, or ran in another schema. |
| 1418 | The function is missing DETERMINISTIC or READS SQL DATA. |
| 1362 | SET NEW in an AFTER trigger. Only BEFORE can change the row. |
| 1363 | NEW in a DELETE trigger. A deleted row only has OLD. |
Self check
If you can answer each one out loud in a sentence or two, you are ready for what comes next. There are no answers on this page on purpose.
WHERE logged_on = CURDATE() find nothing in a DATETIME column, even for entries made today?