在PostgreSQL中哪种方法更适合UPSERT?

时间:2018-05-30 07:53:56

标签: postgresql insert-update upsert postgresql-performance sql-merge

How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?阅读后,我很好奇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

0 个答案:

没有答案