How to Use the Complete Functionalities of the pg_ivm Extension in PostgreSQL

Incrementally maintaining a materialized view is often more efficient than rebuilding it every time the underlying data changes. The pg_ivm extension brings this capability to PostgreSQL by automatically updating eligible materialized views whenever the base tables are modified.

This article explains how to install and configure the extension, create Incrementally Maintainable Materialized Views (IMMVs), and explore the functions and catalog objects provided by pg_ivm. Each example is demonstrated with the proper SQL queries so you can understand how incremental view maintenance works in practice.

Clone the repository

git clone https://github.com/sraoss/pg_ivm.git

Change the directory

cd pg_ivm

Check the contents inside the pg_ivm folder to ensure that the cloning was performed correctly

cybrosys@cybrosys:~/pg_ivm$ ls

Result:

createas.bc  Makefile     pg_ivm--1.0--1.1.sql    pg_ivm--1.1--1.2.sql    pg_ivm--1.16--1.17.sql  pg_ivm--1.6--1.7.sql   pg_ivm.c        README.md       ruleutils.c  subselect.bc
createas.c   matview.bc   pg_ivm--1.0.sql         pg_ivm--1.12--1.13.sql  pg_ivm--1.2--1.3.sql    pg_ivm--1.7--1.8.sql   pg_ivm.control  rpm             ruleutils.o  subselect.c
createas.o   matview.c    pg_ivm--1.10--1.11.sql  pg_ivm--1.13--1.14.sql  pg_ivm--1.3--1.4.sql    pg_ivm--1.8--1.9.sql   pg_ivm.h        ruleutils_13.c  scripts      subselect.o
expected     matview.o    pg_ivm--1.10.sql        pg_ivm--1.14--1.15.sql  pg_ivm--1.4--1.5.sql    pg_ivm--1.9--1.10.sql  pg_ivm.o        ruleutils_14.c  specs
LICENSE      meson.build  pg_ivm--1.11--1.12.sql  pg_ivm--1.15--1.16.sql  pg_ivm--1.5--1.6.sql    pg_ivm.bc              pg_ivm.so       ruleutils.bc    sql

Now, compile this against the system-installed Postgres

make USE_PGXS=1 PG_CONFIG=/usr/lib/postgresql/18/bin/pg_config

Now, install this extension

sudo make USE_PGXS=1 PG_CONFIG=/usr/lib/postgresql/18/bin/pg_config install

Here, we are using PostgreSQL version 18; that’s why we specified the pg_config version of 18.

Now, check whether the extension is available to create or not.

select * from pg_available_extensions where name = 'pg_ivm';

Result:

  name  | default_version | installed_version |                  comment                   
--------+-----------------+-------------------+--------------------------------------------
 pg_ivm | 1.17            |                   | incremental view maintenance on PostgreSQL
(1 row)

Now, create the extension.

 create extension pg_ivm ;

Result:

CREATE EXTENSION

Check the installed version.

 select * from pg_available_extensions where name = 'pg_ivm';

Result:

  name  | default_version | installed_version |                  comment                   
--------+-----------------+-------------------+--------------------------------------------
 pg_ivm | 1.17            | 1.17              | incremental view maintenance on PostgreSQL
(1 row)

Check the functionalities of the pg_ivm extension by using the command like this.

 \dx+ pg_ivm

Result:

             Objects in extension "pg_ivm"
                   Object description                   
--------------------------------------------------------
 function pgivm.create_immv(text,text)
 function pgivm.get_create_immv_commands()
 function pgivm.get_immv_def(regclass)
 function pgivm.get_restore_immv_commands(boolean)
 function pgivm."IVM_immediate_before"()
 function pgivm."IVM_immediate_maintenance"()
 function pgivm."IVM_prevent_immv_change"()
 function pgivm.ivm_visible_in_prestate(oid,tid,oid)
 function pgivm.refresh_immv(text,boolean)
 function pgivm.restore_immv(text,text,boolean,boolean)
 schema pgivm
 table pgivm.pg_ivm_immv
 type pgivm.pg_ivm_immv
 type pgivm.pg_ivm_immv[]
(14 rows)

Now, create some sample tables to understand how pg_ivm works in postgres.

CREATE TABLE customers

