Photo by Chad Kirchoff on Unsplash
Prefer watching on YouTube?
In the ideal world, you fully test how your SQL Server will handle upgrading to the latest version. You’re able to catch and mitigate any performance surprises early on.
In the real world, you might not be able to perform a good test before upgrading. You only learn about poor performance once you upgrade in production.
Does this scenario sound familiar? It’s what I’ve been thinking about recently as I have to deal with query performance issues after upgrading to SQL Server 2016.
Coming from SQL Server 2012, I know the new cardnality estimator added in 2014 is a major source of the problems I’m experiencing. While the new cardinality estimator improves performance of some queries, it has also made made some of my queries take hours to run instead of seconds.
Long-term, the solution is to revisit these queries, their stats, and the execution plans being generated for them to see what can be rewritten for better performance.
But ain’t nobody got time for that (at least when facing performance crippling production issues).
Short-term, put a band-aid on to stop the bleeding.
I could change the compatibility mode of the database to revert back to SQL Server 2012 (before the new cardinality estimator was introduced), but then I miss out on being able to use all of the new SQL Server 2016 improvements just because a few queries are misbehaving.
I could enable trace flag 9481 to have my queries use the old cardinality estimator, however as a developer I probably don’t have access to play with trace flags (and for good reason).
Starting with 2016 SP1, what I can do is use the legacy cardinality estimator query hint:
OPTION (USE HINT ('FORCE_LEGACY_CARDINALITY_ESTIMATION'));
This hint is great because it doesn’t require developers to have any special permissions. It also allows SQL to use the old cardinality estimator for poor performing queries only – the rest of the server gets to benefit from the improvements brought on by the new cardinality estimator.
With time, I can revisit the queries that are using this hint to try to improve their performance, but in the mean time it’s a great way to fix regressed query performance due to the new cardinality estimator.
Thanks for reading. You might also enjoy following me on Twitter.