开发者

When it comes to updating all rows in a table, does the method of locking matter for performance?

开发者 https://www.devze.com 2023-01-02 06:05 出处:网络
Question is a follow up to this. The SQL in question was UPDATE stats SET visits = (visits+1) And the question is, for the purpose of performance,开发者_高级运维 does it matter if you lock all row

Question is a follow up to this.

The SQL in question was

UPDATE stats SET visits = (visits+1)

And the question is, for the purpose of performance,开发者_高级运维 does it matter if you lock all rows in stats in comparison to locking the table stats? Or, if the database uses a page-lock rather than a table/row lock?


There is no predicate on this. Any self respecting DB engine should work this out and realise all rows need updated.

Generally, don't second guess the DB engine: performance is subjectively the same.

Personally,

  • I'd not use table or locking hints unless I have to and know why I'm doing it.
  • I'd not issue a query like this anyway from an application without a WHERE clause


In theory you should lock the table, because 1 lock is cheaper than 1M locks.

Many DBs, though, will promote locks for operations like this. As they see the locks expanding, they'll automatically promote to page and table locks.

But, as with anything, "it depends", and it's better to be specific and lock the table yourself.

Edit:

sigh

Postgres example:

LOCK TABLE mytable IN EXCLUSIVE MODE;
UPDATE mytable SET field = field + 1;
COMMIT;

Here's the deal. This is going to happen ANYWAY, the LOCK TABLE command makes it more explicit, and ensures that your intent, locking the table, is clear and capable before the process takes place.

Would I do this on a 10 row table? No.

Would I do this on a database that I KNEW I had exclusive access to? No, there's no need.

Would I do this on a operational database with a table with a large amount a rows? You bet.

0

精彩评论

暂无评论...
验证码 换一张
取 消