Using WITH(NOLOCK) to increase performance

2019-08-04 17:54发布

I have seen developers using WITH(nolock) in the query, is there any disadvantage of it? Also, what is the default mode of execution of query? My database do not have any index.

Is there any other way to increase database select statement performance?

3条回答
做自己的国王
2楼-- · 2019-08-04 18:37

There are numerous articles on this on the net. The main risk is that with NOLOCK you can read uncomitted data from the table (dirty reads). See, for example, http://msdn.microsoft.com/en-us/library/aa259216(v=sql.80).aspx or http://www.techrepublic.com/article/using-nolock-and-readpast-table-hints-in-sql-server/6185492

查看更多
迷人小祖宗
3楼-- · 2019-08-04 18:49

The common misconception with nolock is that that it places no locks on the database whilst executing. Technically it does issues a schema-stability (sch-s) lock, so the 'no' part of the lock relates to the data side of the query.

Most of the time that I see this, it is a premature optimization by a developer because they have heard it makes the query faster.

Unless you have instrumented proof and validity in accepting a dirty read (and potentially reading the same row twice) then it should not be used - it definately should not be the default approach to queries, but an exception to the rule when it can be shown that it is required.

查看更多
在下西门庆
4楼-- · 2019-08-04 18:50

NOLOCK can be highly useful when you are reading old data from a frequently used table. Consider the following example,

You have a stored procedure to access data of inactive projects. You don't want this stored procedure to lock the frequently used Projects table while reading old data.

NOLOCK is also useful when dirty reads are not a problem and data is not frequently modified such as in the following cases,

Reading list of countries, currencies, etc... from a database to show in the form. Here the data remains unchanged and a dirty read will not cause a big problem as it will occur very rarely.

However starting with SQL server 2005 the benefits of NOLOCK is very little due to row versioning.

查看更多
登录 后发表回答