Re: Upsert error "column reference is ambiguous"

From: Christophe Pettus <xof(at)thebuild(dot)com>
To: Tim Starling <tstarling(at)wikimedia(dot)org>
Cc: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>, pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Upsert error "column reference is ambiguous"
Date: 2025-04-28 22:58:42
Message-ID: D794C225-9F5D-4DF4-BE3F-39AD8C3430B1@thebuild.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-general

> On Apr 28, 2025, at 15:36, Tim Starling <tstarling(at)wikimedia(dot)org> wrote:
> function upsert( $table, $names, $values, $key, $set ) {
> if ( $this->type === 'mysql' ) {
> $conflict = 'ON DUPLICATE KEY UPDATE';
> } else {
> $conflict = "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=$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.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Christophe Pettus 2025-04-28 23:01:23 Re: Upsert error "column reference is ambiguous"
Previous Message Tim Starling 2025-04-28 22:48:03 Re: Upsert error "column reference is ambiguous"