Re: Find NOT NULLs in a group of 20 columns

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: gvim <gvimrc(at)gmail(dot)com>
Cc: pgsql sql <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Find NOT NULLs in a group of 20 columns
Date: 2011-01-11 02:45:50
Message-ID: 5647.1294713950@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

gvim <gvimrc(at)gmail(dot)com> writes:
> I'm struggling to find anything other than a complex stored proc to do this:
> Out of a group of 20 columns return the rows in which:

> 1. Only 1 of the 20 columns IS NOT NULL
> 2. More than 1 of the 20 columns IS NOT NULL

> Any ideas?

Cast to int and add up?

SELECT ... WHERE
((col1 is not null)::int +
(col2 is not null)::int + ...
(col20 is not null)::int) = 1 -- or > 1

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Amar Dhole 2011-01-11 12:17:55 help needs in converting db2 function in postgresql.
Previous Message gvim 2011-01-11 02:14:12 Find NOT NULLs in a group of 20 columns