If the below subquery finds no records it returns null and sets the action_batch_id as so. Is it possible to have the entire query fail/exit if the subquery returns no records?
UPDATE action_batch_items
SET action_batch_id = (SELECT id FROM action_batches WHERE id = '123'
AND batch_count < 1000 AND batch_size < 100000)
WHERE id = 1234567
UPDATE: Here's the structure (it's ActiveRecord)
CREATE TABLE "public"."action_batches" (
"id" int8 NOT NULL,
"action_batch_container_id" int8 NOT NULL,
"action_message" json,
"adaptor" json,
"batch_count" int4 DEFAULT 0,
"batch_size" int8 DEFAULT 0
)
CREATE TABLE "public"."action_batch_items" (
"id" int8 NOT NULL,
"action_batch_id" int8,
"config" json
)
create or replace function raise_error(text) returns int as $$
begin
raise exception '%', $1;
return -1;
end; $$ language plpgsql;
and then
action_batch_id = coalesce((select id ...), raise_error('No data'));
Try using COALESCE():
UPDATE action_batch_items
SET action_batch_id =
(
SELECT COALESCE(id, action_batch_id)
FROM action_batches
WHERE id = '123' AND batch_count < 1000 AND batch_size < 100000
)
WHERE id = 1234567
In the event that the subquery returns NULL the action_batch_id column will not be changed. In the case of the subquery returning one or more non NULL records, your UPDATE will behave as before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With