With stored procedures in PostgreSQL v10.1.2, which is the fastest way or which is better: to check if rows exists and then update or try to update directly with the possibility that no rows matching the condition are found? I need to check a lot of tables with the same condition, tables are not 'denormalized', I made a couple of tests and sometimes option 1 is faster in other cases option 2 ...
Option 1:
IF EXISTS ( SELECT 1
FROM public.table1
WHERE column1 = 'oldvalue' )
THEN
UPDATE public.table1
SET column1 = 'newvalue' , date_update= ....
WHERE column1 = 'oldvalue';
END IF ;
Option 2:
UPDATE public.table1
SET column1 = 'newvalue' , date_update= ...
WHERE column1 = 'oldvalue';
Option 3:
perform FROM public.table1 WHERE column1 = 'oldvalue' ;
if found then
UPDATE public.table1 SET column1='newvalue', date_update = ... WHERE column1 = 'oldvalue';
end if ;
I made:
BEGIN;
EXPLAIN ANALYZE VERBOSE select a_test_w_perform();
ROLLBACK;
for every option and the time average vary, results in time are something like:
Option 1
Query returned successfully in 311 msec. / 423 msec./ 242 msec./ 367Option 2
Query returned successfully in 308 msec. / 307 msec./311 msec./ 200*Option 3
Query returned successfully in 204 msec./ 279 msec./451 msec. / 230
(a IS DISTINCT FROM 'foo' OR b IS DISTINCT FROM 'bar' OR ...)– Erwin Brandstetter Aug 10 '18 at 17:30SETgiving a more symmetrical command. – Jasen Aug 11 '18 at 01:17