Well, this may have point on large databases, when you need fast responce on massive DML
(INSERT / UPDATE / DELETE
).
The problem is that if you rely on database's way to ensure integrity, you hardly can optimize it.
There is also thing called SQL/PLSQL context switching
in Oracle
: if you create an empty trigger on the table, it will slow down DML
about 20 times — with the mere fact that the trigger exists.
In Oracle, when you write a ON UPDATE
trigger and update 50,000
rows in the table, the trigger and the query in it gets called 50,000
times. Foreign keys perform better, but they may also get laggy (and you can do nothing with the underlying queries)
In this case, it's better to put the results you want to update into a temporary table, issue a MERGE
, check integrity before and after, and apply the business rules. A single query that processes 50,000
rows works faster than a loop of 50,000
queries processing single row.
Of course, it's very hard to implement and only pays for itself when you have really large database and need to perform really massive updates on it.
In Oracle
, in any case, FOREING KEY
constraints perform better than tiggers implementing the same functionality.
PRIMARY KEYS
will most likely improve performance, as a primary key implies creating the UNIQUE INDEX
on the constrained field, and this index may be efficiently used in the queries. A UNIQUE INDEX
is also a natural and most efficent way to enforce uniqueness.
But of course, as any index, is slows down INSERTS
and those UPDATES
and DELETES
whose WHERE
condition is not selective.
I. e. if you need to UPDATE
or DELETE
1
row of 2,000,000
, then the index is your friend; if you need to UPDATE
or DELETE
1,500,000
rows of 2,000,000
, the index is your enemy. It's a matter of tradeoff.
You may also see my answer here.