Legitimate case for NOLOCK hint
Roger Allen
#SQL Technical Manager at Network Centric Support, CAA approved #drone and #FPV pilot
I always try and avoid using the NOLOCK hint and in fact when I find one in code I will attempt to remove it, usually through the process of improving indexing on the tables in question.
However, recently I added a NOLOCK hint and it's use can be justified. The above code is inside a trigger in a table called TASK, the trigger runs whenever a row is inserted or updated. The SELECT is just checking for the existent of rows in another table called MONITOR.
Since it is just checking the number of rows it does not matter how many rows are returned from the SELECT (the 'dirty read' associated with NOLOCK hints can result in the incorrect number of rows being returned). All it looking for is whether there are rows or whether there are not.
So adding the NOLOCK hint will only help, the EXIST check will still correctly establish if there are rows in the MONITOR table but will not lock the table in the process, thus preventing INSERTS/UPDATES to the TASK table from blocking/deadlocking the MONITOR table (which is how this code came to light, the #deadlock is no longer occurring on the #select after adding this #nolock hint)