SlideShare a Scribd company logo
10 Ways To Abuse T-SQL
Common performance
mistakes, coding errors, and how to
prevent them
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...
10 Ways To Abuse T-SQL
• Procedural coding
• User-defined functions
• Views
• SELECT *
• Non-SARGable queries
• Bandaids
• Mismatched Data Types
• NULL
• Incorrect or unnecessary ordering
• Single-row triggers
Procedural Coding
Symptoms include:
• loops
• cursors
• repeated SQL statements
• temp tables
• if/else structures
Procedural Coding
Comparable to carrying groceries to the car one item
at a time, when you could be using this instead.
Procedural Coding
Help your DBA out, learn set-based coding methods.
Be a team player.
User-Defined Functions
Useful for
• code re-use
• packaging complex logic
• readability
User-Defined Functions
Useful for
• code re-use
• packaging complex logic
• Readability
• killing performance
• complicating query
tuning
• inducing DBA nightmares
User-Defined Functions
Functions have their place, but they're not always the
right tool for the job.
Views
Like user-defined
functions, views can be
used to
• re-use code
• hide complex queries
• make large queries more
readable
Views
But what's lurking beneath the surface?
Views
Views can hide some scary performance issues. Make sure
your view is clear.
SELECT *
Are you SURE you want the
whole thing?
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
SELECT *
Be a hero.
Don't use SELECT * in code
that counts.
Non-SARGable Queries
What is a SARGable query?
A query that is Search
ARGument-able.
What does that mean?
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
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
Non-SARGable Queries
SARG makes DBA's happy!
Bandaids
Don't use bandaids when corrective surgery is required
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)
Bandaids
Be tough - rip off the bandaids!
Ya big crybaby....
Mismatched Data Types
Wrong. So wrong.
Some comparisons should never be made.
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
Mismatched Data Types
Keep your data types compatible
NULL
Improper handling of NULL values can lead to
errors and/or incorrect results.
NULL
• NULL has NO VALUE
• NULL does not mean zero
• NULL does not mean blank
• NULL does not mean an
empty string
• NULL means NULL
NULL
NULL values aren't difficult to work with, but be
sure to read the fine print.
Incorrect/Unnecessary Ordering
Don't make assumptions
about how data will be
ordered.
If a specific order is
required, specify it.
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.
Incorrect/Unnecessary Ordering
Sometimes the order of things doesn't
matter, sometimes it makes all the difference.
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.
Single-row Triggers
Sometimes there should be only one, but not inside
a trigger.
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
Any Questions?

More Related Content

PDF
Informatica interview questions
PPT
Archivo Secuencial
DOC
Informatica Interview Questions & Answers
PDF
Dbms
PPS
HASH Organizacion de Archivos en Bases de Datos
PPT
Exposicion organización directa
PPT
Dating Game - T-SQL for High School Girls
PPTX
Intro to T-SQL – 2nd session
Informatica interview questions
Archivo Secuencial
Informatica Interview Questions & Answers
Dbms
HASH Organizacion de Archivos en Bases de Datos
Exposicion organización directa
Dating Game - T-SQL for High School Girls
Intro to T-SQL – 2nd session

Viewers also liked (20)

PDF
Using T-SQL
PPTX
MS SQL SERVER: Getting Started With Sql Server 2008
PDF
Writing and optimizing T-SQL
PPTX
T-SQL Overview
PDF
Hadoop Design Patterns
 
PDF
Highlights from the EMC & VMware CIO Summit
 
PDF
Transform Your Business with Big Data Storage
 
PPTX
Pharm mon to perfect
PPT
Friday business cycle AP Macro
PDF
Software Defined Data Center: The Intersection of Networking and Storage
 
PDF
Informe criterio identificacion cliente
PDF
الجريدة الرسمية ليوم 19 يناير
PPTX
psychology of old age
PPT
law of supply
PDF
White paper: EMC Performance Optimization for Microsoft FAST Search Server 20...
 
PPTX
Jaringan komputer pti
PDF
Csw2012
Using T-SQL
MS SQL SERVER: Getting Started With Sql Server 2008
Writing and optimizing T-SQL
T-SQL Overview
Hadoop Design Patterns
 
Highlights from the EMC & VMware CIO Summit
 
Transform Your Business with Big Data Storage
 
Pharm mon to perfect
Friday business cycle AP Macro
Software Defined Data Center: The Intersection of Networking and Storage
 
Informe criterio identificacion cliente
الجريدة الرسمية ليوم 19 يناير
psychology of old age
law of supply
White paper: EMC Performance Optimization for Microsoft FAST Search Server 20...
 
Jaringan komputer pti
Csw2012
Ad

Similar to 10 Ways To Abuse T-SQL (20)

PPTX
Databases 101
PDF
Handling SQL Server Null Values
PPTX
SQL Server 2012 Best Practices
PDF
Query Tuning for Database Pros & Developers
PPTX
02 database oprimization - improving sql performance - ent-db
PPTX
Sql good practices
PPTX
Dell Webinar 2014-06-24: Subqueries For Superheroes
PPTX
My Query is slow, now what?
PPTX
Sql server infernals
ODP
Performance tuning
PDF
Sql coding-standard-sqlserver
PDF
SQL command for daily use ddl dml dcl dql
PPT
Advanced t sql - querying and programming inside sql server
PDF
TSQL Coding Guidelines
PDF
SQL Database Performance Tuning for Developers
PDF
Sql For Ibm I A Database Modernization Guide None Rafael Victriapereira
PPTX
More Complex SQL and Concurrency ControlModule 4.pptx
PDF
Building better SQL Server Databases
PPTX
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
PPTX
SQL Query Optimization | SQL Query Optimization Techniques | SQL Basics | SQL...
Databases 101
Handling SQL Server Null Values
SQL Server 2012 Best Practices
Query Tuning for Database Pros & Developers
02 database oprimization - improving sql performance - ent-db
Sql good practices
Dell Webinar 2014-06-24: Subqueries For Superheroes
My Query is slow, now what?
Sql server infernals
Performance tuning
Sql coding-standard-sqlserver
SQL command for daily use ddl dml dcl dql
Advanced t sql - querying and programming inside sql server
TSQL Coding Guidelines
SQL Database Performance Tuning for Developers
Sql For Ibm I A Database Modernization Guide None Rafael Victriapereira
More Complex SQL and Concurrency ControlModule 4.pptx
Building better SQL Server Databases
SQL-Demystified-A-Beginners-Guide-to-Database-Mastery.pptx
SQL Query Optimization | SQL Query Optimization Techniques | SQL Basics | SQL...
Ad

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
cuic standard and advanced reporting.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Cloud computing and distributed systems.
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
A Presentation on Artificial Intelligence
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPT
Teaching material agriculture food technology
PDF
KodekX | Application Modernization Development
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
Digital-Transformation-Roadmap-for-Companies.pptx
MYSQL Presentation for SQL database connectivity
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Unlocking AI with Model Context Protocol (MCP)
Encapsulation_ Review paper, used for researhc scholars
cuic standard and advanced reporting.pdf
Understanding_Digital_Forensics_Presentation.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Network Security Unit 5.pdf for BCA BBA.
Cloud computing and distributed systems.
The Rise and Fall of 3GPP – Time for a Sabbatical?
A Presentation on Artificial Intelligence
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Teaching material agriculture food technology
KodekX | Application Modernization Development
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Spectral efficient network and resource selection model in 5G networks

10 Ways To Abuse T-SQL