How can I return '0' from a query in pgsql if the string does not exist?

How can I return '0' from a query in pgsql if the string does not exist? how

SELECT IF EXISTS (field) THEN Field ELSE 0 FROM table

+2
source share
2 answers

I did not quite understand what result you want to get, but if you want to get the value from the field from some row in the table and 0, if there are no rows, try:

select coalesce((select field from table limit 1), 0) 

If you have a filter condition for a table that can return 1 row or nothing, try this query:

 select coalesce((select field from table where <your condition>), 0) 
+4
source
 SELECT CASE WHEN EXISTS (SELECT 1 FROM table WHERE xxx) THEN 1 ELSE 0 END 

But your question says about the existence of the field is not a line. If you just compare with NULL and think that "if it exists", it will be:

 SELECT CASE WHEN field IS NULL THEN 0 ELSE 1 END FROM table 

(And of course, if you really want a "0", just leave single quotes around the return values.

+1
source

Source: https://habr.com/ru/post/1207319/


All Articles