tags:

views:

61

answers:

3

When a trigger is better in performance? For example.

I've an insert and then an update wich counts the total rows from a table (where the insert was performed) and the save the value in another table.

But i was thinking instead run the update from the php make a trigger to perform that action.

When it's useful and when it isn't?

+3  A: 

Triggers aren't used for performance - they're used to make operations occur without using stored procedures, functions, or check constraints.

They're considered a necessary evil. Because they aren't part of the table statement, triggers are often overlooked when debugging--very irritating.

i was thinking instead run the update from the php make a trigger to perform that action.

That would be worse than performing the operation in a trigger or stored procedure because it means an additional trip from the application to the database.

OMG Ponies
Yes but he could write a trigger to do what he wants for some DBMS. I seem to recall being able to do some pretty complicated triggers with Postgresql.Actually FK contraints are triggers and I don't consider them a necessary evil. More of robust feature with some trade offs.BTW FKs contraints have usually caught prevented many bugs at least for me.
Adam Gent
@Adam Gent: I never recommend a trigger as my first option; it's a tool, like a cursor, that should only be used sparingly.
OMG Ponies
@OMG Ponies I think you pick the right solution for the right job. So in some cases it *may* be your first option.
Adam Gent
A: 

I would have to imagine the trigger is faster but I don't have raw benchmarks. The reason it would be faster is because of limiting chattiness with client.

Adam Gent
+4  A: 

Triggers and procedures can have be much faster than an external system when it comes to performance simply because they are internal to the database and therefore it does not have to send data anywhere.

Whether to use them or not and in what situations is often an architecture choice though. I.e. how maintainable are they in the over all design of the system, what if the client wants to upgrade or even change the database system.

So you first must decide on what are the priorities for the design before you can decide whether to use them. For example, if you have a large amount of data and speed is the most important issue, then triggers and procedures are likely to be a good idea. But if portability, maintainability and centralised business logic are the most important features o of the design then you most likely will not want them.

Another alternative is to look at abstractions such as hibernate to decouple the database implementation from you software.

Derek Clarkson