i have a table called stock_holdings which does not have data related to account_id and ticker_cd (actually it is empty):
select qty,total_amount from stock_holdings where account_id=1 and ticker_cd='XYZ';
qty | total_amount
-----+--------------
(0 rows)
however when i run the following plpgsql code block, exception should handle the situation, however i get following results:
NOTICE: before v_qty: -100
NOTICE: before v_total_amount: -1000
NOTICE: after v_qty: <NULL>
NOTICE: after v_total_amount: <NULL>
DO
Query returned successfully in 70 msec.
code block looks like this:
do
language plpgsql
$$
declare
v_qty numeric := -100;
v_total_amount numeric := -1000;
begin
raise notice 'before v_qty: %', v_qty;
raise notice 'before v_total_amount: %', v_total_amount;
SELECT qty,total_amount INTO v_qty,v_total_amount
FROM stock_holdings
WHERE account_id = 1 AND ticker_cd = 'XYZ';
raise notice 'after v_qty: %', v_qty;
raise notice 'after v_total_amount: %', v_total_amount;
exception
when NO_DATA_FOUND then
raise notice 'No data found error: %', sqlstate;
when others then
raise notice 'Other error: %', sqlstate;
end;
$$
2
Answers
For
select
to raiseNO_DATA_FOUND
you must use thestrict
option. The intent is when you expect exactly ONE row to be returned.Demonstration.
You need to use the
STRICT
keyword, otherwise the expression will set the variables toNULL
if no rows were returned by the query.eg.
See https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW
Though you could also use the special
FOUND
variable, which is set totrue
if a query returns one or more rows. If you useSTRICT
keyword, then aTOO_MANY_ROWS
exception is raised if the query returned more than one row.eg.