Database systems · Chapter 5 · Sections 5.7 to 5.9 · Database Design and Implementation · Study guide

Chapter 5 review (Sections 5.7 to 5.9): surrogate keys, procedural SQL, and embedded SQL

The first half of Chapter 5 built tables and filled them one statement at a time. This half is about letting the database do more of the work on its own: generating key values, reacting to changes with triggers, running whole business tasks as stored procedures, and being called from inside an application program. The book's examples are written for Oracle, so each one here is shown in Oracle and then in MySQL, the database on our lab PCs, against the same PRODUCT, VENDOR, INVOICE, and LINE tables used in the earlier reviews.

Section 5.7

Having the DBMS Generate Surrogate Keys

Some tables have no good natural key. Instead of making one up by hand, you let the DBMS hand out the next number.

A surrogate key is a primary key the system creates, usually a plain counting number, that carries no business meaning of its own. An invoice number is the classic case: nothing about an invoice naturally identifies it, so the database numbers them 1001, 1002, 1003 as they arrive. A surrogate key is a good choice when the natural key is missing, too long to join on comfortably (a combination of name, date, and address), or likely to change.

The danger in numbering rows by hand is that two users read the current highest number at the same moment, both add one, and both try to insert the same key. Letting the DBMS generate the value removes that race, because the DBMS hands out each number exactly once. Every major DBMS does this, but each with its own syntax.

MySQL: AUTO_INCREMENT

In MySQL the counter belongs to a column. Mark the primary key AUTO_INCREMENT, and any INSERT that leaves the column out (or gives it NULL) gets the next value.

CREATE TABLE INVOICE (
    INV_NUMBER  INT       NOT NULL AUTO_INCREMENT,
    CUS_CODE    INT       NOT NULL,
    INV_DATE    DATE      NOT NULL,
    PRIMARY KEY (INV_NUMBER)
) AUTO_INCREMENT = 1001;            -- first value handed out is 1001

INSERT INTO INVOICE (CUS_CODE, INV_DATE) VALUES (10014, '2026-10-23');
INSERT INTO INVOICE (CUS_CODE, INV_DATE) VALUES (10011, '2026-10-23');
-- INV_NUMBER was never mentioned, yet the rows are 1001 and 1002

SELECT LAST_INSERT_ID();           -- 1002, the value this connection just received

LAST_INSERT_ID() matters as soon as a second table needs the new key. An invoice's LINE rows have to carry the invoice number that was just generated, and this function returns it for your own connection only, so another user's insert in the meantime cannot mix it up:

INSERT INTO LINE (INV_NUMBER, LINE_NUMBER, P_CODE, LINE_UNITS, LINE_PRICE)
VALUES (LAST_INSERT_ID(), 1, '13-Q2/P2', 2, 14.99);

Which tables have an AUTO_INCREMENT counter, and what is next

MySQL keeps a description of every table in a built in schema called information_schema, the data dictionary. Its tables view has one row per table and view, including an auto_increment column. This query lists every table in one database with its counter:

SELECT table_name, auto_increment
FROM information_schema.tables
WHERE table_schema = 'club_db';
  -- AND auto_increment IS NOT NULL;
What the query asks for.
PartMeaning
FROM information_schema.tablesRead the data dictionary's list of tables, not your own data. Every database on the server is in it.
WHERE table_schema = 'club_db'Only the tables in the club_db database. Without it you get MySQL's own system tables too.
auto_incrementThe next value the counter will hand out, not the last one used. If it shows 7, the last insert got 6 (or less, if rows were deleted or an insert failed).

Tables that have no AUTO_INCREMENT column, and every view, show NULL in that column. NULL here means "this table has no counter," not zero. That is what the commented out last line is for:

-- only the tables that HAVE a counter
SELECT table_name, auto_increment
FROM information_schema.tables
WHERE table_schema = 'club_db'
  AND auto_increment IS NOT NULL;

-- only the tables (and views) that do NOT have one
SELECT table_name, auto_increment
FROM information_schema.tables
WHERE table_schema = 'club_db'
  AND auto_increment IS NULL;

Move the semicolon when you switch the line on. In the original query the semicolon ends the WHERE line, and the AND line sits after it as a comment. If you only delete the -- , the AND line comes after the end of the statement and you get ERROR 1064. Take the semicolon off the WHERE line and put it at the end of the AND line, as in the versions above. Also note the test is IS NULL / IS NOT NULL; writing auto_increment = NULL never matches anything, because nothing equals NULL.

ANALYZE TABLE: when the numbers look out of date

MySQL 8 caches the statistics in information_schema.tables, including auto_increment and the approximate row count table_rows, for up to a day by default. Right after you insert rows, the query above can still show the old counter. ANALYZE TABLE refreshes them:

ANALYZE TABLE payment_log;
-- result: one row of status, not your data
Table                 Op       Msg_type  Msg_text
club_db.payment_log   analyze  status    OK

What it actually does: it examines the table's indexes again and records how the values are distributed (how many distinct values each index has). The query optimizer uses those statistics to choose the fastest way to run a query, such as which index to use in a join. Refreshing the cached numbers in information_schema is a side effect of that work.

Oracle: sequences

