From: | Condor <condor(at)stz-bg(dot)com> |
---|---|
To: | pgsql-general(at)lists(dot)postgresql(dot)org |
Subject: | How to avoid UPDATE on same data in table ? |
Date: | 2020-02-02 09:24:02 |
Message-ID: | 1a25799e60c79c65575f6e6375c96a52@stz-bg.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
Hello,
I'm using PostgreSQL 12.1 and trying to avoid update on table when data
is the same. I read somewhere if UPDATE is with the same data SQL server
on system level does not do update on table but don't know if that is
true or not. If that is not true I do:
First I create a function that should update data:
CREATE OR REPLACE FUNCTION log_last_chaged() RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
UPDATE status_table SET status0 = NEW.status0, lastchage =
CURRENT_TIMESTAMP WHERE rowid = OLD.rowid;
RETURN NEW;
END
$$;
then create table:
CREATE TABLE status_table (
rowid INTEGER,
status0 INTEGER,
lastchage TIMESTAMP(0) WITHOUT TIME ZONE
);
attach trigger:
DROP TRIGGER last_changes ON card_sync_tbl;
CREATE TRIGGER last_changes
BEFORE UPDATE ON status_table
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE FUNCTION log_last_chaged();
insert first data:
INSERT INTO status_table (rowid, status0) VALUES (11, 1);
INSERT INTO status_table (rowid, status0) VALUES (12, 2);
and check do everything work fine:
UPDATE status_table SET status0 = 1 WHERE rowid = 11;
UPDATE status_table SET status0 = 4 WHERE rowid = 12;
I receive something on rowid 12 that probably is error:
SQL statement "UPDATE status_table SET status0 = NEW.status0, lastchage
= CURRENT_TIMESTAMP WHERE rowid = OLD.rowid"
PL/pgSQL function log_last_chaged() line 3 at SQL statement
After quick look on duckduckgo I change the function to this:
CREATE OR REPLACE FUNCTION log_last_chaged() RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
NEW.lastchage := CURRENT_TIMESTAMP;
RETURN NEW;
END
$$;
and everything seems work now, but that break the idea update not to hit
table if data is the same.
Any body can help with some hint ? Also I want to know why my first
function does not work, probably loop is happened if trigger does not
stop update to be sent to table on rowid 12 or syntax error.
Regards,
HS
From | Date | Subject | |
---|---|---|---|
Next Message | Andreas Kretschmer | 2020-02-02 13:37:30 | Re: How to avoid UPDATE on same data in table ? |
Previous Message | Peter J. Holzer | 2020-02-01 10:21:33 | Re: Need support on tuning at the time of index creation |