4

I'm attempting to return 0.0 if the following function does not return anything:

CREATE OR REPLACE FUNCTION get_height(firstn VARCHAR, lastn VARCHAR)
  RETURNS FLOAT AS
$$
DECLARE
    height FLOAT = 0.0;
BEGIN
    SELECT into height AVG(((p.h_feet * 12) + p.h_inches) * 2.54)
    FROM player p
    WHERE p.firstname = firstn AND p.lastname = lastn; 

    RETURN height;
END;
$$ LANGUAGE plpgsql;

I've tried searching for it and found that COALESCE does not work. Does anyone have any ideas how to solve this?

Table structure:

 create table player(
                     firstname text
                    ,lastname text
                    ,h_feet INT
                    ,h_inches INT
                    );

Example data:

  insert into player values ('Jimmy','Howard',6,2);
Vivek S.
  • 19,945
  • 7
  • 68
  • 85
user3376703
  • 397
  • 1
  • 5
  • 14
  • Yeah, I do. I found out that I had renamed my function after adding COALESCE to my function and I was accidentally using the old function. I feel like an idiot. – user3376703 Apr 03 '15 at 04:54

4 Answers4

10

Explanation

The root of the problem is the fuzzy definition of "not anything".

if the following function does not return anything

NULL is not nothing, it's just unknown what it is exactly. "Nothing" in terms of SQL would rather be no row - nothing returned at all. That typically happens when no qualifying row is found. But when using aggregate functions, that cannot happen because, per documentation:

... these functions return a null value when no rows are selected.

avg() returns NULL when no rows are found (so not "nothing"). You get a row with a NULL value as result - which overwrites your init value in the code you demonstrate.

Solution

Wrap the result in COALESCE. Demonstrating a much simpler SQL function:

CREATE OR REPLACE FUNCTION get_height_sql(firstn varchar, lastn varchar)
  RETURNS float
  LANGUAGE sql STABLE AS
$func$
SELECT COALESCE(avg(((p.h_feet * 12) + p.h_inches) * 2.54)::float, 0)
FROM   player p
WHERE  p.firstname = firstn
AND    p.lastname = lastn
$func$;

db<>fiddle here
Old sqlfiddle

The same can be used in a PL/pgSQL function. This function can be STABLE, might help with performance in the context of bigger queries.

Other cases

If you actually can get no row from a query, a simple COALESCE would fail, because it's never executed.

For a single value result you can just wrap the whole query like:

SELECT COALESCE((SELECT some_float FROM ... WHERE ... LIMIT 1), 0) AS result

PL/pgSQL has the ability to check before actually returning from the function. This works for multiple rows with one or more columns, too. There is an example in the manual demonstrating the use of FOUND:

...
RETURN QUERY SELECT foo, bar ...;

IF NOT FOUND THEN
    RETURN QUERY VALUES ('foo_default'::text, 'bar_default'::text);
END IF;
...

Related:

To always return exactly one row, you can also use pure SQL:

SELECT foo, bar FROM tbl
UNION ALL
SELECT 'foo_default', 'bar_default'
LIMIT  1;

If the first SELECT returns no row, the second SELECT returns a row with defaults.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
1

Here is the script I used. As you can see I run PostgreSQL 9.4.1. I used HeidiSQL to launch the queries. Are you sure that you correctly updated your function? I just noted that you used a different function ('player_height') in a comment instead of 'get_height' in you original post.

select version();
-- PostgreSQL 9.4.1, compiled by Visual C++ build 1800, 64-bit

delimiter //

CREATE OR REPLACE FUNCTION get_height(firstn VARCHAR, lastn VARCHAR)         
RETURNS FLOAT AS $$
DECLARE
height FLOAT = 0.0;
BEGIN
    SELECT into height AVG(((p.h_feet * 12) + p.h_inches) * 2.54)
    FROM players p
    WHERE p.firstname = firstn AND p.lastname = lastn; 
        return coalesce(height, 0.0);
END;
$$ LANGUAGE plpgsql;

delimiter;

CREATE TABLE players (
     firstname varchar(40),
     lastname  varchar(40),
     h_feet int,
     h_inches int);


insert into players values ('Jimmy', 'Howard', 6, 2);

select * from get_height('Jimmy', 'Howard');
-- gives 187.96

select * from get_height('Random', 'Guy');
-- gives 0
PhillipD
  • 1,797
  • 1
  • 13
  • 23
  • I'm using postgreSQL 8.4.20 and unable to update it as this is not my server. Could this possibly be why this isn't working? – user3376703 Mar 27 '15 at 05:29
0

return coalesce(height, 0::decimal(10,2)); should do the trick

plasticide
  • 1,242
  • 9
  • 13
0

try not found condition

SELECT ... into ...
FROM ...
WHERE ...; 

if not found then
  RETURN 0;
end if;
Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191