Oracle's traditional tool is a sequence, a separate database object that produces numbers. It is not attached to any table or column; you call it wherever you need a value.

CREATE SEQUENCE INV_NUMBER_SEQ START WITH 4010 NOCACHE;

INSERT INTO INVOICE VALUES (INV_NUMBER_SEQ.NEXTVAL, 20010, SYSDATE);
INSERT INTO LINE    VALUES (INV_NUMBER_SEQ.CURRVAL, 1, '13-Q2/P2', 1, 14.99);
INSERT INTO LINE    VALUES (INV_NUMBER_SEQ.CURRVAL, 2, '23109-HB', 1, 9.95);
COMMIT;
The two pseudo columns every sequence has.
ReferenceReturns
seq.NEXTVALMoves the sequence forward and returns the new value. Each call returns a new number.
seq.CURRVALReturns the value your session got from its last NEXTVAL, without moving the sequence. Using it before any NEXTVAL in the session is an error.

That pairing is the whole pattern: NEXTVAL once for the parent row (the invoice), CURRVAL for every child row (its lines), so they all share the same invoice number. Other useful sequence statements:

CREATE SEQUENCE CUS_CODE_SEQ START WITH 20010 INCREMENT BY 1 NOCACHE;
SELECT * FROM USER_SEQUENCES;      -- list your sequences
DROP SEQUENCE CUS_CODE_SEQ;        -- removes the sequence, never any table data

NOCACHE tells Oracle not to set aside a block of numbers in memory ahead of time. Cached values are faster but are lost if the database restarts, which leaves a gap.

SQL Server, and Oracle's newer identity columns

-- SQL Server: IDENTITY(start, step) on the column
CREATE TABLE INVOICE (
    INV_NUMBER  INT IDENTITY(1001, 1) PRIMARY KEY,
    CUS_CODE    INT  NOT NULL,
    INV_DATE    DATE NOT NULL
);

-- Oracle 12c and later also allow a column level identity
CREATE TABLE INVOICE (
    INV_NUMBER  NUMBER GENERATED ALWAYS AS IDENTITY (START WITH 1001),
    CUS_CODE    NUMBER NOT NULL,
    INV_DATE    DATE   NOT NULL,
    PRIMARY KEY (INV_NUMBER)
);
Same job, three syntaxes.
DBMSMechanismGet the value just generated
MySQLAUTO_INCREMENT columnLAST_INSERT_ID()
SQL ServerIDENTITY(seed, increment) columnSCOPE_IDENTITY()
OracleSequence object, or an identity column in 12c and laterseq.CURRVAL

Generated keys have gaps, and that is fine. If an insert is rolled back, the number it took is not handed back; the next insert gets the following number. Deleted rows leave holes too. A surrogate key promises uniqueness, not an unbroken run. If a business rule needs gapless numbering (some tax invoices do), a generated key is the wrong tool.

A sequence is not tied to a table. Dropping a table does not drop its sequence, and one sequence could feed several tables. An AUTO_INCREMENT or IDENTITY counter, by contrast, belongs to its column and disappears with the table.

Section 5.8

Procedural SQL

Plain SQL says what result you want, not how to get it. Some tasks need the how: if this, do that; repeat for each row; stop when done.

SQL is a set oriented, nonprocedural language. It has no IF, no loops, and no variables, so it cannot express "for each product below its minimum stock, mark it for reorder, and if the vendor is out of state, add a shipping note." The application could do that logic, but then every program that touches the data has to repeat it correctly. Procedural SQL adds programming constructs to SQL and stores the code inside the database, so it is written once and runs the same way for every user and every application.

The SQL standard calls this stored code a persistent stored module (PSM): a block of SQL statements and procedural extensions that is stored and executed at the DBMS server. Each vendor has its own dialect:

Procedural SQL dialects.
DBMSLanguage
OraclePL/SQL (Procedural Language SQL), the one the textbook uses
SQL ServerTransact SQL
MySQLStored programs, following the SQL/PSM standard closely

Procedural SQL comes in four forms, each covered below: anonymous blocks, triggers, stored procedures, and stored functions.

The anonymous PL/SQL block

An anonymous block is procedural code with no name. It runs once, right away, and is not saved. It is the simplest way to see the structure every PL/SQL program shares:

SET SERVEROUTPUT ON                -- SQL*Plus: show DBMS_OUTPUT messages

DECLARE                            -- optional: variables live here
    W_P1    NUMBER(3) := 0;
    W_P2    NUMBER(3) := 10;
    W_NUM   NUMBER(2) := 0;
BEGIN                              -- required: the statements
    WHILE W_P2 < 300 LOOP
        SELECT COUNT(P_CODE) INTO W_NUM
        FROM   PRODUCT
        WHERE  P_PRICE BETWEEN W_P1 AND W_P2;
        DBMS_OUTPUT.PUT_LINE('There are ' || W_NUM ||
                             ' products priced between ' || W_P1 || ' and ' || W_P2);
        W_P1 := W_P2 + 1;
        W_P2 := W_P2 + 50;
    END LOOP;
