I'm trying to upsert the data by using conflict and below is the query and each every time it keeps on inserting the record, but not updating, any suggestion on the query?
CREATE TABLE tbl (
id int PRIMARY KEY
, text text
, extra text
, vndr_code int4,
item_code varchar(50)
,created_date timestamp
,created_by varchar(225)
,modified_date timestamp
,modified_by varchar(225)
);
INSERT INTO tbl VALUES
(1, 'foo1', 'sample_data_test1',12345, 89890, now()::timestamp(0), 'user_name',now()::timestamp(0), 'user_name' ),
(2, 'foo2', 'sample_data_test2',12345, 22000, now()::timestamp(0), 'user_name',now()::timestamp(0), 'user_name' ),
(3, 'foo3', 'sample_data_test3',12345, 33030, now()::timestamp(0), 'user_name',now()::timestamp(0), 'user_name' ),
(4, 'foo4', 'sample_data_test4',12345, 44404, now()::timestamp(0), 'user_name',now()::timestamp(0), 'user_name' ),
(5, 'foo5', 'sample_data_test5',12345, 55555, now()::timestamp(0), 'user_name',now()::timestamp(0), 'user_name' )
;
Upsert:
WITH data(id) AS ( -- Only 1st column gets explicit name
VALUES
(5, 'foo5', 'sample_data_test5_view',12345, 55555, now()::timestamp(0), 'user_name',now()::timestamp(0), 'user_name' ),
(6, 'foo6', 'sample_data_test6',12345, 55555, now()::timestamp(0), 'user_name',now()::timestamp(0), 'user_name' )
)
, del AS (
DELETE FROM tbl AS t
USING data d
WHERE t.id = d.id
-- AND t <> d -- optional, to avoid empty updates
) -- only works for complete rows
INSERT INTO tbl AS t
TABLE data -- short for: SELECT * FROM data
ON CONFLICT (id) DO NOTHING
RETURNING t.id;
how not to update created_by & created_date columns, just update the rest of those columns exclude id?