DO $$ DECLARE v_id bigint; begin --1. INSERT INTO r_test_a (name,value,unit,mode,uid,create_ts) SELECT 't_t','',2,extract(epoch from now())::bigint WHERE NOT EXISTS (SELECT id FROM r_test_a WHERE name = 't_t' AND value = '' AND unit = '' AND uid =0); --2. SELECT id into v_id from r_test_a WHERE name = 't_t' AND value = '' AND unit = '' AND uid = 0; --3. DELETE FROM r_test_b a WHERE a.obj_id = 'xxx' AND a.file_id = 'ooo' AND a.id IN (SELECT id FROM r_test_a b WHERE b.name = 't_t' AND b.uid=0); --4. INSERT INTO r_test_b (id,obj_id,file_id,create_ts) SELECT v_id,'xxx','ooo',extract(epoch from now())::bigint ; end $$;