Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: UPDATE row if exists

Tags:

sql

postgresql

I need update row in the table only if row exists.

UPDATE table1 SET ctime = now() WHERE id = 112233;

Or with select before

IF EXISTS (SELECT 1 FROM table1 WHERE id = 112233) THEN
   UPDATE table1 SET ctime = now() WHERE id = 112233;
END IF;

Which query better to reduce write operations?

For performance purpose, do I need to do SELECT before UPDATE to check row exists?

like image 253
Dmitry Avatar asked Jun 11 '17 16:06

Dmitry


1 Answers

This query:

UPDATE table1
    SET ctime = now()
    WHERE id = 112233;

Does exactly what you want. It updates all rows that match the WHERE condition -- over zero rows.

If you are concerned about performance, create an index on table1(id). If id is a primary key, then it already has an index.

like image 199
Gordon Linoff Avatar answered Oct 23 '22 13:10

Gordon Linoff