Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PostgreSQL EXISTS and null value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

You just want:

SELECT EXISTS(SELECT FROM public.test WHERE id = 0) AS any_matching_rows

No extra CASE wrapper. EXISTS returns true / false (never null). All done.
The SELECT list of the nested query can stay empty as it’s irrelevant to EXISTS.

And why does the _query variable for the empty query result have a null value?

That’s because "no row" is converted to a null value in an assignment to a scalar variable. (Feeding that query to EXISTS converts "no row" to false instead – and the existence of any rows to true.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading