Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i return '0' from query in pgsql, if the row doesn't exist?

Tags:

postgresql

How can i return '0' from query in pgsql, if the row doesn't exist? Like

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

like image 226
dio_bless Avatar asked Aug 19 '13 08:08

dio_bless


People also ask

Does not exist in PostgreSQL?

The NOT EXISTS is opposite to EXISTS . It means that if the subquery returns no row, the NOT EXISTS returns true. If the subquery returns one or more rows, the NOT EXISTS returns false.

How do I use coalesce in PostgreSQL?

In PostgreSQL, the COALESCE function returns the first non-null argument. It is generally used with the SELECT statement to handle null values effectively. Syntax: COALESCE (argument_1, argument_2, …); The COALESCE function accepts an unlimited number of arguments.

How do you handle NULL values in PostgreSQL?

nullif also used with the coalesce function to handle the null values. PostgreSQL nullif function returns a null value if provided expressions are equal. If two expressions provided are equal, then it provides a null value; as a result, otherwise, it will return the first expression as a result.


2 Answers

I don't completely understand what result you want to get, but if you want to get value from a field from some row in a table and 0 if there's no rows, try:

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

if you have some filter condition for table which could return 1 row or nothing, try this query:

select coalesce((select field from table where <your condition>), 0)
like image 104
Roman Pekar Avatar answered Oct 17 '22 09:10

Roman Pekar


SELECT CASE WHEN EXISTS (SELECT 1 FROM table WHERE xxx) THEN 1 ELSE 0 END

But your question talks about exists on a field not on a row. If you're just comparing to NULL, and considering that "if it exists", it'd be:

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

(And of course, if you actually want '0' the string, just put single quotes around the return values.

like image 36
Magnus Hagander Avatar answered Oct 17 '22 08:10

Magnus Hagander