首页 > 解决方案 > 哪种方法更适合 PostgreSQL 中的 UPSERT?

问题描述

在阅读如何在 PostgreSQL 中进行 UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) 之后?我很好奇哪种方法对 UPSERT 更好(更快)。

我目前正在编写一个应用程序,在大多数情况下,数据只更新(新行很少见),因此我认为最好使用这种方法而不尝试先插入(来自Postgres DOCS):

CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
    LOOP
        -- first try to update the key
        UPDATE db SET b = data WHERE a = key;
        IF found THEN
            RETURN;
        END IF;
        -- not there, so try to insert the key
        -- if someone else inserts the same key concurrently,
        -- we could get a unique-key failure
        BEGIN
            INSERT INTO db(a,b) VALUES (key, data);
            RETURN;
        EXCEPTION WHEN unique_violation THEN
            -- Do nothing, and loop to try the UPDATE again.
        END;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

还是会更好用INSERT ... ON CONFLICT DO UPDATE

标签: postgresqlinsert-updateupsertpostgresql-performancesql-merge

解决方案


推荐阅读