Re: coalesce for null AND empty strings

From: Richard Huxton <dev(at)archonet(dot)com>
To: Ferdinand Gassauer <gassauer(at)kde(dot)org>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: coalesce for null AND empty strings
Date: 2007-03-30 07:30:29
Message-ID: 460CBC95.30902@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Ferdinand Gassauer wrote:
> Hi!
>
> it would be great to have a coalesce2 function which treats empty strings as
> null values.

Why? What is the use-case for this?

> as far as I have seen, there are a lot of comments and coding solutions about
> this, but none is an "easy" one and all make the code a bit more complicated
> and more difficult to maintain.
>
> I have created this function.
> It's similar to nullif, but takes only ONE argument
>
> create or replace function "empty2null"(text_i varchar)
> returns varchar as $$
> declare
> text_p varchar;
> begin
> if text_i = ''
> then text_p := null;
> else text_p := text_i;
> end if;
> return text_p;
> end;
> $$ LANGUAGE plpgsql;

or even shorter:

CREATE OR REPLACE FUNCTION empty2null(varchar) RETURNS varchar AS $$
SELECT CASE WHEN $1 = '' THEN NULL ELSE $1 END;
$$ LANGUAGE SQL;

--
Richard Huxton
Archonet Ltd

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message filippo 2007-03-30 07:31:18 stored queries and quoted strings
Previous Message Tiger Quimpo 2007-03-30 06:11:39 Re: COPY command details