sqlpostgresqlsql-insertunnest

Insert same values for multiple records based on list of ids


I have a PostgreSQL database and want to insert the same value for multiple records based on record IDs I have.
Is there a way to make a WHERE condition in the INSERT statement? For example:

insert into Customers (new-customer) values ('t') where customer_id in (list)

Solution

  • Yes, you can do something like:

    INSERT INTO customers(customer_id, customer_name)
        select  13524, 'a customer name'
    where  13524 = ANY ('{13524,5578,79654,5920}'::BIGINT[])
    

    Here, a customer with id: 13524 will be added because it's ID is in the list: {13524,5578,79654,5920}

    I hope that what you are looking for!