CIS 4720 · Chapter 5, Sections 5.7 and 5.8 · In Class Lab 5d, In Class Lab 5e, Project 9 · Concept checklist

What you should know after Labs 5d, 5e, and Project 9

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

Working in the right schema

Every assignment started with the same small problem, and you should understand why the routine solves it.

Section 5.7

Natural keys and surrogate keys

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.

What a good primary key needs, and how each kind measures up.
A primary key should beNatural keySurrogate key
UniqueUsually, until two people share a phone or an email gets reassignedAlways; the server hands out each number once
Never emptyNot always; a new student may not have an email yetAlways; the server fills it in
Never changingNo. People, agencies, and businesses change these valuesYes; there is never a business reason to change it
Controlled by youNo. Someone outside your organization owns itYes
Small and fast to join onOften long textA 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

When Stanislaus County changed its parcel numbers

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.

The problems those organizations ran into

What breaks when a natural primary key changes.
ProblemWhat it looked like
Every foreign key had to changeThe 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 matchingEach 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 twoPayments 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 mergesOne 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 backIf a number that was retired is later given to a different parcel, old records keyed on it now point at the wrong land.
Format mismatchesSome 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 restructuringChanging 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.

The fix: a surrogate key, with the APN as ordinary data

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

How the AUTO_INCREMENT counter behaves

You should be able to predict the next id without running anything.

Lab 5d

LAST_INSERT_ID()

If the server picked the id, you need a way to ask what it picked.

Lab 5d

Outer joins saved as views

The question is not just "how do I join," but "who disappears when I do?"

Section 5.8, Lab 5d and Project 9

Stored functions

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:

The parts of a MySQL stored function.
PartWhat you should know about it
ParametersEach 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.
RETURNSThe type of the one value that comes back. A function always returns exactly one value; a view returns rows.
DETERMINISTICA 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 DATASays the function queries tables but never changes them. Leaving out both this and DETERMINISTIC gives error 1418.
BEGIN ... ENDWraps the body. Every statement inside ends with its own semicolon.
DECLARECreates a local variable that exists only while the function runs.
SELECT ... INTOStores a query's single result in a variable instead of displaying it.
RETURNHands the answer back to whatever called the function.

All three assignments

Running a function or trigger in VS Code

A function or trigger is one statement, however many lines and semicolons it contains.

Section 5.8, Labs 5d, 5e, and Project 9

Triggers

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:

The four decisions in every trigger.
DecisionWhat you should understand
Timing: BEFORE or AFTERA 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 DELETEIn 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 ROWThe body runs once for every row the statement affects. A statement that inserts five rows fires the trigger five times.
Action: BEGIN ... ENDThe 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.
NEW and OLD: which exists when. Memorize this one.
Trigger onNEWOLD
INSERTThe row being addedDoes not exist
UPDATEThe values going inThe values being replaced
DELETEDoes not exist (error 1363)The row that was removed

Labs 5e and Project 9

DATE, DATETIME, CURDATE(), and NOW()

Two column types and two functions that look alike but answer different questions: "what day?" and "exactly when?"

The two column types

What each type stores.
TypeStoresWritten asUse it for
DATEA calendar day only, no time'2026-10-29'Birthdays, due dates, the day a payment was made, the day a student attended
DATETIMEA 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.

The two functions

Built in functions that read the server's clock.
FunctionReturnsExample resultMatches
CURDATE()Today's date2026-10-29A DATE column
NOW()Today's date and the current time2026-10-29 14:05:37A 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.

Why a log uses DATETIME and NOW()

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.

What happens when the type and the function do not match

Where these functions run in a trigger

Comparing dates, and the DATETIME trap

-- 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.

A few more date functions worth recognizing

You will see these in later work.
FunctionDoesExample
DATE(dt)The date part of a DATETIMEDATE(NOW())
CURTIME()The current time only14: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 aDATEDIFF(CURDATE(), paid_on)
DATE_FORMAT(d, pattern)Display a date in another styleDATE_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

Design ideas: stored totals and audit logs

Project 9 is less about new syntax than about two design decisions you should be able to defend.

A stored total needs something to keep it true

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.

An audit log deliberately has no foreign key

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

Errors you should recognize on sight

From Labs 5d, 5e, and Project 9.
ErrorWhat it is telling you
1064 near 'DELIMITER'A command prompt instruction was sent to the server. Remove it.
1064 on DECLARE, SET, IFOnly part of a block was sent. Select the whole thing.
1046No database selected. Check SELECT DATABASE().
1005, errno 150A foreign key points at a column that does not exist or is not a key.
1452A child row names a parent that does not exist.
1701TRUNCATE refused because a foreign key points at the table.
1304 / 1359The function / trigger already exists. Drop it, then create it again.
1305The function does not exist here: it never ran, or ran in another schema.
1418The function is missing DETERMINISTIC or READS SQL DATA.
1362SET NEW in an AFTER trigger. Only BEFORE can change the row.
1363NEW in a DELETE trigger. A deleted row only has OLD.

Self check

Can you explain these without looking?

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.

Keys and counters

  • Why did organizations that used the APN as a primary key have trouble when parcel numbers changed, and what does a surrogate key fix?
  • Why should a parcel number or zip code be stored as text and not as a number?
  • A table has 5 rows and its counter says 7. Is something wrong?
  • What happens to the counter after DELETE of every row? After TRUNCATE? Why are they different?
  • Why must a starting value be set before the first insert?
  • Why does LAST_INSERT_ID() return the first id after a four row insert, and when does it return 0?

Functions and views

  • What is the difference between a view and a function?
  • Why does a function that adds up amounts need IFNULL?
  • What would go wrong if a parameter had exactly the same name as a column?
  • What does SELECT ... INTO do that a normal SELECT does not?
  • Why is DETERMINISTIC not strictly true for a function that reads a table?

Triggers and design

  • When must a trigger be BEFORE, and when must it be AFTER?
  • Which of NEW and OLD exists in an INSERT, UPDATE, and DELETE trigger?
  • Why did deleting a score leave the GPA wrong at the end of Lab 5d?
  • Why does recalculating a total with a function work for both inserts and deletes?
  • Why does the payment log have no foreign key?
  • What is the difference between DATE and DATETIME, and between CURDATE() and NOW()? Which pair belongs together?
  • What gets stored if NOW() goes into a DATE column, or CURDATE() into a DATETIME column?
  • Why does WHERE logged_on = CURDATE() find nothing in a DATETIME column, even for entries made today?
  • You create a trigger after some rows are already in the table. What happens to those rows?
  • Why do you not need DELIMITER in VS Code, and what error do you get if you include it?