17.1. Triggers for Computations

If you look at posting in newsgroups, you can easily find examples of table declarations with computed columns. The values in these columns are provided by a computation done in a trigger.

CREATE TABLE Boxes
(box_name CHAR(5) NOT NULL PRIMARY KEY,
box_length INTEGER NOT NULL,
box_height INTEGER NOT NULL,
box_width INTEGER NOT NULL,
box_volume INTEGER NOT NULL);

This is accompanied by a trigger that has the statement:

SET box_volume = box_length * box_height * box_width;

Depending on your SQL product, you might have to update the table as a whole, or just update the modified rows. The reasoning given for this trigger is to be sure that an UPDATE is always run to keep the box’s volume correct. It is a way to ensure ...

Get Joe Celko's Thinking in Sets: Auxiliary, Temporal, and Virtual Tables in SQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.