Skip to content
Advertisement

Postgresql – How to insert only if specific conditions are met

I have the following table:

Currently, I’m inserting thousands of records into this table at once using the following statement:

I want to add a constraint to the insert statement, stopping new records being inserted if new.balance_one == old.balance_one AND new.balance_two == old.balance_two where old = the most recent (timestamp) record where account_id = new.account_id.

How do I do this? Insert performance is also a concern.

Advertisement

Answer

Perhaps you should take a look at ON INSERT triggers. You could create a function :

… and attach it to your table

Demo: db<>fiddle

Note: This approach will fail if you try to insert two records with the same acount_id in the same transaction, as all records in the transaction will get the same timestamp and your primary key will be violated.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement