Search code examples
sqlpostgresqlinsert-update

Insert Into On Conflict With a Where Clause


I have a SQL query that looks like this:

INSERT INTO testing.names
(
    id, 
    first_name,
    active_status
)
-------------------------------------
SELECT 
    stage.id,
    stage.first_name,
    stage.active_status
FROM 
    testing.name stage
    ON CONFLICT ON CONSTRAINT names_pkey DO UPDATE
SET 
    active_status = excluded.active_status
where
    active_status <> excluded.active_status

Problem: Error Message

active_status <> excluded.active_status is ambiguous.

Does anyone have a suggestion? For some reason, it says active_status is ambiguous, but only in the location of the where clause? I know I can use an alias, but I'm not sure how to in this case.


Solution

  • Looks like I can do something like this:

    INSERT INTO testing.names <place alias here>
    (
        id, 
        first_name,
        active_status
    )
    -------------------------------------
    SELECT 
        stage.id,
        stage.first_name,
        stage.active_status
    FROM 
        testing.name stage
        ON CONFLICT ON CONSTRAINT names_pkey DO UPDATE
    SET 
        active_status = excluded.active_status
    where
        <alias from insert>.active_status <> excluded.active_status