Search code examples
sqlpostgresqlsubquerysql-insertwhere-clause

postgresql conditionnal insert values


I need a SQL which do following work.

  1. INSERT INTO table_1 (column1, column2, column3) VALUES (:1,:2, :3)
  2. This insert will only happen when another condition is TRUE, the
    condition is:
    SELECT 1 FROM table_2 WHERE column_time = 'time_stamp'

Table_1 and table_2 dont have any relation. the INSERT values to table_1 should only happen if the query on Table_2 return TRUE(1)

So i try to write my SQL as following

 INSERT INTO table_1 (column1, column2, column3) VALUES (:1,:2, :3) 
  WHERE EXISTS (SELECT 1 FROM table_2 WHERE column_time = 'time_stamp') 
  ON CONFLICT DO NOTHING

However, this SQL not work as Postgresql looks dont like the INSERT combine with WHERE condition.

BTW: the values (:1, :2:, :3) are bind array values. the final SQL looks like this:

INSERT INTO table_1 (column1, column2, column3) VALUES ('ca_1','cb_1', 'cc_1') ('ca_2','cb_2', 'cc_2') ... ('ca_n','cb_n', 'cc_n') WHERE EXISTS (SELECT 1 FROM table_2 WHERE column_time = 'my_time_stamp') ON CONFLICT DO NOTHING 

Really need help thanks.


Solution

  • You need to select those values.

    This would work in Postgres:

    INSERT INTO table_1 (column1, column2, column3) 
    SELECT :1, :2, :3
    WHERE EXISTS (SELECT 1 FROM table_2 WHERE column_time = 'time_stamp') 
    ON CONFLICT DO NOTHING
    

    Alternatively:

    INSERT INTO table_1 (column1, column2, column3) 
    SELECT x.*
    FROM (VALUES (:1, :2, :3)) AS x(column1, column2, column3)
    WHERE EXISTS (SELECT 1 FROM table_2 WHERE column_time = 'time_stamp') 
    ON CONFLICT DO NOTHING