Search code examples
postgresqlmaxinformation-schema

Get max value of same field in all tables in schema


I have 10 tables in a schema, which all have a 'measurementdatetime' field. I'm trying to write a script which will return a row for each table showing the tablename and the max measurementdatetime for each.

I figure it should be coded something like this, but I can't figure out the exact syntax

    SELECT table_name AS table_full_name,
    MAX ( table_name || '.measurementdatetime'  ) AS max_timestamp
    FROM information_schema.tables
    WHERE table_schema = 'temp_work_w_roof'
    GROUP BY tables.table_name
    ORDER BY pg_total_relation_size('"' ||  table_name || '"') DESC

I get the 'Error relation my_tablename1 doesn't exist'

(Also: is it possible to compile this as a view? & if so how to code the preceding 'fieldnames' of the view if they're dynamic like this?)


Solution

  • You have to use the plpgsql language dynamic command, e.g.:

    create or replace function get_max_measurementdatetime()
    returns table (table_name text, max_value timestamp)
    language plpgsql as $$
    declare
        r record;
    begin
        for r in
            select i.table_name, i.table_schema
            from information_schema.tables i
            where table_schema = 'temp_work_w_roof'
            and table_type = 'BASE TABLE'
        loop
            execute format (
                'select max(measurementdatetime) from %I.%I',
                r.table_schema, r.table_name)
            into max_value;
            table_name := r.table_name;
            return next;
        end loop;
    end $$;
    
    select *
    from get_max_measurementdatetime();