SlideShare ist ein Scribd-Unternehmen logo
1 von 35
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?

Weitere ähnliche Inhalte

Andere mochten auch

Friday business cycle AP Macro
Friday business cycle AP MacroFriday business cycle AP Macro
Friday business cycle AP Macro
Travis Klein
 
Informe criterio identificacion cliente
Informe criterio identificacion clienteInforme criterio identificacion cliente
Informe criterio identificacion cliente
Nathalia Sanchez
 
psychology of old age
psychology of old agepsychology of old age
psychology of old age
Deepika Singh
 
Mon timeline of important events
Mon timeline of important eventsMon timeline of important events
Mon timeline of important events
Travis Klein
 

Andere mochten auch (20)

Writing and optimizing T-SQL
Writing and optimizing T-SQLWriting and optimizing T-SQL
Writing and optimizing T-SQL
 
T-SQL Overview
T-SQL OverviewT-SQL Overview
T-SQL Overview
 
Hadoop Design Patterns
Hadoop Design PatternsHadoop Design Patterns
Hadoop Design Patterns
 
Doc2
Doc2Doc2
Doc2
 
Highlights from the EMC & VMware CIO Summit
Highlights from the EMC & VMware CIO SummitHighlights from the EMC & VMware CIO Summit
Highlights from the EMC & VMware CIO Summit
 
Transform Your Business with Big Data Storage
Transform Your Business with Big Data StorageTransform Your Business with Big Data Storage
Transform Your Business with Big Data Storage
 
Pharm mon to perfect
Pharm mon to perfectPharm mon to perfect
Pharm mon to perfect
 
Friday business cycle AP Macro
Friday business cycle AP MacroFriday business cycle AP Macro
Friday business cycle AP Macro
 
Software Defined Data Center: The Intersection of Networking and Storage
Software Defined Data Center: The Intersection of Networking and StorageSoftware Defined Data Center: The Intersection of Networking and Storage
Software Defined Data Center: The Intersection of Networking and Storage
 
Informe criterio identificacion cliente
Informe criterio identificacion clienteInforme criterio identificacion cliente
Informe criterio identificacion cliente
 
Deeltopia
DeeltopiaDeeltopia
Deeltopia
 
الجريدة الرسمية ليوم 19 يناير
الجريدة الرسمية ليوم 19 ينايرالجريدة الرسمية ليوم 19 يناير
الجريدة الرسمية ليوم 19 يناير
 
psychology of old age
psychology of old agepsychology of old age
psychology of old age
 
law of supply
law of supplylaw of supply
law of supply
 
White paper: EMC Performance Optimization for Microsoft FAST Search Server 20...
White paper: EMC Performance Optimization for Microsoft FAST Search Server 20...White paper: EMC Performance Optimization for Microsoft FAST Search Server 20...
White paper: EMC Performance Optimization for Microsoft FAST Search Server 20...
 
Jaringan komputer pti
Jaringan komputer ptiJaringan komputer pti
Jaringan komputer pti
 
Csw2012
Csw2012Csw2012
Csw2012
 
Mobile mini trends
Mobile mini trendsMobile mini trends
Mobile mini trends
 
Mon timeline of important events
Mon timeline of important eventsMon timeline of important events
Mon timeline of important events
 
Venta de Productos Shelo Nabel , @shelonabelshop tienda en facebook
 Venta de Productos Shelo Nabel , @shelonabelshop tienda en facebook  Venta de Productos Shelo Nabel , @shelonabelshop tienda en facebook
Venta de Productos Shelo Nabel , @shelonabelshop tienda en facebook
 

Ähnlich wie 10 Ways To Abuse T-SQL

What SQL should actually be...
What SQL should actually be...What SQL should actually be...
What SQL should actually be...
Open Academy
 
libinjection: new technique in detecting SQLi attacks, iSEC Partners Open Forum
libinjection: new technique in detecting SQLi attacks, iSEC Partners Open Forumlibinjection: new technique in detecting SQLi attacks, iSEC Partners Open Forum
libinjection: new technique in detecting SQLi attacks, iSEC Partners Open Forum
Nick Galbreath
 
We Don't Need Roads: A Developers Look Into SQL Server Indexes
We Don't Need Roads: A Developers Look Into SQL Server IndexesWe Don't Need Roads: A Developers Look Into SQL Server Indexes
We Don't Need Roads: A Developers Look Into SQL Server Indexes
Richie Rump
 

Ähnlich wie 10 Ways To Abuse T-SQL (20)

My Query is slow, now what?
My Query is slow, now what?My Query is slow, now what?
My Query is slow, now what?
 
SQL Tips + Tricks for Developers
SQL Tips + Tricks for DevelopersSQL Tips + Tricks for Developers
SQL Tips + Tricks for Developers
 
Dell Webinar 2014-06-24: Subqueries For Superheroes
Dell Webinar 2014-06-24: Subqueries For SuperheroesDell Webinar 2014-06-24: Subqueries For Superheroes
Dell Webinar 2014-06-24: Subqueries For Superheroes
 
What SQL should actually be...
What SQL should actually be...What SQL should actually be...
What SQL should actually be...
 
Tips for Database Performance
Tips for Database PerformanceTips for Database Performance
Tips for Database Performance
 
You Can Tune Your Own SQL Code
You Can Tune Your Own SQL CodeYou Can Tune Your Own SQL Code
You Can Tune Your Own SQL Code
 
libinjection: new technique in detecting SQLi attacks, iSEC Partners Open Forum
libinjection: new technique in detecting SQLi attacks, iSEC Partners Open Forumlibinjection: new technique in detecting SQLi attacks, iSEC Partners Open Forum
libinjection: new technique in detecting SQLi attacks, iSEC Partners Open Forum
 
SQL Server Worst Practices - EN
SQL Server Worst Practices - ENSQL Server Worst Practices - EN
SQL Server Worst Practices - EN
 
Clean code
Clean codeClean code
Clean code
 
Killing Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORMKilling Shark-Riding Dinosaurs with ORM
Killing Shark-Riding Dinosaurs with ORM
 
ORM Pink Unicorns
ORM Pink UnicornsORM Pink Unicorns
ORM Pink Unicorns
 
The Key to Keys - Database Design
The Key to Keys - Database DesignThe Key to Keys - Database Design
The Key to Keys - Database Design
 
Test Driven Development with Laravel
Test Driven Development with LaravelTest Driven Development with Laravel
Test Driven Development with Laravel
 
Apex 10 commandments df14
Apex 10 commandments df14Apex 10 commandments df14
Apex 10 commandments df14
 
Software testing with examples in Angular (and AngularJS)
Software testing with examples in Angular (and AngularJS)Software testing with examples in Angular (and AngularJS)
Software testing with examples in Angular (and AngularJS)
 
New techniques in sql obfuscation, from DEFCON 20
New techniques in sql obfuscation, from DEFCON 20New techniques in sql obfuscation, from DEFCON 20
New techniques in sql obfuscation, from DEFCON 20
 
Testing gone-right
Testing gone-rightTesting gone-right
Testing gone-right
 
Quick & Easy SQL Tips
Quick & Easy SQL TipsQuick & Easy SQL Tips
Quick & Easy SQL Tips
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)
 
We Don't Need Roads: A Developers Look Into SQL Server Indexes
We Don't Need Roads: A Developers Look Into SQL Server IndexesWe Don't Need Roads: A Developers Look Into SQL Server Indexes
We Don't Need Roads: A Developers Look Into SQL Server Indexes
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

10 Ways To Abuse T-SQL