3

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
)
kreek
  • 8,774
  • 8
  • 44
  • 69
  • 1
    This might help: http://stackoverflow.com/a/8766815/1073631 -- assuming you have a field to `join` on... Does `action_batch_items` have an `action_batches_id`? – sgeddes Feb 19 '16 at 02:02
  • as i didn't get you wrong, but this query is really really weird to me. you update action_batch_id to the result of the subquery, but in your subquery, let's check it out. you select ID and where id = '123'. so no all of the result should be 123 or null? as you asked you expected 123 or no change at all? – Raffaello.D.Huke Feb 19 '16 at 02:05
  • @sgeddes it's ActiveRecord doing raw SQL but yes an action_batch_item has an action_batch_id – kreek Feb 19 '16 at 02:43
  • 2
    Your inner subquery is confusing. If you have `WHERE id = '123'` doesn't this mean that the `id` assigned to `action_batch_id` will always be `123` ? – Tim Biegeleisen Feb 19 '16 at 02:54

2 Answers2

3
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'));
Abelisto
  • 14,826
  • 2
  • 33
  • 41
1

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360