(
    customer_id SERIAL PRIMARY KEY,
    customer_name TEXT,
    city TEXT
);
CREATE TABLE orders
(
    order_id SERIAL PRIMARY KEY,
    customer_id INT REFERENCES customers(customer_id),
    order_date DATE,
    amount NUMERIC(10,2)
);
CREATE TABLE order_items
(
    item_id SERIAL PRIMARY KEY,
    order_id INT REFERENCES orders(order_id),
    product TEXT,
    quantity INT,
    price NUMERIC(10,2)
);

Insert some sample values.

INSERT INTO customers(customer_name,city)
VALUES
('Alice','London'),
('Bob','Paris'),
('Charlie','Tokyo');
INSERT INTO orders(customer_id,order_date,amount)
VALUES
(1,'2026-01-01',200),
(1,'2026-01-05',300),
(2,'2026-01-08',150),
(3,'2026-01-10',500);
INSERT INTO order_items(order_id,product,quantity,price)
VALUES
(1,'Keyboard',2,50),
(1,'Mouse',1,20),
(2,'Laptop',1,300),
(3,'Monitor',2,75),
(4,'Printer',1,500);

Create a materialized view using the functionalities of the pg_ivm extension named pgivm.create_immv like this.

Check the function definition like this.

\df+ pgivm.create_immv

Result:

List of functions
-[ RECORD 1 ]-------+--------------------------------
Schema              | pgivm
Name                | create_immv
Result data type    | bigint
Argument data types | immv text, view_definition text
Type                | func
Volatility          | volatile
Parallel            | unsafe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | c
Internal name       | create_immv
Description         | 

Create a materialized view like this.

