← 中文资源

简体中文版本

upsert 跳过未变化行

重放式同步要跳过数值未变化的行:DO UPDATE 的 WHERE 比较目标行与 EXCLUDED,用 IS DISTINCT FROM 保证 NULL 与 NULL 视为相等,避免制造死元组。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / UPDATE / CREATE 语句,涉及 price_feed、set、excluded.price_cents。 用到的 SQL 构件:WHERE 按条件筛出这条语句真正触碰的行;ORDER BY 固定了输出顺序;upsert 守卫(ON CONFLICT/MERGE)把插入或更新合并成一条原子语句;RETURNING 把受影响的行交回调用方;DISTINCT 折叠重复行;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;补齐缺省列的 DEFAULT 值。

常见问题

这段 SQL 会碰到哪些对象?

price_feed、set、excluded.price_cents。

核心语句

INSERT INTO price_feed AS target (sku, price_cents)
VALUES ('A-1', 1999), ('B-2', 500)
ON CONFLICT (sku) DO UPDATE
SET price_cents = EXCLUDED.price_cents,
    updated_at = now()
WHERE target.price_cents IS DISTINCT FROM EXCLUDED.price_cents
RETURNING sku, price_cents;
CREATE TABLE price_feed (
    sku text PRIMARY KEY,
    price_cents int NOT NULL,
    currency text NOT NULL DEFAULT 'USD',
    updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO price_feed (sku, price_cents) VALUES ('A-1', 1999), ('B-2', 450);

代码示例

-- A sync job replays the same prices every 5 minutes: unchanged values must not produce dead tuples,
-- otherwise autovacuum cannot keep up with the update rate and indexes keep ballooning
CREATE TABLE price_feed (
    sku text PRIMARY KEY,
    price_cents int NOT NULL,
    currency text NOT NULL DEFAULT 'USD',
    updated_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO price_feed (sku, price_cents) VALUES ('A-1', 1999), ('B-2', 450);

-- The upsert takes the DO UPDATE path, but a WHERE compares the target row with the proposed values:
-- unchanged rows skip the write and never appear in RETURNING
INSERT INTO price_feed AS target (sku, price_cents)
VALUES ('A-1', 1999), ('B-2', 500)
ON CONFLICT (sku) DO UPDATE
SET price_cents = EXCLUDED.price_cents,
    updated_at = now()
WHERE target.price_cents IS DISTINCT FROM EXCLUDED.price_cents
RETURNING sku, price_cents;

-- Verify: updated_at refreshed only for B-2; A-1 keeps its original row version
SELECT sku, price_cents, updated_at FROM price_feed ORDER BY sku;