Dmitry
Dmitry

Reputation: 867

PostgreSQL: UPDATE row if exists

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?

Upvotes: 6

Views: 11088

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

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.

Upvotes: 13

Related Questions