Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to COALESCE for empty strings and NULL values?

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?

like image 502
MikeCW Avatar asked Mar 13 '14 23:03

MikeCW


People also ask

Does coalesce work with empty strings?

The Coalesce function evaluates its arguments in order and returns the first value that isn't blank or an empty string. Use this function to replace a blank value or empty string with a different value but leave non-blank and non-empty string values unchanged.

What if both values are NULL in coalesce?

If all the values in MySQL COALESCE() function are NULL then it returns NULL as the output. It means that this function does not find any non-NULL value in the list.

How do you use coalesce for NULL values in SQL?

The SQL Coalesce and IsNull functions are used to handle NULL values. During the expression evaluation process the NULL values are replaced with the user-defined value. The SQL Coalesce function evaluates the arguments in order and always returns first non-null value from the defined argument list.

Does an empty string count as NULL?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .


1 Answers

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 ,'').

like image 61
Dwayne Towell Avatar answered Sep 18 '22 15:09

Dwayne Towell