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

試著忘記壹切 提交于 2019-12-11 14:27:49

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/2984963/when-it-comes-to-updating-all-rows-in-a-table-does-the-method-of-locking-matter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!