MySQL triggers

December 8th, 2006. Tagged: mysql

Now that even my favourite $50/year web hosts (example) are offering MySQL 5 and even recommending it over 4, why not take advantage of MySQL's "enterprise" features. Like triggers. OK, what's a trigger? It's something that happens as a result of something else. Clear? Yeah, maybe an example.

Say, as it often happens in life, you insert a row into a table. If there is a trigger that "listens" to inserts on this table, it will be, well... triggered.

Quick example. You have a blog app and a `blog` database that has a table called `posts`. You want to show some stats, like the total number of posts. Instead of using some (potentially heavy) queries that include some COUNT()-ing and SUM()-ing, you can "cache" the stats for faster display. So you create a table called `stats`. Let's see.

C:\\Development\\Apache\\MySQL\\bin>mysql -u root -p
Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 240 to server version: 5.0.27-community-nt

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> \u blog
Database changed
| Tables_in_blog |
| posts          |
| stats          |
2 rows in set (0.00 sec)

mysql> SHOW COLUMNS FROM posts;
| Field | Type             | Null | Key | Default | Extra          |
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| title | varchar(255)     | NO   |     |         |                |
| body  | text             | NO   |     |         |                |
3 rows in set (0.00 sec)

mysql> SHOW COLUMNS FROM stats;
| Field | Type        | Null | Key | Default | Extra |
| key   | varchar(50) | NO   | PRI |         |       |
| value | int(11)     | NO   |     |         |       |
2 rows in set (0.00 sec)


So far, so good. Initializing the stats...

mysql> INSERT INTO stats VALUES ('posts', 0);
Query OK, 1 row affected (0.02 sec)

Let's create the trigger!

mysql> CREATE TRIGGER mytrigger
    -> AFTER INSERT ON posts
    -> UPDATE stats SET `value` = `value` + 1 WHERE `key` = 'posts';
Query OK, 0 rows affected (0.01 sec)

What does it mean? Well, after each row INSERT-ed in `posts`, it will update the `stats` table, incrementing the total number of posts. Does it work? But of course!

mysql> INSERT INTO posts VALUES ('', 'title1', 'body1');
Query OK, 1 row affected, 1 warning (0.04 sec)

mysql> INSERT INTO posts VALUES ('', 'title2', 'body2');
Query OK, 1 row affected, 1 warning (0.02 sec)

mysql> SELECT * FROM stats;
| key   | value |
| posts |     2 |
1 row in set (0.00 sec)

mysql> ha-haaaa!

To display the triggers you've created, use the SHOW TRIGGERS statement, as described in the MySQL manual. More on the triggers - using triggers, CREATE TRIGGER syntax

Tell your friends about this post: Facebook, Twitter, Google+

7 Responses

  1. Доста интересно, ще го включа в един настоящ проект, но все още доста хостове не са ъпгрейднали към версия 5 за жалост

  2. Awesome. I’ll definitely use this.

  3. [...] In a previous post about the MySQL triggers, I mentioned that inexpensive web hosts are now offering MySQL 5. This was based on ICDsoft’s hosting plan, this is a (highly recommended, awesome support!) company I’ve been using for years and I was thinking that it represents the avegarge $50-60/year web hosting solutions offered worldwide, which is what most people use when they start a web site. [...]

  4. [...] Continuing (from here) the “Discover MySQL’s enterprise features” trip, let’s check out the Views. [...]

  5. [...] The journey “Fall in love with MySQL (again)” continues from here (triggers) and here (views). Next stop – MySQL events. [...]

  6. [...] MySQL triggers, case study. [...]

  7. this is what i was looking for…many thanks

Leave a Reply