|
| 1 | +# Use A Trigger To Mirror Inserts To Another Table |
| 2 | + |
| 3 | +On a PostgreSQL server, a trigger can be set up to execute a function whenever |
| 4 | +a certain action happens. In this case, I want set up a trigger to call a |
| 5 | +custom function whenever an `insert` happens on a specific table |
| 6 | +(`original_table`). That custom function will then mirror the inserted values |
| 7 | +into a secondary table (`another_table`). |
| 8 | + |
| 9 | +First, I have to create a function that will respond to `insert` operations by |
| 10 | +inserting the newly inserted rows into `another_table`. |
| 11 | + |
| 12 | +```sql |
| 13 | +create or replace function mirror_table_to_another_table() |
| 14 | + returns trigger as $mirrored_table$ |
| 15 | + begin |
| 16 | + if (TG_OP = 'insert') then |
| 17 | + insert into another_table |
| 18 | + select * from new_table; |
| 19 | + end if; |
| 20 | + return null; -- result is ignored since this is an after trigger |
| 21 | + end; |
| 22 | +$mirrored_table$ language plpgsql; |
| 23 | +``` |
| 24 | + |
| 25 | +This function can then be referenced by the trigger I set up. After any insert |
| 26 | +on the `original_table`, the function defined above will be executed. |
| 27 | + |
| 28 | +```sql |
| 29 | +create trigger mirror_table_to_another_table_trigger |
| 30 | + after insert on original_table |
| 31 | + referencing new table as new_table |
| 32 | + for each statement |
| 33 | + execute function mirror_table_to_another_table(); |
| 34 | +``` |
| 35 | + |
| 36 | +Note that I am handling inserts at a statement level and that multiple rows can |
| 37 | +be inserted in a single statement. That is why the function mirrors to the |
| 38 | +other table with `select * from new_table`. |
0 commit comments