sqlpostgresqlplpgsqlpostgresql-8.3

SQL script to UNION a large number of tables


I have to do a union of a large number of disjoint daily tables from 2012-12-17 to 2012-10-30 in this example. The code for this gets ugly here is the snippet:

CREATE table map 
with (appendonly=true, compresstype = quicklz)
AS
 SELECT * FROM final_map_12_17
    UNION ALL
 SELECT * FROM final_map_12_16
    UNION ALL
     SELECT * FROM final_map_12_15
    UNION ALL
     SELECT * FROM final_map_12_14
    UNION ALL
....
SELECT * FROM final_map_10_30;

Can I do this type of thing with a sequence or PL/PGSQL function instead of writing out each individual select by hand?


Solution

  • You can loop over date range in plpgsql function like this:

    create or replace function add_map(date_from date, date_to date)
    returns void language plpgsql as $$
    declare
        day date;
    begin
        for day in 
            select generate_series(date_from, date_to, '1 day')
        loop
            execute 'insert into map select * from final_map_'|| 
                to_char(extract(month from day), '09')|| '_' || 
                to_char(extract(day from day), '09');
        end loop;
    end; $$;
    

    Calling the function:

    -- create table map (....);
    select add_map('2012-11-30', '2012-12-02');
    

    is equivalent to:

    insert into map select * from final_map_11_30;
    insert into map select * from final_map_12_01;
    insert into map select * from final_map_12_02;