PostgreSQL: insert from another table

183,392

Solution 1

You can supply literal values in the SELECT:

INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';

A select list can contain any value expression:

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

And a string literal is certainly a value expression.

Solution 2

For referential integtity :

insert into  main_tbl (col1, ref1, ref2, createdby)
values ('col1_val',
        (select ref1 from ref1_tbl where lookup_val = 'lookup1'),
        (select ref2 from ref2_tbl where lookup_val = 'lookup2'),
        'init-load'
       );

Solution 3

Very late answer, but I think my answer is more straight forward for specific use cases where users want to simply insert (copy) data from table A into table B:

INSERT INTO table_b (col1, col2, col3, col4, col5, col6)
SELECT col1, 'str_val', int_val, col4, col5, col6
FROM table_a

Solution 4

You could use coalesce:

insert into destination select coalesce(field1,'somedata'),... from source;
Share:
183,392
Seerumi
Author by

Seerumi

Updated on July 08, 2022

Comments

  • Seerumi
    Seerumi almost 2 years

    I'm trying to insert data to a table from another table and the tables have only one column in common. The problem is, that the TABLE1 has columns that won't accept null values so I can't leave them empty and I can't get them from the TABLE2.

    I have TABLE1: id, col_1 (not null), col_2(not null), col_3 (not null)

    and TABLE2: id, col_a, col_b, col_c

    so how could I insert id from TABLE2 to TABLE1 and fill the col_1-3 with hard coded strings like "data1", "data2", "data3"?

    INSERT INTO TABLE1 (id) SELECT id FROM TABLE2 WHERE col_a = "something";
    

    will result in:

    ERROR: null value in column "col_1" violates not-null constraint

  • chomp
    chomp over 2 years
    do you know if this way of doing inserts uses multi valued inserts under the hood?
  • mu is too short
    mu is too short over 2 years
    @chomp The INSERT will be atomic either was insert into t (...) select ... or insert into t (...) values (...), (...), .... Have a look at Erwin's answer over here though.
  • hpaknia
    hpaknia over 2 years
    Is "ON CONFLICT" supported?
  • mu is too short
    mu is too short over 2 years
    @hpaknia Have you checked the documentation?