Question

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)
Was it helpful?

Solution 2

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!

OTHER TIPS

To insert a row for every id in your list, you can use unnest() to produce a set of rows:

INSERT INTO customers(customer_id, column1)
SELECT id, 't'
FROM   unnest ('{123,456,789}'::int[]) id;

If you misspoke and actually meant to UPDATE existing rows:

UPDATE customers
SET    column1 = 't'
WHERE  customer_id = ANY ('{123,456,789}'::int[]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top