SELECT pgivm.create_immv(
'customer_orders',
'
SELECT
    c.customer_id,
    c.customer_name,
    o.order_id,
    o.amount
FROM customers c
JOIN orders o
ON c.customer_id=o.customer_id
');

Result:

NOTICE:  created index "customer_orders_index" on immv "customer_orders"
 create_immv 
-------------
           4
(1 row)

Here, we pass 2 arguments:

  • The first argument specifies the name of the materialized view
  • The second argument specifies the query for that materialized view.

Now, query the result directly from the materialized view table.

SELECT * FROM customer_orders;

Result:

 customer_id | customer_name | order_id | amount 
-------------+---------------+----------+--------
           1 | Alice         |        1 | 200.00
           1 | Alice         |        2 | 300.00
           2 | Bob           |        3 | 150.00
           3 | Charlie       |        4 | 500.00
(4 rows)

Check the metadata stored in the pg_ivm_immv table like this.

select * from pgivm.pg_ivm_immv ;

Result:

------------------------------------------------------------------------------------------------------------------------------------------------------------------------
immvrelid     | customer_orders
viewdef       | {QUERY :commandType 1 :querySource 0 :canSetTag true :utilityStmt <> :resultRelation 0 :hasAggs false :hasWindowFuncs false :hasTargetSRFs false :hasSubLinks false :hasDistinctOn false :hasRecursive false :hasModifyingCTE false :hasForUpdate false :hasRowSecurity false :hasGroupRTE false :isReturn false :cteList <> :rtable ({RANGETBLENTRY :alias {ALIAS :aliasname c :colnames <>} :eref {ALIAS :aliasname c :colnames ("customer_id" "customer_name" "city")} :rtekind 0 :relid 200060 :inh true :relkind r :rellockmode 1 :perminfoindex 1 :tablesample <> :lateral false :inFromCl true :securityQuals <>} {RANGETBLENTRY :alias {ALIAS :aliasname o :colnames <>} :eref {ALIAS :aliasname o :colnames ("order_id" "customer_id" "order_date" "amount")} :rtekind 0 :relid 200070 :inh true :relkind r :rellockmode 1 :perminfoindex 2 :tablesample <> :lateral false :inFromCl true :securityQuals <>} {RANGETBLENTRY :alias <> :eref {ALIAS :aliasname unnamed_join :colnames ("customer_id" "customer_name" "city" "order_id" "customer_id" "order_date" "amount")} :rtekind 2 :jointype 0 :joinmergedcols 0 :joinaliasvars ({VAR :varno 1 :varattno 1 :vartype 23 :vartypmod -1 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 1 :varattnosyn 1 :location -1} {VAR :varno 1 :varattno 2 :vartype 25 :vartypmod -1 :varcollid 100 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 1 :varattnosyn 2 :location -1} {VAR :varno 1 :varattno 3 :vartype 25 :vartypmod -1 :varcollid 100 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 1 :varattnosyn 3 :location -1} {VAR :varno 2 :varattno 1 :vartype 23 :vartypmod -1 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 2 :varattnosyn 1 :location -1} {VAR :varno 2 :varattno 2 :vartype 23 :vartypmod -1 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 2 :varattnosyn 2 :location -1} {VAR :varno 2 :varattno 3 :vartype 1082 :vartypmod -1 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 2 :varattnosyn 3 :location -1} {VAR :varno 2 :varattno 4 :vartype 1700 :vartypmod 655366 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 2 :varattnosyn 4 :location -1}) :joinleftcols (i 1 2 3) :joinrightcols (i 1 2 3 4) :join_using_alias <> :lateral false :inFromCl true :securityQuals <>}) :rteperminfos ({RTEPERMISSIONINFO :relid 200060 :inh true :requiredPerms 2 :checkAsUser 0 :selectedCols (b 8 9) :insertedCols (b) :updatedCols (b)} {RTEPERMISSIONINFO :relid 200070 :inh true :requiredPerms 2 :checkAsUser 0 :selectedCols (b 8 9 11) :insertedCols (b) :updatedCols (b)}) :jointree {FROMEXPR :fromlist ({JOINEXPR :jointype 0 :isNatural false :larg {RANGETBLREF :rtindex 1} :rarg {RANGETBLREF :rtindex 2} :usingClause <> :join_using_alias <> :quals {OPEXPR :opno 96 :opfuncid 65 :opresulttype 16 :opretset false :opcollid 0 :inputcollid 0 :args ({VAR :varno 1 :varattno 1 :vartype 23 :vartypmod -1 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 1 :varattnosyn 1 :location -1} {VAR :varno 2 :varattno 2 :vartype 23 :vartypmod -1 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 2 :varattnosyn 2 :location -1}) :location -1} :alias <> :rtindex 3}) :quals <>} :mergeActionList <> :mergeTargetRelation 0 :mergeJoinCondition <> :targetList ({TARGETENTRY :expr {VAR :varno 1 :varattno 1 :vartype 23 :vartypmod -1 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 1 :varattnosyn 1 :location -1} :resno 1 :resname customer_id :ressortgroupref 0 :resorigtbl 200060 :resorigcol 1 :resjunk false} {TARGETENTRY :expr {VAR :varno 1 :varattno 2 :vartype 25 :vartypmod -1 :varcollid 100 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 1 :varattnosyn 2 :location -1} :resno 2 :resname customer_name :ressortgroupref 0 :resorigtbl 200060 :resorigcol 2 :resjunk false} {TARGETENTRY :expr {VAR :varno 2 :varattno 1 :vartype 23 :vartypmod -1 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 2 :varattnosyn 1 :location -1} :resno 3 :resname order_id :ressortgroupref 0 :resorigtbl 200070 :resorigcol 1 :resjunk false} {TARGETENTRY :expr {VAR :varno 2 :varattno 4 :vartype 1700 :vartypmod 655366 :varcollid 0 :varnullingrels (b) :varlevelsup 0 :varreturningtype 0 :varnosyn 2 :varattnosyn 4 :location -1} :resno 4 :resname amount :ressortgroupref 0 :resorigtbl 200070 :resorigcol 4 :resjunk false}) :override 0 :onConflict <> :returningOldAlias <> :returningNewAlias <> :returningList <> :groupClause <> :groupDistinct false :groupingSets <> :havingQual <> :windowClause <> :distinctClause <> :sortClause <> :limitOffset <> :limitCount <> :limitOption 0 :rowMarks <> :setOperations <> :constraintDeps <> :withCheckOptions <> :stmt_location -1 :stmt_len -1}
ispopulated   | t
lastivmupdate | 
ColumnPurpose
immvrelidThe OID of the IMMV that pg_ivm manages (e.g., customer_orders).
viewdefThe internal PostgreSQL parse tree of the IMMV's defining SELECT query, used by pg_ivm to reconstruct the query during refresh, restore, and incremental maintenance.
ispopulatedIndicates whether the IMMV currently contains valid data (true) or is unpopulated (false).
lastivmupdateStores the timestamp of the last incremental maintenance operation performed on the IMMV. NULL means no incremental update has been recorded yet (for example, the IMMV has only been created or fully refreshed).

Check the results from the materialized view based on the sorting of order_id.

 SELECT *
FROM customer_orders
ORDER BY order_id;

Result:

 customer_id | customer_name | order_id | amount 
-------------+---------------+----------+--------
           1 | Alice         |        1 | 200.00
           1 | Alice         |        2 | 300.00
           2 | Bob           |        3 | 150.00
           3 | Charlie       |        4 | 500.00
(4 rows)

Check the results from the table named orders.

select * from orders;

Result:

 order_id | customer_id | order_date | amount 
----------+-------------+------------+--------
        1 |           1 | 2026-01-01 | 200.00
        2 |           1 | 2026-01-05 | 300.00
        3 |           2 | 2026-01-08 | 150.00
        4 |           3 | 2026-01-10 | 500.00
(4 rows)

Now, insert one new record into the base table like this.

INSERT INTO orders(customer_id,order_date,amount)
VALUES
(2,'2026-02-01',600);

Check the records again in the table named orders.

select * from orders;

Result:

 order_id | customer_id | order_date | amount 
----------+-------------+------------+--------
        1 |           1 | 2026-01-01 | 200.00
        2 |           1 | 2026-01-05 | 300.00
        3 |           2 | 2026-01-08 | 150.00
        4 |           3 | 2026-01-10 | 500.00
        5 |           2 | 2026-02-01 | 600.00
(5 rows)

Now check the results from the materialized view again.

 SELECT *
FROM customer_orders
ORDER BY order_id;

Result:

 customer_id | customer_name | order_id | amount 
-------------+---------------+----------+--------
           1 | Alice         |        1 | 200.00
           1 | Alice         |        2 | 300.00
           2 | Bob           |        3 | 150.00
           3 | Charlie       |        4 | 500.00
           2 | Bob           |        5 | 600.00
(5 rows)

Now, we can see that the materialized view contains the latest added data without manual refresh.

Check the results from the materialized view table where the order_id is 1.

 SELECT *
FROM customer_orders
WHERE order_id=1;

Result:

 customer_id | customer_name | order_id | amount 
-------------+---------------+----------+--------
           1 | Alice         |        1 | 200.00
(1 row)

Now, update that record in the base table to set the value of amount to 999.

 UPDATE orders
SET amount=999
WHERE order_id=1;

Result:

UPDATE 1

Now, check the same record from the matview again.

 SELECT *
FROM customer_orders
WHERE order_id=1;

Result:

 customer_id | customer_name | order_id | amount 
-------------+---------------+----------+--------
           1 | Alice         |        1 | 999.00
(1 row)

Now, we can see that the updated value is also reflected in the mat view without manual refreshing.

We can get the mat view commands that are used to create by using the function named get_create_immv_commands.

Check the function definition like this.

\df+ pgivm.get_create_immv_commands

Result:

List of functions
-[ RECORD 1 ]-------+-------------------------
Schema              | pgivm
Name                | get_create_immv_commands
Result data type    | SETOF text
Argument data types | 
Type                | func
Volatility          | volatile
Parallel            | unsafe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | sql
Internal name       | 
Description         | 

Now, use this function and check its result.

select pgivm.get_create_immv_commands();

Result:

                     get_create_immv_commands                     
------------------------------------------------------------------
 SELECT pgivm.create_immv(                                       +
     immv => 'public.customer_orders',                           +
     view_definition => ' SELECT c.customer_id,                  +
     c.customer_name,                                            +
     o.order_id,                                                 +
     o.amount                                                    +
    FROM (public.customers c                                     +
      JOIN public.orders o ON ((c.customer_id = o.customer_id)))'+
 );
(1 row)

We can also get the specific mat view definition by using the function named pgivm.get_immv_def.

Check the function definition like this.

\df+ pgivm.get_immv_def

Result:

List of functions
-[ RECORD 1 ]-------+-------------------
Schema              | pgivm
Name                | get_immv_def
Result data type    | text
Argument data types | immvrelid regclass
Type                | func
Volatility          | volatile
Parallel            | unsafe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | c
Internal name       | get_immv_def
Description         | 

Check a specific mat view definition like this

select pgivm.get_immv_def('customer_orders'::regclass);

Result:

                       get_immv_def                       
----------------------------------------------------------
  SELECT c.customer_id,                                  +
     c.customer_name,                                    +
     o.order_id,                                         +
     o.amount                                            +
    FROM (customers c                                    +
      JOIN orders o ON ((c.customer_id = o.customer_id)))
(1 row)

The next function is pgivm.get_restore_immv_commands.

It generates SQL restore_immv() statements for all registered IMMVs, which can be executed later to restore the pg_ivm metadata after the execution of backup/restore or pg_upgrade.

Check the definition of this function named pgivm.get_restore_immv_commands

\df+  pgivm.get_restore_immv_commands

Result:

List of functions
-[ RECORD 1 ]-------+------------------------------
Schema              | pgivm
Name                | get_restore_immv_commands
Result data type    | SETOF text
Argument data types | replace boolean DEFAULT false
Type                | func
Volatility          | volatile
Parallel            | unsafe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | sql
Internal name       | 
Description         | 

Use this function to get the restore immv commands like this.

select pgivm.get_restore_immv_commands();

Result:

                     get_restore_immv_commands                     
-------------------------------------------------------------------
 SELECT pgivm.restore_immv(                                       +
     immv => 'public.customer_orders',                            +
     view_definition => ' SELECT c.customer_id,                   +
     c.customer_name,                                             +
     o.order_id,                                                  +
     o.amount                                                     +
    FROM (public.customers c                                      +
      JOIN public.orders o ON ((c.customer_id = o.customer_id)))',+
     replace => false                                             +
 );
(1 row)

Now, pass true to this function and check the result.

select pgivm.get_restore_immv_commands(true);

Result:

                     get_restore_immv_commands                     
-------------------------------------------------------------------
 SELECT pgivm.restore_immv(                                       +
     immv => 'public.customer_orders',                            +
     view_definition => ' SELECT c.customer_id,                   +
     c.customer_name,                                             +
     o.order_id,                                                  +
     o.amount                                                     +
    FROM (public.customers c                                      +
      JOIN public.orders o ON ((c.customer_id = o.customer_id)))',+
     replace => true                                              +
 );
(1 row)

Here, it returns the mat view name, the mat view definition, and a boolean keyword named replace.

The replace parameter controls what restore_immv() should do if the IMMV is already registered in pg_ivm's metadata.

The next three functions are the internal functions of the pg_ivm extension, and we cannot use them directly.

function pgivm."IVM_immediate_before"()

Checking the function definition.

 \df+ pgivm."IVM_immediate_before"

Result:

List of functions
-[ RECORD 1 ]-------+---------------------
Schema              | pgivm
Name                | IVM_immediate_before
Result data type    | trigger
Argument data types | 
Type                | func
Volatility          | volatile
Parallel            | unsafe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | c
Internal name       | IVM_immediate_before
Description         | 

function pgivm."IVM_immediate_maintenance"()

Checking the function definition.

 \df+ pgivm."IVM_immediate_maintenance"

Result:

List of functions
-[ RECORD 1 ]-------+--------------------------
Schema              | pgivm
Name                | IVM_immediate_maintenance
Result data type    | trigger
Argument data types | 
Type                | func
Volatility          | volatile
Parallel            | unsafe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | c
Internal name       | IVM_immediate_maintenance
Description         | 

function pgivm."IVM_prevent_immv_change"()

These three functions are internal functions, and both act like triggers that are created on the base tables when we create a materialized view.

Check the triggers whose names start with pg_ivm like this.

 SELECT
    tgname,
    tgrelid::regclass AS table_name,
    tgfoid::regprocedure
FROM pg_trigger
WHERE tgfoid::regprocedure::text LIKE 'pgivm.%';

Result:

               tgname               |   table_name    |               tgfoid                
------------------------------------+-----------------+-------------------------------------
 IVM_trigger_ins_before_208269      | customers       | pgivm."IVM_immediate_before"()
 IVM_trigger_del_before_208270      | customers       | pgivm."IVM_immediate_before"()
 IVM_trigger_upd_before_208271      | customers       | pgivm."IVM_immediate_before"()
 IVM_trigger_truncate_before_208272 | customers       | pgivm."IVM_immediate_before"()
 IVM_trigger_ins_after_208273       | customers       | pgivm."IVM_immediate_maintenance"()
 IVM_trigger_del_after_208274       | customers       | pgivm."IVM_immediate_maintenance"()
 IVM_trigger_upd_after_208275       | customers       | pgivm."IVM_immediate_maintenance"()
 IVM_trigger_truncate_after_208276  | customers       | pgivm."IVM_immediate_maintenance"()
 IVM_trigger_ins_before_208277      | orders          | pgivm."IVM_immediate_before"()
 IVM_trigger_del_before_208278      | orders          | pgivm."IVM_immediate_before"()
 IVM_trigger_upd_before_208279      | orders          | pgivm."IVM_immediate_before"()
 IVM_trigger_truncate_before_208280 | orders          | pgivm."IVM_immediate_before"()
 IVM_trigger_ins_after_208281       | orders          | pgivm."IVM_immediate_maintenance"()
 IVM_trigger_del_after_208282       | orders          | pgivm."IVM_immediate_maintenance"()
 IVM_trigger_upd_after_208283       | orders          | pgivm."IVM_immediate_maintenance"()
 IVM_trigger_truncate_after_208284  | orders          | pgivm."IVM_immediate_maintenance"()
 IVM_prevent_immv_change_208291     | customer_orders | pgivm."IVM_prevent_immv_change"()
 IVM_prevent_immv_change_208292     | customer_orders | pgivm."IVM_prevent_immv_change"()
 IVM_prevent_immv_change_208293     | customer_orders | pgivm."IVM_prevent_immv_change"()
 IVM_prevent_immv_change_208294     | customer_orders | pgivm."IVM_prevent_immv_change"()
(20 rows)

Now we can see these triggers are created on the base tables that were related to the materialized view.

Now we can also do the manual refresh inside the pg_ivm extension by using the function named pgivm.refresh_immv.

Check the records from the mat view.

 SELECT * FROM customer_orders;

Result :

 customer_id | customer_name | order_id | amount 
-------------+---------------+----------+--------
           1 | Alice         |        2 | 300.00
           2 | Bob           |        3 | 150.00
           3 | Charlie       |        4 | 500.00
           2 | Bob           |        5 | 600.00
           1 | Alice         |        1 | 999.00
(5 rows)

Check the records from the base table named orders.

select * from orders;

Result :

 order_id | customer_id | order_date | amount 
----------+-------------+------------+--------
        2 |           1 | 2026-01-05 | 300.00
        3 |           2 | 2026-01-08 | 150.00
        4 |           3 | 2026-01-10 | 500.00
        5 |           2 | 2026-02-01 | 600.00
        1 |           1 | 2026-01-01 | 999.00
(5 rows)

Insert a new record into the orders table.

INSERT INTO orders VALUES
(103, 1, '2026-02-15', 900.00);

Now, we can execute a manual refresh on materialized view like this.

 SELECT pgivm.refresh_immv(
    'customer_orders',
    true
);

Result:

 refresh_immv 
--------------
            6
(1 row)

Check the records from the mat view again.

SELECT * FROM customer_orders
ORDER BY order_id;

Result:

 customer_id | customer_name | order_id | amount 
-------------+---------------+----------+--------
           1 | Alice         |        1 | 999.00
           1 | Alice         |        2 | 300.00
           2 | Bob           |        3 | 150.00
           3 | Charlie       |        4 | 500.00
           2 | Bob           |        5 | 600.00
           1 | Alice         |      103 | 900.00
(6 rows)

Now, we can see the latest added value in the base table named orders, which is correctly added in the mat view.

The next function is pgivm.restore_immv. It restores or re-registers an Incrementally Maintainable Materialized View (IMMV) by recreating its pg_ivm metadata and maintenance triggers from the original view definition, typically after a database restore or a postgressql upgrade.

function pgivm.restore_immv(text,text,boolean,boolean)

Check the definition of this function like this.

\df+ pgivm.restore_immv

Result:

List of functions
-[ RECORD 1 ]-------+-----------------------------------------------------------------------------------------------
Schema              | pgivm
Name                | restore_immv
Result data type    | void
Argument data types | immv text, view_definition text, populate boolean DEFAULT false, replace boolean DEFAULT false
Type                | func
Volatility          | volatile
Parallel            | unsafe
Owner               | postgres
Security            | invoker
Leakproof?          | no
Access privileges   | 
Language            | c
Internal name       | restore_immv
Description         | 

The pg_ivm extension provides an efficient way to keep supported materialized views synchronized with their base tables without requiring a complete refresh after every data modification.

By understanding how to create IMMVs, monitor their metadata, refresh them when needed, and use the available utility functions, you can simplify data maintenance while improving performance for suitable workloads. With the examples covered in this guide, you should have a solid foundation for exploring and using incremental view maintenance in PostgreSQL.

WhatsApp