Skip to content
Advertisement

Add on to an existing value in a field

In MySQL I would do something along the lines of

INSERT INTO "playerhours" ("uid", "playtime", "port") 
VALUES ('user1', 1337, 7780) 
ON DUPLICATE KEY UPDATE "playtime" = "playtime" + 1337

I tried the following but after a bunch of searching I wasn’t able to find how to do the same in postgresql

INSERT INTO "playerhours" ("uid", "playtime", "port") 
VALUES ('user1', 1337, 7780) 
ON CONFLICT("uid", "port", "date") 
  DO UPDATE SET "playtime" = "playtime" + 1337

so my question is how would I go about adding a number to the previous value of a field (BIGINT)

Advertisement

Answer

You have to catch the value from the variable EXCLUDED:

INSERT INTO "playerhours" ("uid", "playtime", "port") 
VALUES ('test1@steam', 1337, 7780) 
ON CONFLICT("uid", "port", "date") 
DO UPDATE SET "playtime" = EXCLUDED."playtime" + 1337;

Or if you only want to get the current value of a certain column:

INSERT INTO "playerhours" ("uid", "playtime", "port") 
VALUES ('test1@steam', 1337, 7780) 
ON CONFLICT("uid", "port", "date") 
DO UPDATE SET "playtime" = "playerhours"."playtime" + 1337;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement