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
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With