software-mariodiana
4/15/2017 - 8:58 PM

An example of a PostgreSQL "Upsert" statement: meaning, if the UPDATE fails, INSERT the data.

An example of a PostgreSQL "Upsert" statement: meaning, if the UPDATE fails, INSERT the data.

-- Postgres "UPSERT" statement.
WITH upd AS (
    UPDATE my_table 
    SET os='iOS', os_version='10.3' 
    WHERE account='default' 
    RETURNING *
)
INSERT INTO my_table (
    account, os, os_version
)
SELECT 'default', 'iOS', '10.3'
WHERE NOT EXISTS (
    SELECT * FROM upd
);