
Photo by Todd Quackenbush on Unsplash
Part 1 of this two-part series, discussed the requirements for implementing data integrity checks using a TRIGGER
. With the success of that TRIGGER
, this second blog post will dive into its workings, gaining an understanding of how the checks are performed, along with the TRIGGER
itself.
Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any party or organization.
I will be using Xubuntu Linux 16.04.3 LTS (Xenial Xerus) and MySQL 5.7.21 for these exercises.
Nuts and Bolts
What is a TRIGGER
?
A TRIGGER
is a database object that is basically a special kind of procedure, called implicitly due to some database event.
To start, let’s revisit the collect_to_stage
TRIGGER
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | DELIMITER $$ CREATE TRIGGER collect_to_stage BEFORE INSERT ON asset_staging FOR EACH ROW BEGIN IF NEW.kind = 0 THEN SET NEW.kind = 'other'; INSERT INTO flagged_asset(f_pipe_name, f_pipe_jt_num, f_pipe_heat, f_pipe_length, f_defect, f_message, import_date) VALUES(NEW.pipe_name, NEW.pipe_jt_num, NEW.pipe_heat, NEW.pipe_length, 'Unknown Type', CONCAT(NEW.pipe_name, ' was not in the acceptable list.'), NOW()); END IF; IF NEW.pipe_length < = 0 THEN INSERT INTO flagged_asset(f_pipe_name, f_pipe_jt_num, f_pipe_heat, f_pipe_length, f_defect, f_message, import_date) VALUES(NEW.pipe_name, NEW.pipe_jt_num, NEW.pipe_heat, NEW.pipe_length, 'Questionable Length', CONCAT(NEW.pipe_name, ' needs the length verified for accuracy.'), NOW()); END IF; END $$ DELIMITER ; |
How does this TRIGGER
perform its required work?
Let’s find out line by line.
-
- Line 1:
DELIMITER $$
– Line’s 1 and 20 share the same keyword, yet its implications are different. The commonality lies in setting theDELIMITER
. The difference is in the characters used. Why redefine it to begin with?
By default, the statementDELIMITER
recognized by the mysql command-line program is the semicolon (;
). In order to use it (the semicolon) in multiple statements, requires an alternative character. - Line 2:
CREATE TRIGGER collect_to_stage BEFORE INSERT
– Line 2 specifies theTRIGGER
timing , indicating it will fireBEFORE
anINSERT
operation. - Line 3:
ON asset_staging
– The target table. - Line 4:
FOR EACH ROW
– Indicates theTRIGGER
actuates, occurring for each row affected by the event condition. In this case,INSERT
. - Line 5:
BEGIN
– Used to start a section of compound statements. - Line 6:
IF NEW.kind = 0 THEN
– Line 6 is vital to thekind
column integrity check within anIF
conditional block. TheENUM
data type is a string object composed of a permitted list of values assigned at creation. Each value has an index. The index for an invalid value is 0 (zero). With this information, we can check theNEW.kind
column value. If the value is equal to 0, then an invalid value has been stored for this column.
Depending on the type ofTRIGGER
event,NEW
andOLD
keywords, enable access to row column values. It is worth noting,INSERT
operations provide only aNEW.column
value. - Line 7:
SET NEW.kind = 'other';
– Here, I am setting the unacceptablekind
column value to ‘other’ until it can be investigated, determined what the correct type of asset it is, and corrected. TheSET
statement is purposely located within thisIF
block. By locating it here, setting the consistent ‘other’ value only happens if an invalid value has been imported. Therefore, we still retain the acceptable values for those records having them. - Lines 8 – 11:
INSERT INTO flagged_asset(f_pipe_name, f_pipe_jt_num, f_pipe_heat, f_pipe_length, f_defect, f_message)
VALUES(NEW.pipe_name, NEW.pipe_jt_num, NEW.pipe_heat, NEW.pipe_length,
'Unknown Type', CONCAT(NEW.pipe_name, ' was not in the acceptable list.'));This
INSERT
statement stores the record in tableflagged_asset
due to failing the column check. - Line 12:
END IF;
– The end of this conditional block. - Line 13:
IF NEW.pipe_length < = 0 THEN
– Beginning this second check inside anIF
conditional block. If thepipe_length
value is either 0 (zero) or less, it is flagged. Simple enough.
- Line 1:
VALUES(NEW.pipe_name, NEW.pipe_jt_num, NEW.pipe_heat, NEW.pipe_length,
'Questionable Length', CONCAT(NEW.pipe_name, ' needs the length verified for accuracy.'));
Records not passing the ‘length check’ are inserted into table flagged_asset
.
END IF;
– Ends this IF
conditional block.END $$
– Ending this BEGIN...END
construct and executing the trigger with $$
which is the delimiter. For now.DELIMITER ;
– Re-setting the delimiter back to the default semicolon (;
)To receive notifications for the latest post from “Digital Owl’s Prose” via email, please subscribe by clicking the ‘Click To Subscribe!’ button in the sidebar!
Be sure and visit the “Best Of” page for a collection of my best blog posts.
Final Thoughts
From enforcing business rules to ensuring the integrity of your data, triggers have their place in databases. Oftentimes, they are used to maintain logs of events.
Although not discussed in this series, MySQL does allow a table to have multiple triggers with the same timing and event action, determining firing order using PRECEDES
or FOLLOWS
followed by the existing TRIGGER
.
That’s A Wrap
Wow! This 2 part series on triggers has blown my mind! I have learned so much with this concept of their use and I hope you have as well. I’d love to hear any feedback on triggers from those more experienced with them.
Explore the official MySQL 5.7 Online Manual for an in-depth overview of all topics covered in this post.
A Call To Action!
Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.
Have I mentioned how much I love a cup of coffee?!?!
To receive notifications for the latest post from “Digital Owl’s Prose” via email, please subscribe by clicking the ‘Click To Subscribe!’ button in the sidebar!
Be sure and visit the “Best Of” page for a collection of my best blog posts.
Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.
Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided are performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.