Function 2 – Computing the size of a table without locks

Here is a function that does what pg_relation_size does, more or less, without taking any locks. Because of this, it is always fast, but it may give an incorrect result if the table is being heavily altered at the same time:

CREATE OR REPLACE FUNCTION pg_relation_size_nolock(tablename regclass) RETURNS BIGINT LANGUAGE plpgsql AS $$ DECLARE     classoutput RECORD;     tsid        INTEGER;     rid         INTEGER;     dbid        INTEGER;     filepath    TEXT;     filename    TEXT;     datadir     TEXT;     i           INTEGER := 0;     tablesize   BIGINT; BEGIN     --     -- Get data directory     --     EXECUTE 'SHOW data_directory' INTO datadir;     --     -- Get relfilenode and reltablespace     --     SELECT      reltablespace as tsid     ,relfilenode as rid     INTO classoutput  FROM ...

Get PostgreSQL 10 Administration Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.