END;                               -- required
/                                  -- the slash on its own line runs the block
PL/SQL pieces in that block.
PieceMeaning
DECLARE ... BEGIN ... END;Declarations, then executable statements. Only BEGIN and END are required.
:=Assignment. A plain = is a comparison in PL/SQL.
SELECT ... INTOPuts a query result into variables. The query must return exactly one row, or PL/SQL raises NO_DATA_FOUND or TOO_MANY_ROWS.
IF ... THEN ... ELSIF ... ELSE ... END IF;Conditional logic
WHILE ... LOOP ... END LOOP;Repeats while the condition is true. FOR and plain LOOP with EXIT WHEN also exist.
DBMS_OUTPUT.PUT_LINEPrints a message, shown only after SET SERVEROUTPUT ON
||String concatenation (MySQL uses CONCAT)
P_PRICE%TYPEDeclares a variable with the same type as a column, so it stays correct if the column changes

Common PL/SQL variable types are CHAR, VARCHAR2, NUMBER(p,s), DATE, and BOOLEAN, plus %TYPE to copy a column's type.

Writing procedural code in MySQL

MySQL has no anonymous blocks; procedural code must live inside a trigger, procedure, or function. Because the body contains semicolons, the mysql command line client needs a temporary end marker, set with DELIMITER, so it does not stop at the first semicolon:

DELIMITER $$
CREATE PROCEDURE PRC_HELLO()
BEGIN
    DECLARE W_COUNT INT DEFAULT 0;           -- DECLARE goes inside BEGIN in MySQL
    SELECT COUNT(*) INTO W_COUNT FROM PRODUCT;
    SELECT CONCAT('There are ', W_COUNT, ' products') AS message;
END $$
DELIMITER ;

CALL PRC_HELLO();

MySQL assigns with SET W_COUNT = 5;, and prints a message by running a SELECT, since it has no DBMS_OUTPUT.

In VS Code you do not need DELIMITER

DELIMITER is not part of SQL. The MySQL server has never heard of it. It is a command for the mysql command line client only, which reads your typing line by line and normally sends a statement to the server the moment it sees a semicolon. Inside a trigger or function body that would cut the statement off at the first ;, so you temporarily tell the client "the statement ends at $$ instead."

VS Code with SQLTools works differently. It does not watch for semicolons as you type; it sends the text you run to the server in one piece, and the server understands that everything from BEGIN to the matching END belongs to one statement. So in VS Code, write the routine with ordinary semicolons and no DELIMITER lines at all:

-- VS Code with SQLTools: no DELIMITER, and END ends with a normal semicolon
CREATE PROCEDURE PRC_HELLO()
BEGIN
    DECLARE W_COUNT INT DEFAULT 0;
    SELECT COUNT(*) INTO W_COUNT FROM PRODUCT;
    SELECT CONCAT('There are ', W_COUNT, ' products') AS message;
END;

CALL PRC_HELLO();

Reading the examples on this page: the MySQL versions below include DELIMITER $$ and END $$ so they also work at the mysql> command prompt. In VS Code, delete the two DELIMITER lines and change END $$ to END;. MySQL Workbench's routine editor handles the delimiter for you too.

Section 5.8, continued

Triggers

A trigger is procedural code the DBMS runs automatically when a row is inserted, updated, or deleted. Nobody calls it.

A trigger is attached to one table and fires when a specified data change happens to that table. Because it fires no matter which application or user made the change, it is the right place for rules that must always hold. Typical uses:

The parts of a trigger

Every trigger definition answers four questions.
PartOptionsMeans
TimingBEFORE or AFTERRun before the change is applied (so it can still alter or block it) or after it is done
EventINSERT, UPDATE, DELETEWhich statement fires it. Oracle allows several, like INSERT OR UPDATE, and UPDATE OF specific columns.
LevelStatement or rowA statement level trigger fires once per statement, however many rows it touches. A row level trigger (FOR EACH ROW) fires once for every row affected.
ActionBEGIN ... ENDThe procedural code to run

An UPDATE that changes 10 rows fires a statement level trigger once and a row level trigger 10 times. Only a row level trigger can see the individual values being changed, through two special references:

Old and new values inside a row level trigger.
OracleMySQLHolds
:NEW.columnNEW.columnThe value after the change. Exists for INSERT and UPDATE. In a BEFORE trigger you can assign to it.
:OLD.columnOLD.columnThe value before the change. Exists for UPDATE and DELETE.

Example 1: flag products that need reordering

Add two columns to PRODUCT: a minimum stock level and a reorder flag. The rule is "whenever quantity on hand is at or below the minimum, set the flag to 1, otherwise 0." A BEFORE row level trigger sets the flag on the row as it is written:

ALTER TABLE PRODUCT ADD P_MIN     NUMBER(4);
ALTER TABLE PRODUCT ADD P_REORDER NUMBER(1) DEFAULT 0;

Oracle

CREATE OR REPLACE TRIGGER TRG_PRODUCT_REORDER
BEFORE INSERT OR UPDATE OF P_QOH, P_MIN ON PRODUCT
FOR EACH ROW
BEGIN
    IF :NEW.P_QOH <= :NEW.P_MIN THEN
        :NEW.P_REORDER := 1;
    ELSE
        :NEW.P_REORDER := 0;
    END IF;
END;
/

MySQL

