Supplements and SQL Hints - Pt 3 - Table Hints

 


Welcome to part 3 of my month long series on Supplements and SQL Hints. A guide to getting enhancements in the gym and in your database. We're back to the database side of things with Table Hints today. Two weeks ago I touched on overall query hints, those boosters that might help speed your query along and give the query analyzer a little assistance. Table hints are helpers for specific tables in your query. You can use them on multiple tables within the same query, or just one and of course you could stack them.  Let's dive in shall we?

NOLOCK Hint

If you're a regular in the SQL Server community, you're already screaming at me and rightfully so. However, this blog is for beginners as well as seniors in the field so I want to be sure to address it.
NOLOCK is used to allow reading of rows without acquiring a lock. Meaning your massive SELECT statement query won't create a blocking scenario with other readers or writers. Conversely, a NOLOCK will allow you to read a table in which another query might be updating or inserting data. At first blush you might be inclined to think "Well that sounds like a dandy of a helper. I don't want my query to be a blocker." But as the great sports pundit Lee Corso would say "Not so fast my friend."

This will be a crude example but you'll get the idea. Let's consider the following two statements:

The query on the left is going to update the Reputation score where a user's location is Houston and the right hand query is going to look for users in Houston with a score of greater than or equal to 5000. Running that right hand query on its own right now shows me 2 results. 
If I run the left hand query, the BEGIN TRAN will acquire a lock while it waits for a COMMIT or ROLLBACK. Meanwhile, I can run the query on the right with that NOLOCK hint and get results. But what do you suppose happens? I'm going to get all of the rows, even though the data hasn't been committed, the NOLOCK allows me to barrel my way through and get the results. Only problem is, I realized I meant to make that Reputation score 500, not 5000 so I roll it back. However, I've already provided the data to my supervisor that we had 232 records of users in Houston with a reputation score of 5000. Bad data.
Coming the other direction, if I start my SELECT using the NOLOCK hint, then data in the data is being updated, inserted or deleted, my query is getting the data as it was when I began the select. So it may miss new rows, incorrectly return rows that have been deleted or incorrectly report values that were updated.
So yes, NOLOCK can be quite dangerous, especially in high volume transaction systems. It's definitely tempting to use in scenarios where you see blocking occurring. I don't want my selects to block updates. Great, neither do I. Let's go tune the queries and procedures though, dig in and see what can be done with your indexes or even rewriting the query if possible to make it more effective and reduce the blocking.
Now, I have one caveat to this. In warehouse type systems where you may be reporting on historical data that does not change often, for example running a large query on order data from a year ago that won't be updated or deleted, it's more acceptable to use in that scenario. I still urge good tuning, but in some cases even the best indexes and queries are still going to run long. And you don't want to block other report users, then a NOLOCK would be an option. Do not simply reach for this hint every time you hit a blocker though. 

INDEX

Pure and simple, use WITH (INDEX (indexname or id)) to tell a query to use particular index for a table. Now, nine times out of ten, the query optimizer nails the right indexes to use when constructing a query plan. However, there are those odd one offs where you test and test and test and no matter what you cannot get the query to utilize the index you know will be most effective.
I experienced just such an instance not too long ago. We had a report that called a procedure utilizing two parameters; one for an account number and one for a specific date. In the WHERE clause of the query, it read like this:
WHERE AccountNumber like '%@acctNbr%' and Date = @date.
There was an index on the account number field, but not one using date. The cached query plan was doing a full scan on table looking for AccountNumber and left a residual predicate of the date. Think of a residual predicate as the next thing the optimizer would look for but either there's no index containing it or it's in the included columns. Anyway, it was performing a full scan on the table and taking roughly 4 minutes to complete. When using a wildcard (the % symbol) in your where clause, the plan is unable to seek for records so it has to go row by row looking for values that contain your search criteria. So of course I'm thinking, quick index on the date column and include the account number, that should do the trick. Added the index, cleared the procedure cache and ran again. It built the same plan. Oh Mr. Optimizer, I gave you a good index. This will be much more efficient, please use it. Nope, it refused. 
Now I will say this, I'm not a big fan of using this particular hint either. Mainly because if parameter values skew wildly, forcing the index could have disastrous consequences. Especially if you deal with range values. However, in my particular case, there were only two parameters and the date criteria was an equals so I felt pretty confident. I forced it to use my date based index and voila! The query ran in about 1 second. That report has not shown up my long running alerts since it was implemented.
In my case, even though I provided an index that was more effective for a seek operation, the optimizer was stuck on the fact that the account number field was unique and it thought it would be the quickest search. However, with that wildcard in the WHERE clause, it was forcing a full scan.
Bottom line, this is a handy option to have, but I advise caution. If you force an index, revisit your query and index stats regularly, make sure it's still the most effective course of action.
You can pair this hint with FORCESEEK and FORCESCAN as well. Again, bypassing the plan built by the optimizer. These are incredible nuanced though I feel and I've neither seen or used them to get a query to perform better. Just wanted you to know they are there though. 

There are a wealth of table hints available to use. Many have to do with how the table or rows get locked for reading or writing. Table hints can be handy, but are often times very nuanced, tricky to implement and maintain and probably should only be used as a last resort option. Always attempt to build good queries and appropriate indexes first. 

Come back next week for part 4 of the series; Post workout supplements and muscle builders!





Comments

Popular posts from this blog

Running Out of INT

Supplements and SQL Hints - Part 1 - TSQL Helpers