Search code examples
postgresqlsql-insertliquibaseliquibase-sql

Liquibase insert select multiple rows postgres


I want to insert into table1 multiple rows from table2. The problem is that I have some fields in table1 that I want to compute, and some rows that I want to select from table2. For example something like this:

insert into table1 (id, selectField1, selectField2, constant)
values ((gen_random_uuid()), (select superField1 from table2), (select superField2 from table2), 'test');

So the logic is to select superField1 and superField2 from all the rows in the table2 and insert them into table1 with constant value test and generated uids. superField1 and superField2 should be from the same row in table2 when inserting in table1. How can I achieve something like this using liquibase?

P.S: I'm using <sql> tag since it's easier to implement using SQL than using XML changeset, but if you know how to do it in XML that would be appreciated too, but just in SQL will be enough too. DBMS is postgres.


Solution

  • Don't use the VALUES clause if the source is a SELECT statement:

    insert into table1 (id, selectField1, selectField2, constant)
    select gen_random_uuid(), superField1, superField2, 'test'
    from table2;