DELIMITER $$
CREATE TRIGGER TRG_PRODUCT_REORDER
BEFORE UPDATE ON PRODUCT
FOR EACH ROW
BEGIN
    IF NEW.P_QOH <= NEW.P_MIN THEN
        SET NEW.P_REORDER = 1;
    ELSE
        SET NEW.P_REORDER = 0;
    END IF;
END $$
DELIMITER ;

MySQL in VS Code (same trigger, no DELIMITER)

CREATE TRIGGER TRG_PRODUCT_REORDER
BEFORE UPDATE ON PRODUCT
FOR EACH ROW
BEGIN
    IF NEW.P_QOH <= NEW.P_MIN THEN
        SET NEW.P_REORDER = 1;
    ELSE
        SET NEW.P_REORDER = 0;
    END IF;
END;

Testing the trigger: what this UPDATE does

A trigger never runs on its own. To see it work, change the data it watches:

UPDATE PRODUCT SET P_QOH = 4 WHERE P_CODE = '11QER/31';
The statement, one clause at a time.
ClauseMeaning
UPDATE PRODUCTChange rows that already exist in the PRODUCT table. UPDATE never adds or removes rows.
SET P_QOH = 4Give the quantity on hand column the new value 4. The old value is simply replaced.
WHERE P_CODE = '11QER/31'Only for the row whose product code is 11QER/31. P_CODE is the primary key, so this matches exactly one row. The code is text, so it goes in single quotes; the slash is just one of its characters, not an operator.

Here is what happens inside the DBMS, in order:

  1. MySQL finds the one row with that P_CODE and builds its new version, with P_QOH set to 4. That new version is NEW; the row as it was is OLD.
  2. Because the trigger is BEFORE UPDATE ... FOR EACH ROW, it runs now, once, for this row, before anything is saved.
  3. The trigger compares NEW.P_QOH (4) with NEW.P_MIN. Suppose the minimum for this product is 5. Since 4 <= 5, it sets NEW.P_REORDER = 1.
  4. MySQL saves the row with both changes: P_QOH is 4 and P_REORDER is 1, even though the UPDATE statement never mentioned P_REORDER.

Check it with a SELECT before and after, then test the other direction:

SELECT P_CODE, P_QOH, P_MIN, P_REORDER FROM PRODUCT WHERE P_CODE = '11QER/31';
-- before: say P_QOH 8, P_MIN 5, P_REORDER 0

UPDATE PRODUCT SET P_QOH = 4 WHERE P_CODE = '11QER/31';
SELECT P_CODE, P_QOH, P_MIN, P_REORDER FROM PRODUCT WHERE P_CODE = '11QER/31';
-- after: P_QOH 4, P_MIN 5, P_REORDER 1   (low stock, flagged)

UPDATE PRODUCT SET P_QOH = 20 WHERE P_CODE = '11QER/31';
SELECT P_CODE, P_QOH, P_MIN, P_REORDER FROM PRODUCT WHERE P_CODE = '11QER/31';
-- restocked: P_QOH 20, P_REORDER back to 0

Keep the WHERE clause. Without WHERE P_CODE = '11QER/31', the UPDATE sets every product's quantity to 4, and the trigger fires once for every row, flagging most of the store for reorder.

MySQL allows only one event per trigger, so covering INSERT too means a second trigger, BEFORE INSERT, with the same body.

Why BEFORE and not AFTER here. An AFTER statement level trigger that runs UPDATE PRODUCT SET P_REORDER = 1 WHERE P_QOH <= P_MIN would also flag low stock, but it rescans the whole table on every change and never clears the flag when a product is restocked. Changing the row's own :NEW value in a BEFORE row level trigger handles both directions and avoids a second UPDATE of the same table. MySQL in fact forbids a trigger from running an UPDATE on its own table (error 1442), so setting NEW is the only way there.

Example 2: a sale reduces stock automatically

Each LINE row records units sold. An AFTER INSERT trigger on LINE subtracts them from the product's quantity on hand, in a different table:

Oracle

CREATE OR REPLACE TRIGGER TRG_LINE_PROD
AFTER INSERT ON LINE
FOR EACH ROW
BEGIN
    UPDATE PRODUCT
    SET    P_QOH  = P_QOH - :NEW.LINE_UNITS
    WHERE  P_CODE = :NEW.P_CODE;
END;
/

MySQL

DELIMITER $$
CREATE TRIGGER TRG_LINE_PROD
AFTER INSERT ON LINE
FOR EACH ROW
BEGIN
    UPDATE PRODUCT
    SET    P_QOH  = P_QOH - NEW.LINE_UNITS
    WHERE  P_CODE = NEW.P_CODE;
END $$
DELIMITER ;

Notice the chain: the UPDATE on PRODUCT fired by this trigger in turn fires TRG_PRODUCT_REORDER, so selling the last few units of a product flags it for reorder with no application code at all. Triggers firing other triggers is powerful, and also the main reason triggers are hard to debug.

Example 3: an audit log of price changes

MySQL

CREATE TABLE PRICE_HISTORY (
    PH_ID       INT NOT NULL AUTO_INCREMENT PRIMARY KEY,   -- surrogate key from 5.7
    P_CODE      VARCHAR(10),
    OLD_PRICE   DECIMAL(8,2),
    NEW_PRICE   DECIMAL(8,2),
    CHANGED_BY  VARCHAR(80),
    CHANGED_AT  DATETIME
);

DELIMITER $$
CREATE TRIGGER TRG_PRICE_AUDIT
AFTER UPDATE ON PRODUCT
FOR EACH ROW
BEGIN
    IF NEW.P_PRICE <> OLD.P_PRICE THEN
        INSERT INTO PRICE_HISTORY (P_CODE, OLD_PRICE, NEW_PRICE, CHANGED_BY, CHANGED_AT)
        VALUES (OLD.P_CODE, OLD.P_PRICE, NEW.P_PRICE, CURRENT_USER(), NOW());
    END IF;
END $$
DELIMITER ;

This one needs both OLD and NEW, which is why it must be row level. The IF keeps the log free of rows where only the quantity changed.

Managing triggers

DROP TRIGGER TRG_PRICE_AUDIT;                -- both Oracle and MySQL
SHOW TRIGGERS;                               -- MySQL: list them
ALTER TRIGGER TRG_LINE_PROD DISABLE;         -- Oracle: switch off without dropping

Dropping a table drops its triggers with it.

Section 5.8, continued

Stored Procedures

A stored procedure is a named block of procedural code and SQL saved in the database, which runs when something calls it.

Where a trigger fires on its own, a stored procedure runs only when a user or program invokes it by name. It usually wraps one complete business task, such as "add a new invoice" or "apply a price increase for a vendor."

Why store the logic in the database.
BenefitHow
Less network trafficThe client sends one CALL instead of many separate SQL statements; all the work happens at the server.
Shared, consistent codeEvery application calls the same procedure, so the business rule is written once and cannot drift between programs.
SecurityUsers can be allowed to run a procedure without being given direct UPDATE rights on its tables.
PerformanceThe procedure is stored and its plan can be reused, rather than parsed fresh each time.

New to procedures? Stored procedures in plain terms walks through every part of a procedure slowly, without and then with a cursor, using the employee database.

Parameters: IN, OUT, IN OUT

How values move in and out of a procedure.
ModeDirection
INThe caller passes a value in; the procedure reads it. The default.
OUTThe procedure sets a value that the caller reads afterward.
IN OUT (MySQL: INOUT)Passed in, possibly changed, and passed back.

Example 1: raise one vendor's prices

Oracle

CREATE OR REPLACE PROCEDURE PRC_VENDOR_PRICE_UP
    (W_VCODE IN NUMBER, W_PCT IN NUMBER)
AS
BEGIN
    UPDATE PRODUCT
    SET    P_PRICE = P_PRICE * (1 + W_PCT / 100)
    WHERE  V_CODE  = W_VCODE;
    DBMS_OUTPUT.PUT_LINE('Prices raised for vendor ' || W_VCODE);
END;
/

EXEC PRC_VENDOR_PRICE_UP(21344, 5);          -- 5 percent for vendor 21344

MySQL

DELIMITER $$
CREATE PROCEDURE PRC_VENDOR_PRICE_UP (IN W_VCODE INT, IN W_PCT DECIMAL(5,2))
BEGIN
    UPDATE PRODUCT
    SET    P_PRICE = P_PRICE * (1 + W_PCT / 100)
    WHERE  V_CODE  = W_VCODE;
END $$
DELIMITER ;

CALL PRC_VENDOR_PRICE_UP(21344, 5);

Do not name a parameter the same as a column. If the MySQL parameter above were called V_CODE, then WHERE V_CODE = V_CODE compares the parameter to itself, is always true, and raises every product's price. That is why the book prefixes variables with W_ (working variable).

Example 2: an OUT parameter

MySQL

DELIMITER $$
CREATE PROCEDURE PRC_VENDOR_COUNT (IN W_VCODE INT, OUT W_COUNT INT)
BEGIN
    SELECT COUNT(*) INTO W_COUNT
    FROM   PRODUCT
    WHERE  V_CODE = W_VCODE;
END $$
DELIMITER ;

CALL PRC_VENDOR_COUNT(21344, @how_many);     -- @how_many is a session variable
SELECT @how_many;

Example 3: one business transaction, several tables

The textbook builds procedures for adding a customer, an invoice, and an invoice line. Adding a line is a good example of why a procedure is useful: it combines a lookup, an insert, and the surrogate key from 5.7 into one call that every program uses the same way.

Oracle

CREATE OR REPLACE PROCEDURE PRC_LINE_ADD
    (W_LN IN NUMBER, W_P_CODE IN VARCHAR2, W_LU IN NUMBER)
AS
    W_LP NUMBER := 0;
BEGIN
    -- look up the current price so the caller cannot get it wrong
    SELECT P_PRICE INTO W_LP FROM PRODUCT WHERE P_CODE = W_P_CODE;

    -- add the line to the invoice this session just created
    INSERT INTO LINE VALUES (INV_NUMBER_SEQ.CURRVAL, W_LN, W_P_CODE, W_LU, W_LP);

    DBMS_OUTPUT.PUT_LINE('Invoice line ' || W_LN || ' added');
END;
/

EXEC PRC_LINE_ADD(1, '13-Q2/P2', 2);

The INSERT into LINE also fires TRG_LINE_PROD, which lowers the stock, which may fire TRG_PRODUCT_REORDER. One procedure call, three automatic consequences, all handled inside the database.

Managing procedures

DROP PROCEDURE PRC_VENDOR_COUNT;             -- both
SHOW PROCEDURE STATUS WHERE Db = DATABASE(); -- MySQL: list them
SHOW CREATE PROCEDURE PRC_VENDOR_COUNT;      -- MySQL: see the code

Oracle uses CREATE OR REPLACE PROCEDURE to change an existing one; MySQL needs DROP PROCEDURE IF EXISTS first, then CREATE.

Section 5.8, continued

Processing Rows One at a Time with Cursors

SELECT ... INTO works only when the query returns exactly one row. To walk through many rows, procedural SQL uses a cursor.

A cursor is a reserved memory area that holds the rows a query returns and lets the program step through them one row at a time. It bridges the gap between SQL, which returns whole sets, and procedural code, which handles one value at a time.

Two kinds of cursor.
KindWhen
Implicit cursorCreated automatically by the DBMS for any SQL statement that returns a single row, such as SELECT ... INTO
Explicit cursorDeclared by you, for a query that can return any number of rows

Working with an explicit cursor is always the same four steps:

The life of an explicit cursor.
StepDoes
DECLARE (CURSOR ... IS)Names the cursor and attaches the SELECT. Nothing runs yet.
OPENRuns the query and fills the cursor with its rows, positioned before the first one.
FETCH ... INTOCopies the next row into variables and moves forward one row.
CLOSEReleases the cursor's memory.

Oracle

DECLARE
    W_P_CODE      PRODUCT.P_CODE%TYPE;
    W_P_DESCRIPT  PRODUCT.P_DESCRIPT%TYPE;
    CURSOR PROD_CURSOR IS
        SELECT P_CODE, P_DESCRIPT
        FROM   PRODUCT
        WHERE  P_QOH > (SELECT AVG(P_QOH) FROM PRODUCT);
BEGIN
    OPEN PROD_CURSOR;
    LOOP
        FETCH PROD_CURSOR INTO W_P_CODE, W_P_DESCRIPT;
        EXIT WHEN PROD_CURSOR%NOTFOUND;
        DBMS_OUTPUT.PUT_LINE(W_P_CODE || ' ' || W_P_DESCRIPT);
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('Products above average stock: ' || PROD_CURSOR%ROWCOUNT);
    CLOSE PROD_CURSOR;
END;
/
Oracle cursor attributes.
AttributeReturns
%ROWCOUNTHow many rows have been fetched so far
%FOUNDTRUE if the last FETCH returned a row
%NOTFOUNDTRUE if the last FETCH found no row, the usual loop exit test
%ISOPENTRUE if the cursor is open

MySQL

DELIMITER $$
CREATE PROCEDURE PRC_ABOVE_AVG_STOCK()
BEGIN
    DECLARE W_DONE     INT DEFAULT 0;
    DECLARE W_P_CODE   VARCHAR(10);
    DECLARE W_COUNT    INT DEFAULT 0;
    DECLARE PROD_CURSOR CURSOR FOR
        SELECT P_CODE FROM PRODUCT
        WHERE  P_QOH > (SELECT AVG(P_QOH) FROM PRODUCT);
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET W_DONE = 1;   -- the %NOTFOUND of MySQL

    OPEN PROD_CURSOR;
    read_loop: LOOP
        FETCH PROD_CURSOR INTO W_P_CODE;
        IF W_DONE = 1 THEN LEAVE read_loop; END IF;
        SET W_COUNT = W_COUNT + 1;
    END LOOP;
    CLOSE PROD_CURSOR;

    SELECT W_COUNT AS products_above_average;
END $$
DELIMITER ;

MySQL requires declarations in a fixed order: variables, then cursors, then handlers.

Reach for a cursor last. The count above could be a single SELECT COUNT(*). A set based SQL statement is almost always faster than looping row by row. Use a cursor only when each row needs different procedural handling.

Section 5.8, continued

Stored Functions

A stored function is like a stored procedure, except it returns one value and can be used inside an ordinary SQL statement.

A stored function is a named group of procedural and SQL statements that returns a value, declared with a RETURN clause. You cannot run it with EXEC or CALL on its own; you use it inside SQL, wherever a built in function like ROUND could go. That makes it the way to add your own reusable calculations to the database.

Example: the inventory value of one product

Oracle

CREATE OR REPLACE FUNCTION FN_INV_VALUE (W_PCODE IN VARCHAR2)
RETURN NUMBER
IS
    W_VALUE NUMBER(10,2);
BEGIN
    SELECT P_QOH * P_PRICE INTO W_VALUE
    FROM   PRODUCT
    WHERE  P_CODE = W_PCODE;
    RETURN W_VALUE;
END;
/

MySQL

DELIMITER $$
CREATE FUNCTION FN_INV_VALUE (W_PCODE VARCHAR(10))
RETURNS DECIMAL(10,2)
READS SQL DATA
BEGIN
    DECLARE W_VALUE DECIMAL(10,2);
    SELECT P_QOH * P_PRICE INTO W_VALUE
    FROM   PRODUCT
    WHERE  P_CODE = W_PCODE;
    RETURN W_VALUE;
