Skip to content

Commit fb33d03

Browse files
committed
Add Use A Trigger To Mirror Inserts To Another Table as a Postgres TIL
1 parent aaa0ede commit fb33d03

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1330 TILs and counting..._
13+
_1331 TILs and counting..._
1414

1515
---
1616

@@ -740,6 +740,7 @@ _1330 TILs and counting..._
740740
- [Types By Category](postgres/types-by-category.md)
741741
- [Union All Rows Including Duplicates](postgres/union-all-rows-including-duplicates.md)
742742
- [Use A psqlrc File For Common Settings](postgres/use-a-psqlrc-file-for-common-settings.md)
743+
- [Use A Trigger To Mirror Inserts To Another Table](postgres/use-a-trigger-to-mirror-inserts-to-another-table.md)
743744
- [Use Argument Indexes](postgres/use-argument-indexes.md)
744745
- [Use Not Valid To Immediately Enforce A Constraint](postgres/use-not-valid-to-immediately-enforce-a-constraint.md)
745746
- [Use Rename To Hot Swap Two Tables](postgres/use-rename-to-hot-swap-two-tables.md)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

Comments
 (0)