1. 10 Ways To Abuse T-SQL
Common performance
mistakes, coding errors, and how to
prevent them
2. Tracy McKibben
DBA Supervisor, Senior SQL Server DBA
Pearson VUE
Blog: realsqlguy.com
Twitter: @RealSQLGuy
I’m not saying I’m Batman, I’m just saying that nobody has
ever seen me and Batman in the same room together...
14. SELECT *
What's wrong with SELECT *?
• prone to table scans or lookups
• difficult to support with indexes
• widely considered sloppy and "lazy“
• dangerous in views
15. SELECT *
Be a hero.
Don't use SELECT * in code
that counts.
17. Non-SARGable Queries
Which of these are SARGable expressions?
• SalesPersonID <> 10
• SalesPersonID = 99
• SalesPersonID >= 100
• SalesPersonID NOT IN (some
subquery)
• SalesPersonID IN (some subquery)
• SalesPersonID IS NULL
• ISNULL(SalesPersonID, 0) = 0
18. Non-SARGable Queries
Which of these are SARGable expressions?
• SalesPersonID <> 10 *
• SalesPersonID = 99
• SalesPersonID >= 100
• SalesPersonID NOT IN (some
subquery)
• SalesPersonID IN (some subquery)
• SalesPersonID IS NULL
• ISNULL(SalesPersonID, 0) = 0 **
* SQL 2008+ ** sargable if column is NOT NULLable
21. Bandaids
T-SQL makes it easy, too easy, to cover up coding
mistakes, often with a price.
• DISTINCT (don't hide
dupes, stop fetching
them in the first place)
• NOLOCK (this is NOT
the cure for blocking)
• UNION (figure out the
logic for a proper
WHERE clause)
24. Mismatched Data Types
Some transformations conversions work just fine.
Some create performance problems. Some just fail
miserably.
Watch out for:
• NVARCHAR to VARCHAR
• character to numeric
• datetime manipulations
to remove
time, DATEDIFF
30. Incorrect/Unnecessary Ordering
Without ORDER BY, the query
optimizer will surprise you
with a "random" sort
order, dictated by the fastest
query plan it could find.
Specifying an ORDER BY can
affect the query plan
selected, thus affecting the
performance of the query.
32. Single-row Triggers
This kind of thinking has no place in this movie. Nor does
it belong inside a trigger.
Triggers fire per
operation, not per
row, and must be
written to handle
multi-row operations.
34. Lessons Learned
• Use set-based methods
• Be careful with user-defined
functions and views
• SELECT * - lazy and dangerous
• Always obey SARG
• Don’t use bandaids
• Watch your data types
• NULL – it’s not nothing
• Order your results carefully
• Triggers – many rows, not one