END $$
DELIMITER ;

Now it works like any built in function, in a select list, a WHERE, or an ORDER BY:

SELECT P_CODE, P_DESCRIPT, FN_INV_VALUE(P_CODE) AS INV_VALUE
FROM   PRODUCT
WHERE  FN_INV_VALUE(P_CODE) > 500
ORDER BY INV_VALUE DESC;

MySQL asks you to describe what a function does to data (READS SQL DATA, NO SQL, or DETERMINISTIC for one that always gives the same result for the same input). A function that only does arithmetic on its arguments needs no table at all:

DELIMITER $$
CREATE FUNCTION FN_WITH_TAX (W_AMOUNT DECIMAL(10,2), W_RATE DECIMAL(5,4))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
    RETURN ROUND(W_AMOUNT * (1 + W_RATE), 2);
END $$
DELIMITER ;

SELECT P_CODE, P_PRICE, FN_WITH_TAX(P_PRICE, 0.0825) AS PRICE_WITH_TAX FROM PRODUCT;

Managing functions: SHOW FUNCTION STATUS

Functions are not tables, so SHOW TABLES never lists them. To see which stored functions exist, ask for them by database:

SHOW FUNCTION STATUS WHERE Db = 'club_db';

It returns one row per stored function in club_db, with columns such as these:

The columns you will read most.
ColumnShows
DbThe database the function belongs to
NameThe function's name, the one you use in a SELECT
TypeAlways FUNCTION here
DefinerThe account that created it, such as root@localhost
Modified, CreatedWhen it was last changed and when it was first made
Security_typeDEFINER (runs with the creator's permissions, the default) or INVOKER (runs with the caller's)
-- only functions whose names start with FN
SHOW FUNCTION STATUS WHERE Db = 'club_db' AND Name LIKE 'FN%';

-- see the full code of one function
SHOW CREATE FUNCTION FN_INV_VALUE;

-- the same list from the data dictionary, as a normal query
SELECT routine_name, routine_type, created
FROM information_schema.routines
WHERE routine_schema = 'club_db' AND routine_type = 'FUNCTION';

-- remove a function
DROP FUNCTION IF EXISTS FN_WITH_TAX;

Triggers, procedures, and functions side by side

The three kinds of stored procedural code.
TriggerStored procedureStored function
How it runsAutomatically, on INSERT, UPDATE, or DELETEExplicitly, with EXEC (Oracle) or CALL (MySQL)Inside a SQL statement
Tied to a tableYes, exactly oneNoNo
ParametersNone; sees NEW and OLDIN, OUT, IN OUTInput only
ReturnsNothingValues through OUT parameters, if anyExactly one value, with RETURN
Typical useRules that must always hold, audit logsA complete business task across tablesA reusable calculation

Section 5.9

Embedded SQL

Most people never type SQL at all. They use an application, and the application sends SQL to the database for them.

Embedded SQL is SQL written inside a program in a general purpose programming language, called the host language: COBOL, C, C++, Java, C#, Python, and so on. The host language handles the screens, input, and logic; the SQL handles the data.

Why combining them is not simple

SQL and a host language were not designed to work together, and the textbook names three ways they clash:

The three mismatches between SQL and a host language.
MismatchProblemSolution
Run time mismatchSQL is a nonprocedural language that the DBMS interprets and runs at the server, one statement at a time. The host program is typically compiled and runs on the client, in its own process.The program sends each SQL statement to the DBMS and waits for the answer.
Processing mismatchSQL works on whole sets of rows at once. Most host languages process one record, one value, at a time.A cursor, so the program can fetch the result set one row at a time.
Data type mismatchSQL types (VARCHAR, DATE, DECIMAL) do not always match the host language's types (strings, integers, floats).Host variables of compatible types, and conversion by the interface.

The standard framework

To make embedded SQL work, the SQL standard sets a few rules:

A single row query in COBOL

EXEC SQL
    SELECT EMP_LNAME, EMP_FNAME
    INTO   :W_EMP_LNAME, :W_EMP_FNAME
    FROM   EMPLOYEE
    WHERE  EMP_NUM = :W_EMP_NUM
END-EXEC.

IF SQLCODE = 0 THEN
    DISPLAY W_EMP_FNAME, W_EMP_LNAME
ELSE IF SQLCODE = 100 THEN
    DISPLAY 'No employee with that number'
END-IF.

The program puts a value in W_EMP_NUM (say, typed by a user), the SELECT reads it as :W_EMP_NUM, and the result comes back into two more host variables. This is exactly the SELECT ... INTO pattern from PL/SQL, with the host program in place of the procedure.

Many rows: a cursor again

A query that can return more than one row cannot go INTO single variables. The processing mismatch is solved the same way as in PL/SQL:

EXEC SQL
    DECLARE PROD_CURSOR CURSOR FOR
    SELECT P_CODE, P_DESCRIPT FROM PRODUCT WHERE V_CODE = :W_VCODE
END-EXEC.

EXEC SQL OPEN PROD_CURSOR END-EXEC.

