This is the second attempt as I didn't add enough examples in the first one and it was closed.
I need to make a query in Postgres that inserts new item if existing data has invalid data. I want to do something like this
if not exists( select * from table where field='value' ) then
insert into ...
end if;
Can I do this without functions?
Here's the table
create table if not exists test_md (
id serial not null,
partition text not null,
version int not null,
data jsonb not null,
primary key (partition, version)
);
Here's some data
insert into test_md(partition, version, data)
values
('part one', 1, '{"k1": "v1", "k2": "v2"}'),
('part one', 2, '{"k1": "v1", "k2": "v2"}'),
('part two', 4, '{"k1": "v1", "k2": "v2"}'),
('part two', 5, '{"k1": "v1", "k2": "v2"}')
;
For example I want to insert data set
{
'partition': 'part one',
'data': '{"k1": "v1", "k2": "v2"}'
}
I should do nothing if partition and data are the same with the v2 record. In any other case, I should add a new record with version max + 1.