Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1u9XRX-0033XE-SW for pgsql-general@arkaria.postgresql.org; Mon, 28 Apr 2025 22:59:20 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.94.2) (envelope-from ) id 1u9XRV-003rpu-AP for pgsql-general@arkaria.postgresql.org; Mon, 28 Apr 2025 22:59:18 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1u9XRV-003rpl-0J for pgsql-general@lists.postgresql.org; Mon, 28 Apr 2025 22:59:18 +0000 Received: from smtp92.iad3a.emailsrvr.com ([173.203.187.92]) by magus.postgresql.org with esmtps (TLS1.2) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.96) (envelope-from ) id 1u9XRT-0005GO-2C for pgsql-general@lists.postgresql.org; Mon, 28 Apr 2025 22:59:17 +0000 X-Auth-ID: xof@thebuild.com Received: by smtp12.relay.iad3a.emailsrvr.com (Authenticated sender: xof-AT-thebuild.com) with ESMTPSA id 60DCF2610A; Mon, 28 Apr 2025 18:59:13 -0400 (EDT) Content-Type: text/plain; charset=us-ascii Mime-Version: 1.0 (Mac OS X Mail 16.0 \(3776.700.51.11.1\)) Subject: Re: Upsert error "column reference is ambiguous" From: Christophe Pettus In-Reply-To: <5fe1d1c9-662e-405e-aaed-21d15bdbea06@wikimedia.org> Date: Mon, 28 Apr 2025 15:58:42 -0700 Cc: Tom Lane , pgsql-general@lists.postgresql.org Content-Transfer-Encoding: quoted-printable Message-Id: References: <697017.1745837694@sss.pgh.pa.us> <80f95342-cc09-4236-a2d7-68538fbfc41b@wikimedia.org> <774865.1745848449@sss.pgh.pa.us> <5fe1d1c9-662e-405e-aaed-21d15bdbea06@wikimedia.org> To: Tim Starling X-Mailer: Apple Mail (2.3776.700.51.11.1) X-Classification-ID: f3535ca7-5b14-4e56-b800-ae9ca7dd7624-1-1 List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk > On Apr 28, 2025, at 15:36, Tim Starling = wrote: > function upsert( $table, $names, $values, $key, $set ) { > if ( $this->type =3D=3D=3D 'mysql' ) { > $conflict =3D 'ON DUPLICATE KEY UPDATE'; > } else { > $conflict =3D "ON CONFLICT ($key) DO UPDATE SET"; > } > return $this->query( "INSERT INTO $table ($names) " . > "VALUES ($values) $conflict $set" ); I'll mention that you can do this without ON CONFLICT in PostgreSQL in a = way that, while not nearly as clean as ON CONFLICT, isn't a huge hack, = either: "DO $$ BEGIN INSERT INTO $table($names) VALUES($values); EXCEPTION WHEN = integrity_constraint_violation THEN UPDATE $table SET $set WHERE = $key=3D$values[0]; END; $$ LANGUAGE plpgsql;" It does require knowing which of the VALUES is the key value being = inserted (pseudocode syntax above), but if that is stylized to always be = the first value, that does not seem insurmountable.