I have a SQLite table with a Balance field that will be used as a running total. I have a trigger defined that calculates the Balance on insert of new records, but it doesn’t fire on the first insert, so the Balance in the first record is zero. All following records calculate correctly.
Current trigger definition:
CREATE TRIGGER [UpdateBalance_Insert] AFTER INSERT ON [Transaction] FOR EACH ROW BEGIN
REPLACE INTO [Transaction]
SELECT t1.[ID],
t1.[Date],
t1.[Transaction],
t1.[Debit],
t1.[Credit],
( SELECT SUM( t2.[Credit] ) - SUM( t2.[Debit] ) + new.[Credit] - new.[Debit]
FROM [Transaction] AS t2
WHERE t2.[Date] < t1.[Date] OR (
t2.[Date] = t1.[Date] AND t2.[ID] < t1.[ID] )
) AS [Balance]
FROM [Transaction] AS t1
WHERE [ID] = new.[ID];
UPDATE [Transaction]
SET [Balance] = [Balance] + new.[Credit] - new.[Debit]
WHERE [Date] > new.[Date];
END
Edit: The nature of my question changed between typing the title and typing the description. Above is my original trigger. My original question was whether a separate trigger could be created to handle the first insert only, but now I wonder if the existing trigger could be modified to perform the needed functionality.
I’d try to check if the table is empty first, and if it is, hard-code a balance. If not, i’d compute it using your algorithm.