Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

When is it safe to use NOLOCK?

$
0
0
We never use NOLOCK in our APPs, but I see it used like confetti in 3rd party apps installed on our servers, and it always worries me, but I wonder if my worry is unfounded and what scenarios are "safe" such that I can ignore them?Having said we "never" use NOLOCK we do use it freely in DBA reports which query APP tables - so that we don't interfere with what users are doing when we check things. But the DBAs know in what ways the data is not "safe" and can / cannot be trusted for. Its just that we don't include NOLOCK in ANY App Code which we write for our users.I've been looking at an example in a 3rd party APP today and my blood is boiling ... but if you learned folk tell me it is safe I'll cut vendors some slack in future.Consider this example:[code]SELECT ... some columns ...FROM WellKnownDocumentManagementSystemDocumentsTable AS DOCWHERE ... AND NOT EXISTS ( SELECT * FROM DenyDocumentToUser (NOLOCK) WHERE DOCNUM = DOC.DOCNUM AND DOCUSER = @CurrentUserID )[/code]Let's assume that I am not allowed to view that document because its DOCNUM is in the Deny Documents To User table associated with my User ID.Normally the NOT EXISTS would return FALSE and I would never know that the document existsBut what if the DenyDocumentToUser table's index was being split as I made my query, and I only read the revised half-page index page, and the newly inserted index overflow page hadn't yet been created, so I didn't read that at all. Thus I never saw the relevant index entry at all, and as a consequence the NOT EXISTS returned TRUE. Of course if I repeated the exercise a couple of milliseconds, or more, later than my query would see all the index pages, as no [relevant] pages were being split at the time, and the document would be blocked from me again.Is this a scenario that could, however rarely, occur?(Its the principle I'm after, rather than this specific example, so if my example has over trivialised it such that it would never fail, but a similar scenario could fail, I'd be very grateful to hear what the subtleties are so I can moderate my blood boiling point temperature accordingly!)Many thanks

Viewing all articles
Browse latest Browse all 3145

Trending Articles