Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1j5crG-0006Gf-OW for pgsql-general@arkaria.postgresql.org; Sat, 22 Feb 2020 22:02:46 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1j5crE-0003nK-7y for pgsql-general@arkaria.postgresql.org; Sat, 22 Feb 2020 22:02:44 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1j5crD-0003nD-R2 for pgsql-general@lists.postgresql.org; Sat, 22 Feb 2020 22:02:43 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1j5cr6-00078x-B0 for pgsql-general@lists.postgresql.org; Sat, 22 Feb 2020 22:02:42 +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 01MM2XVH007427; Sat, 22 Feb 2020 17:02:33 -0500 From: Tom Lane To: Christophe Pettus cc: stan , pgsql-general@lists.postgresql.org Subject: Re: Can I trigger an action from a coalesce ? In-reply-to: <982511F6-2957-43EE-8A28-3A5541B56ADF@thebuild.com> References: <20200222210206.GA17445@panix.com> <35c60adc-3f02-13ad-a4a6-48642a1185d8@aklaver.com> <20200222213325.GA22785@panix.com> <982511F6-2957-43EE-8A28-3A5541B56ADF@thebuild.com> Comments: In-reply-to Christophe Pettus message dated "Sat, 22 Feb 2020 13:46:56 -0800" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <7425.1582408953.1@sss.pgh.pa.us> Date: Sat, 22 Feb 2020 17:02:33 -0500 Message-ID: <7426.1582408953@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Christophe Pettus writes: > Something like this: > create function supply_default() returns int as $$ > begin > raise notice 'Supplied default'; > return 1; > end; > $$ immutable language plpgsql; It's a really bad idea to mark a function that has side-effects (i.e., emitting a NOTICE) as immutable, especially if the occurrence of the side-effect at well-defined times is exactly what you're desirous of. > xof=# create table t ( i integer default supply_default(), t text ); > CREATE TABLE > xof=# insert into t(i, t) values (2, 'text'); > INSERT 0 1 > xof=# insert into t(t) values ('text'); > NOTICE: Supplied default > INSERT 0 1 Other than the mislabeled volatility, I think this will mostly work. Another possibility is to use a before-row-insert trigger that does something like if new.i is null then begin new.i := whatever; raise notice 'Supplied default'; end if; This seems cleaner in principle, but a problem is that it can't tell an inserted-by-default NULL from one that was intentionally supplied. That might be OK if you never want the field to be null anyway. regards, tom lane