Subject: How do I upsert depending on a second table?

From: Samuel Marks <[email-masked]>
Date: Tue, 23 Sep 2025 15:36:53 -0500

Attempt:
```sql
CREATE TABLE org
(
    "name"      VARCHAR(50) PRIMARY KEY,
    owner       VARCHAR(50) NOT NULL
);

CREATE TABLE repo
(
    "id"           INTEGER PRIMARY KEY,
    full_name      VARCHAR(255) UNIQUE NOT NULL,
    org            VARCHAR(50)         NOT NULL REFERENCES org ("name")
);

INSERT INTO org(name, owner) VALUES ('org0', 'user0');

INSERT INTO repo (id, full_name, org)
VALUES (0, 'org0/name0 by wrong user', 'org0')
ON CONFLICT (full_name) DO UPDATE
    SET full_name = EXCLUDED.full_name,
        org       = EXCLUDED.org
WHERE EXISTS (SELECT 1
              FROM org org_tbl
              WHERE org_tbl.name = EXCLUDED.org
                AND org_tbl.owner = 'wrong user')
RETURNING *;

SELECT * FROM repo WHERE id = 0;
```

This all succeeds. It should fail because the 'wrong user' is trying
to create a new—or update an existing—repo.

Thanks for all suggestions

---

From: Adrian Klaver <[email-masked]>
Date: Tue, 23 Sep 2025 13:52:03 -0700

>                  AND org_tbl.owner = 'wrong user')

Where is org_tbl?

Or is this a copy and paste error?

-- 
Adrian Klaver
[email-masked]

---

From: Samuel Marks <[email-masked]>
Date: Tue, 23 Sep 2025 15:56:05 -0500

the AS syntax can alternatively be used for aliases
https://www.postgresql.org/docs/current/sql-select.html

`SELECT actual_tablename table0 WHERE table0.column00 = 1`

(I used a space)

---

From: "David G. Johnston" <[email-masked]>
Date: Tue, 23 Sep 2025 15:31:46 -0600

On Tuesday, September 23, 2025, Samuel Marks <[email-masked]> wrote:

$subject

You can only upsert/provoke a meaningful conflict on the singular table
being inserted into.

There are other features like functions and triggers that may get you
something usable.

David J.