Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1eyIFB-0000kE-JA for pgsql-general@arkaria.postgresql.org; Tue, 20 Mar 2018 14:28:05 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1eyIF9-00055J-SY for pgsql-general@arkaria.postgresql.org; Tue, 20 Mar 2018 14:28:03 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1eyIF9-000559-KT for pgsql-general@lists.postgresql.org; Tue, 20 Mar 2018 14:28:03 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1eyIF6-0007tH-JU for pgsql-general@postgresql.org; Tue, 20 Mar 2018 14:28:03 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id w2KERvc6011516; Tue, 20 Mar 2018 10:27:57 -0400 From: Tom Lane To: Alexander Farber cc: pgsql-general Subject: Re: You might be able to move the set-returning function into a LATERAL FROM item. In-reply-to: References: Comments: In-reply-to Alexander Farber message dated "Tue, 20 Mar 2018 10:44:31 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <11514.1521556077.1@sss.pgh.pa.us> Date: Tue, 20 Mar 2018 10:27:57 -0400 Message-ID: <11515.1521556077@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Alexander Farber writes: > I am trying to fetch a history/protocol of a game with: > SELECT > CASE WHEN JSONB_TYPEOF(tiles) = 'array' THEN > JSONB_ARRAY_ELEMENTS(tiles) ELSE NULL END AS x I think you could push the conditionality into a plpgsql function, something like (untested) create function jsonb_elements_if_array(j jsonb) returns setof jsonb as $$ begin if jsonb_typeof(j) = 'array' then return query select jsonb_array_elements(j); end if; end$$ strict immutable language plpgsql; Note that this gives *no* elements, rather than a single NULL value, if the input isn't an array --- but that seems to me to make more sense than your existing code anyhow. If you disagree, add "else return next null::jsonb". regards, tom lane