For example use Test
table with only positive id
value.
Query select 1 from public.Test where id = 0
return empty result.
But when I use this query:
select case
when exists(select 1 from public.Test where id = 0) then 'exist'
else 'not exist'
end
result is – not exist
For query:
select case when exists(select null) then 'exist' else 'not exist' end
result is – ‘exist’
And for query:
do $$
declare _query int = 7;
begin
_query:= (select 1 from public.Test where id = 0);
RAISE NOTICE '%', _query;
end;
$$;
result is – NULL
So what’s the difference between query returning empty result and null
? And why does the _query
variable for the empty query result have a null
value?
2
Answers
exists
only tests the presence of a row, not the value(s) returned by the query.In fact, the expression in the select list isn’t not even evaluated for an EXISTS operator.
You could even write
select exists (select 1/0)
without getting an error (this would return true). Althoughselect 1/0
as a standalone query would result in an error.You just want:
No extra
CASE
wrapper.EXISTS
returnstrue
/false
(nevernull
). All done.The
SELECT
list of the nested query can stay empty as it’s irrelevant toEXISTS
.That’s because "no row" is converted to a
null
value in an assignment to a scalar variable. (Feeding that query toEXISTS
converts "no row" tofalse
instead – and the existence of any rows totrue
.)