PERFORM UNTIL SQLCODE NOT = 0
    EXEC SQL
        FETCH PROD_CURSOR INTO :W_P_CODE, :W_P_DESCRIPT
    END-EXEC
    IF SQLCODE = 0 THEN DISPLAY W_P_CODE, W_P_DESCRIPT END-IF
END-PERFORM.

EXEC SQL CLOSE PROD_CURSOR END-EXEC.

The loop ends when FETCH sets SQLCODE to 100, meaning no more rows.

How an embedded SQL program gets built

  1. The programmer writes host code with SQL statements embedded in it.
  2. A vendor precompiler scans the source, pulls out the SQL, and replaces each statement with calls to the DBMS's runtime library. It also checks the SQL against the database.
  3. The host language compiler compiles the translated program.
  4. The result is linked with the DBMS library and run; at run time, each call sends its SQL to the DBMS.

Static versus dynamic SQL

When is the SQL statement known?
Static SQLDynamic SQL
Statement knownAt compile time. Only the host variable values change from run to run.At run time. The program builds the statement text as it runs.
ExampleWHERE V_CODE = :W_VCODE, always that columnA search screen where the user picks which columns to filter and sort by
StrengthsChecked and optimized ahead of time, so faster and saferFlexible; handles queries nobody predicted
CostsFixed shapeParsed and optimized every run, so slower and uses more resources; risky if built from user input
-- dynamic SQL: the WHERE clause is chosen at run time
W_SQL = 'SELECT * FROM PRODUCT WHERE ' + W_CONDITION
EXEC SQL EXECUTE IMMEDIATE :W_SQL END-EXEC.

The same idea in a modern language

Today most programs talk to the database through a library interface (ODBC, JDBC, or a language driver) rather than a precompiler, but every piece of the framework above is still there. Here is the static query with a cursor, in Python against MySQL:

import mysql.connector

conn = mysql.connector.connect(host="localhost", user="root",
                               password="lab password", database="store")
cur = conn.cursor()                          # a cursor, for the processing mismatch

w_vcode = int(input("Vendor code: "))        # a host variable
cur.execute("SELECT P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT WHERE V_CODE = %s",
            (w_vcode,))                      # %s plays the role of :W_VCODE

for p_code, p_descript, p_price in cur:      # FETCH one row at a time
    print(p_code, p_descript, p_price)       # DECIMAL arrives as Python Decimal: type mapping

cur.close()                                  # CLOSE the cursor
conn.close()

Never build SQL by gluing user input into the string. Writing "... WHERE V_CODE = " + user_text is dynamic SQL from untrusted input, and a user who types 0 OR 1=1 sees every row. That is SQL injection. Passing the value separately, as a host variable or a %s placeholder, keeps it as data that can never become part of the statement.

Quick check

If you remember only these

  • A surrogate key is a system generated primary key with no business meaning. Letting the DBMS generate it means two users can never get the same value.
  • MySQL uses AUTO_INCREMENT and LAST_INSERT_ID(); SQL Server uses IDENTITY; Oracle uses a sequence with NEXTVAL and CURRVAL (or an identity column in 12c and later).
  • NEXTVAL gets a new number and moves the sequence; CURRVAL repeats the session's last one. Use NEXTVAL for the parent row and CURRVAL for its child rows.
  • A sequence is its own object, not tied to any table. Generated keys can have gaps, and that is normal.
  • In information_schema.tables, auto_increment is the next value to be handed out, and NULL means the table has no counter. Filter with IS NULL or IS NOT NULL, never = NULL. ANALYZE TABLE refreshes those cached numbers and the optimizer's index statistics without changing any data.
  • Procedural SQL adds variables, IF, and loops to SQL and stores the code at the server. The standard name is persistent stored module; Oracle's is PL/SQL.
  • An anonymous PL/SQL block runs once and is not saved. SELECT ... INTO must return exactly one row.
  • A trigger runs automatically on INSERT, UPDATE, or DELETE against one table. It has a timing (BEFORE or AFTER), an event, a level (statement or row), and an action.
  • A statement level trigger fires once per statement; a row level trigger (FOR EACH ROW) fires once per affected row and can use :NEW and :OLD.
  • A stored procedure runs when called (EXEC or CALL), takes IN and OUT parameters, and wraps a business task. It reduces network traffic and keeps the logic in one place.
  • A cursor holds a multirow result so procedural code can process it one row at a time: DECLARE, OPEN, FETCH, CLOSE. %NOTFOUND ends the loop.
  • DELIMITER is a command for the mysql command line client, not SQL. In VS Code, leave it out, end the routine with END;, and run the whole CREATE statement as one selection.
  • A stored function returns exactly one value and is used inside SQL statements, unlike a procedure.
  • SHOW FUNCTION STATUS WHERE Db = 'club_db'; lists the stored functions in one database; SHOW PROCEDURE STATUS does the same for procedures.
  • Embedded SQL puts SQL inside a host language. The three mismatches are run time, processing (solved by cursors), and data type.
  • Host variables are prefixed with a colon. SQLCODE 0 is success, 100 is no data, negative is an error.
  • Static SQL is fixed when the program is compiled; dynamic SQL is built at run time, more flexible but slower, and must never be built from raw user input.