Skip to content
Advertisement

postgres: Any way to insert multiple tables into another table in the same query?

So I have a bunch of tables and I want to insert them all into another table where all entries from the table and with a label of the name of the title of their table.

Here is a sample of what I want to be doing but with also logging in old users at the same time from an oldusers table

insert into growth_accounting_weekly (userid, week_ending, status)
    select 
        permid, 
        (select current_date - extract(dow from current_date)::integer), 
        'New' 
    from newusers,

Advertisement

Answer

UNION will to the trick. Or UNION ALL, like this:

insert into growth_accounting_weekly (userid, week_ending, status)
select 
    permid, 
    (select current_date - extract(dow from current_date)::integer), 
    'New' 
from newusers
UNION ALL
select another_id, another_number, another_status
FROM another table

Note that fields must have the same type.
Thake a look to: https://www.postgresqltutorial.com/postgresql-union/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement