Re: Using || operator to fold multiple columns into one

From: Craig Ringer <craig(at)postnewspapers(dot)com(dot)au>
To: Bryce Nesbitt <bryce2(at)obviously(dot)com>
Cc: sql pgsql <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Using || operator to fold multiple columns into one
Date: 2009-12-23 08:44:29
Message-ID: 4B31D86D.9030000@postnewspapers.com.au
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On 23/12/2009 4:34 PM, Bryce Nesbitt wrote:
> Dear experts,
>
> This point is confusing me with the || operator. I've got a table with
> "one column per data type", like so:

Dare I ask why? What problem are you trying to solve by doing this?

> # select context_key,keyname,t_number||t_string||t_date||t_boolean as
> value from context_keyvals;
>
> But it is not working, the columns always come up empty.

Here's why:

psql> SELECT ('TEST'||NULL) IS NULL;

?column?
t
--------
(1 row)

`||' applied to anything and null returns null, since it is unknown what
the "null" part of the expression. It makes sense if you think of null
as "unknown" or "undefined".

In your case, you should probably typecast each field to `text' and use
`coalesce' to show the first non-null one. Alternately, you could use a
CASE statement, eg:

SELECT COALESCE( t_number::text, t:string::text, t_date::text,
t_boolean::text) AS value;

Also: You do have a CHECK constraint on the table that asserts that at
most one of those entries may be non-null, right? If not, you're very
likely to land up with entries with more than one t_something non-null
sooner or later so I suggest adding one.

--
Craig Ringer

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message A. Kretschmer 2009-12-23 08:50:31 Re: Using || operator to fold multiple columns into one
Previous Message Bryce Nesbitt 2009-12-23 08:34:33 Using || operator to fold multiple columns into one