Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggers are they asynchronous?

I have a table A which maintains count of total users in Table B. All I care is that the count in Table A is in sync with the number of users in the table B.

So, whenever I insert a user in Table B, I want the count to be incremented/decremented depending on insert of user or delete.

There are two ways:- a) In case I am inserting the row in Table B, I can issue the update count on Table A in one stored procedure. This result in two commands insert followed by update. Hence say take 2 secs. ( assuming each txn in 1 sec)

b) I can write the insert command in the stored procedure. Also, define a trigger which updates the count in table A after the insert in Table A is completed. To me this will only take time of 1 sec which is just inserting the row in Table B. I presume that the 'after insert trigger' which updates the count in Table B happens in the background and hence is asynchronous or non-blocking.

Is this presumption correct or shall both the approaches will take equal time.

Note: I don't care the timing of update counts in table A. Hence I am looking for a way which does the sync job in non-blocking mode like in a queue!

ANy suggestions/comments?

like image 844
Kapil D Avatar asked Jun 17 '10 19:06

Kapil D


1 Answers

No, triggers are executed absolutely synchronously in the same way a stored procedure would be. This means that if you start doing things like updating counts in triggers, you can make a simple query executed with autocommit do a lot of work in a transaction hence be very likely to deadlock. You should be aware of this.

If you don't want it synchronous, I suppose you could make it do an insert into a table of pending changes, then have an asynchronous process which updates it. This would probably avoid a lot of deadlocks in the long run (inserting into a table with no secondary indexes cannot deadlock with another insert into the same table, AFAIK)

like image 152
MarkR Avatar answered Nov 01 '22 19:11

MarkR