SQL programming / SQL performance |
Commit database changes by blocks of transaction speeds performance with some database servers.
To mimic the IBM® Informix® auto-commit behavior with an ANSI compliant RDBMS like Oracle or DB2® UDB, the database driver must perform an implicit commit after each statement execution, if the SQL statement is not inside a transaction block. This generates unnecessary database operations and can slow down big loops. To avoid this implicit commit, you can control the transaction with BEGIN WORK / COMMIT WORK around the code containing a lot of SQL statement execution.
PREPARE s FROM "INSERT INTO tab VALUES ( ?, ? )" FOR n=1 TO 100 EXECUTE s USING n, c -- Generates implicit COMMIT END FOR
You can improve performance if you put a transaction block around the loop:
PREPARE s FROM "INSERT INTO tab VALUES ( ?, ? )" BEGIN WORK FOR n=1 TO 100 EXECUTE s USING n, c -- In transaction -> no implicit COMMIT END FOR COMMIT WORK
With this code, only 1001 basic SQL operations will be executed ( 1000 inserts plus 1 commit ).
PREPARE s FROM "INSERT INTO tab VALUES ( ?, ? )" BEGIN WORK FOR n=1 TO 100 IF n MOD 10 == 0 THEN COMMIT WORK BEGIN WORK END IF EXECUTE s USING n, c -- In transaction -> no implicit COMMIT END FOR COMMIT WORK