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 1ik8Yg-0004na-2l for pgsql-general@arkaria.postgresql.org; Wed, 25 Dec 2019 15:26: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 1ik8Ye-0003Dc-4h for pgsql-general@arkaria.postgresql.org; Wed, 25 Dec 2019 15:26: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 1ik8Yd-0003DV-NL for pgsql-general@lists.postgresql.org; Wed, 25 Dec 2019 15:26:43 +0000 Received: from mailbackend.panix.com ([166.84.1.89]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1ik8YZ-00071G-W6 for pgsql-general@lists.postgresql.org; Wed, 25 Dec 2019 15:26:42 +0000 Received: from panix5.panix.com (panix5.panix.com [166.84.1.5]) by mailbackend.panix.com (Postfix) with ESMTP id 47jcPp39yjz15T6 for ; Wed, 25 Dec 2019 10:26:38 -0500 (EST) Received: by panix5.panix.com (Postfix, from userid 17622) id 47jcPp1bb5zfYc; Wed, 25 Dec 2019 10:26:38 -0500 (EST) Date: Wed, 25 Dec 2019 10:26:38 -0500 From: stan To: pgsql-general@lists.postgresql.org Subject: Syntax question about returning value from an insert Message-ID: <20191225152638.GA19508@panix.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline X-Editor: gVim User-Agent: Mutt/1.12.1 (2019-06-15) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk I am writing a trigger/function to make certain a default item, and its key exist when an insert is called. EG The trigger gets called on insert to T1 If column c1 is NULL in the NEW structure, I need to check table t2 to get the key associated with the default for this column. However, if the default is not yet inserted into t2, I an to go ahead and insert it. I found this page: https://stackoverflow.com/questions/6560447/can-i-use-return-value-of-insert-returning-in-another-insert which sugest this syntax: with rows as ( INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id ) INSERT INTO Table2 (val) SELECT id FROM rows I modified it slightly to look like this: IF _bom_name_key is NULL THEN with rows as ( INSERT INTO project_bom (bom_name) VALUES ('Main') RETURNING project_bom_key ) NEW.project_bom_key = SELECT project_bom_key FROM rows ; But this gives me syntax error. I realize this functionality is slightly different, but can I get the new key into the NEW structure to return from the function call? -- "They that would give up essential liberty for temporary safety deserve neither liberty nor safety." -- Benjamin Franklin