96

I'm trying to make the fastest COALESCE() that accepts two or more arguments, and returns the first non-null AND non-empty ("") value.

I'm using this:

CREATE OR REPLACE FUNCTION coalescenonempty(VARIADIC in_ordered_actual varchar[])
RETURNS varchar AS $$
  SELECT i
  FROM (SELECT unnest($1) AS i) t
  WHERE i IS NOT NULL AND i <> ''
  LIMIT 1;
$$ LANGUAGE sql;

It's pretty fast, but still nowhere as fast as COALESCE or CASE WHEN statements.

What do you think?

2
  • 1
    Don't worry about "fastest" until you get "working" - even though there is working here, keep the question open and let the answers/suggestions come in. (And maybe the "better solution" is simply to not allow empty strings in the model ;-) Mar 13, 2014 at 23:30
  • 1
    I agree with user2864740: if you want to prevent null and empty strings, why not disallow to put them into the database in the first place.
    – user330315
    Mar 13, 2014 at 23:34

1 Answer 1

164

Do not create a user function is you want speed. Instead of this:

coalescenonempty(col1,col2||'blah',col3,'none');

do this:

COALESCE(NULLIF(col1,''),NULLIF(col2||'blah',''),NULLIF(col3,''),'none');

That is, for each non-constant parameter, surround the actual parameter with NULLIF( x ,'').

1
  • Coalesce is not defined it is coming, You have any idea about this ??
    – venkat
    Mar 15, 2018 at 17:44

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.