Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have SQL query fail if subquery returns null

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
)
like image 515
kreek Avatar asked Oct 22 '25 18:10

kreek


2 Answers

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'));
like image 128
Abelisto Avatar answered Oct 25 '25 07:10

Abelisto


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.

like image 21
Tim Biegeleisen Avatar answered Oct 25 '25 07:10

Tim Biegeleisen