SlideShare a Scribd company logo
1 of 23
Download to read offline
Grant Fritchey | www.ScaryDBA.com
www.ScaryDBA.com
Top Tips for Better T-SQL
Stored Procedures
Grant Fritchey – Red Gate Software
Grant Fritchey | www.ScaryDBA.com
Goal
 Learn methods for writingT-SQL for readability
 Understand how to write T-SQL for performance
2
Grant Fritchey | www.ScaryDBA.com
Get in touch
scarydba.com
grant@scarydba.com
@gfritchey
Grant Fritchey
Grant Fritchey | www.ScaryDBA.com
Agenda
 Writing for readability
» Object Names & Format
» Comments
» Error Handling
» Personal Preferences
 Writing for performance
» DataTypes
» Functions inComparisons
» ImproperUse of Functions
» The “Run Faster” Switch
» InappropriateUse ofQuery Hints
» Recompiles
» Row byAgonizing Row
» NestingViews
4
Grant Fritchey | www.ScaryDBA.com
Writing for Readability
 Define a local standard
» Object names
» Comments
» Format
» Error handling
 Enforce the standard
» Document it
» Code reviews
5
Grant Fritchey | www.ScaryDBA.com
Object Names & Format
 Names should be descriptive
» Procedures should be a phrase
» Abbreviations should be common (no Ddltbl)
 Use aliases
» Clear
» Common
 Be consistent
» A foolish consistency is the hobgoblin of little
minds
» Keyword in that sentence is “foolish”
6
Grant Fritchey | www.ScaryDBA.com
Comments
 Do something
 Most important is describing the action, not
documentation
 Use source control for documentation
 Self-documenting code is a lie
7
Grant Fritchey | www.ScaryDBA.com
Error Handling
 TRY/CATCH
 Deadlocks
 Establish local best practices
8
Grant Fritchey | www.ScaryDBA.com
Personal Preferences
 CamelCase
 Uppercase for reserve words and key words
 Line breaks
» On SELECT list
» Between JOIN criteria
» BetweenWHERE criteria
 Use the semicolon
 Indent
» After initial SELECT
» With ON clause
» AfterWHERE clause
9
Grant Fritchey | www.ScaryDBA.com
Writing For Performance
 Write for your data structures
 Write for your indexes
 Write for the query optimizer
 Avoid common issues:
» Data types
» Functions in comparisons
» Improper use of functions
» The “run faster” switch
» Inappropriate Query Hints
» Recompiles
» NullValues
» Row By Agonizing Row
» NestedViews
10
Grant Fritchey | www.ScaryDBA.com
Data Types
 Problem
» Implicit or explicit data type conversion
 Indications
» Scans
» Slow performance
 Solution
» Use appropriate data types
11
Grant Fritchey | www.ScaryDBA.com
Functions in Comparisons
 Problem
» Function on column in WHERE or JOIN criteria
 Indications
» Scans
» Slow performance
 Solution
» Don’t run functions on columns
» Use sargeable functions
12
Grant Fritchey | www.ScaryDBA.com
Improper Use of Functions
 Problem
» Multi-statement user defined functions cause
poor performance
 Indications
» Zero cost scan operator in exec plan
» Very slow performance
 Solution
» When working with more than a few (~50?) rows,
don’t use them
» When using operations such as JOIN that require
statistics, don’t use them
13
Grant Fritchey | www.ScaryDBA.com
The “Run Faster” Switch
 Problem
» Use of the NO_LOCK query hint everywhere, or
setting transaction isolation level to
READ_UNCOMMITTED
 Indications
» Extra rows in result set
» Missing rows in result set
 Solution
» Tune the queries
» Tune the structures
» Use snapshot isolation levels
 http://www.jasonstrate.com/2012/06/the-side-effect-of-
nolock/
14
Grant Fritchey | www.ScaryDBA.com
Query Hints
 Problem
» Query hints in the code such as FAST n, index
hints, JOIN hints
 Indications
» Inconsistent performance behavior
» Bad performance
» Odd looking execution plans
 Solution
» Use of query hints should be exceptional
» Exceptions are rare, not standard practice
15
Grant Fritchey | www.ScaryDBA.com
Recompiles
 Problem
» Excessive blocking and CPU contention caused by
constant or long statement recompiles
 Indications
» Recompile events in extended events or trace
» Blocking
» High CPU usage
 Solutions
» Avoid interleaving DDL & DML
» Where viable, use table variables
16
Grant Fritchey | www.ScaryDBA.com
Row by Agonizing Row
 Problem
» Cursors instead of set-based operations
» WHILE loops instead of set-based operations
» Multiple statements where 1 will do
 Indications
» Extremely slow performance
 Solutions
» Eliminate unnecessary row-by-row processing
17
Grant Fritchey | www.ScaryDBA.com
Nested Views
 Problem
» Views within views causes optimizer timeout
 Indications
» Incredibly complex query plans for simple queries
» Very poor performance
 Solutions
» Don’t nest views
» Materialize views
18
Grant Fritchey | www.ScaryDBA.com
Writing for Readability
 Define a local standard
» Object names
» Comments
» Format
» Error handling
 Enforce the standard
» Document it
» Code reviews
19
Grant Fritchey | www.ScaryDBA.com
Writing For Performance
 Write for your data structures
 Write for your indexes
 Write for the query optimizer
 Avoid common issues:
» Data types
» Functions in comparisons
» Improper use of functions
» The “run faster” switch
» Inappropriate Query Hints
» Recompiles
» Row By Agonizing Row
» NestedViews
20
Grant Fritchey | www.ScaryDBA.com
Goal
 Learn methods for writingTSQL for readability
 Understand how to write TSQL for performance
21
Grant Fritchey | www.ScaryDBA.com
Get in touch
scarydba.com
grant@scarydba.com
@gfritchey
Grant Fritchey
Grant Fritchey | www.ScaryDBA.com
Questions?
24

More Related Content

Viewers also liked

MarketLine Country Statistics Database
MarketLine Country Statistics DatabaseMarketLine Country Statistics Database
MarketLine Country Statistics Database
MarketLine
 
Oracle hard and soft parsing
Oracle hard and soft parsingOracle hard and soft parsing
Oracle hard and soft parsing
Ishaan Guliani
 

Viewers also liked (20)

Performance Tuning Azure SQL Database
Performance Tuning Azure SQL DatabasePerformance Tuning Azure SQL Database
Performance Tuning Azure SQL Database
 
Understanding Your Servers, All Your Servers
Understanding Your Servers, All Your ServersUnderstanding Your Servers, All Your Servers
Understanding Your Servers, All Your Servers
 
The Importance of Wait Statistics in SQL Server
The Importance of Wait Statistics in SQL ServerThe Importance of Wait Statistics in SQL Server
The Importance of Wait Statistics in SQL Server
 
التحدى 6 الإستعلام بطريقة المعالج
التحدى 6 الإستعلام بطريقة المعالجالتحدى 6 الإستعلام بطريقة المعالج
التحدى 6 الإستعلام بطريقة المعالج
 
Trabalho fitos digitais
Trabalho fitos digitaisTrabalho fitos digitais
Trabalho fitos digitais
 
Lesson4 Protect and maintain databases
Lesson4 Protect and maintain databases Lesson4 Protect and maintain databases
Lesson4 Protect and maintain databases
 
Lesson8 Manage Records
Lesson8 Manage RecordsLesson8 Manage Records
Lesson8 Manage Records
 
Lesson11 Create Query
Lesson11 Create QueryLesson11 Create Query
Lesson11 Create Query
 
MarketLine Country Statistics Database
MarketLine Country Statistics DatabaseMarketLine Country Statistics Database
MarketLine Country Statistics Database
 
Oracle hard and soft parsing
Oracle hard and soft parsingOracle hard and soft parsing
Oracle hard and soft parsing
 
Chapter 11new
Chapter 11newChapter 11new
Chapter 11new
 
Lesson5 Print and export databases
Lesson5 Print and export databases Lesson5 Print and export databases
Lesson5 Print and export databases
 
الوحدة التاسعة - قاعدة البيانات وادارتها
الوحدة التاسعة - قاعدة البيانات وادارتهاالوحدة التاسعة - قاعدة البيانات وادارتها
الوحدة التاسعة - قاعدة البيانات وادارتها
 
Performance tuning in sql server
Performance tuning in sql serverPerformance tuning in sql server
Performance tuning in sql server
 
Oracle 11g PL/SQL proqramlamlaşdırma yenilikləri
Oracle 11g PL/SQL proqramlamlaşdırma yenilikləri Oracle 11g PL/SQL proqramlamlaşdırma yenilikləri
Oracle 11g PL/SQL proqramlamlaşdırma yenilikləri
 
أساسيات التأمين
أساسيات التأمينأساسيات التأمين
أساسيات التأمين
 
Top frinds-انشاء-استعلام-بطريقه-المعالج-6-copy
Top frinds-انشاء-استعلام-بطريقه-المعالج-6-copyTop frinds-انشاء-استعلام-بطريقه-المعالج-6-copy
Top frinds-انشاء-استعلام-بطريقه-المعالج-6-copy
 
SQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database PerformanceSQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database Performance
 
Database system concepts and architecture
Database system concepts and architectureDatabase system concepts and architecture
Database system concepts and architecture
 
Performance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL DatabasePerformance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL Database
 

Similar to Top Tips for Better T-SQL

5 physical data modeling blunders 09092010
5 physical data modeling blunders 090920105 physical data modeling blunders 09092010
5 physical data modeling blunders 09092010
ERwin Modeling
 
Using Compass to Diagnose Performance Problems in Your Cluster
Using Compass to Diagnose Performance Problems in Your ClusterUsing Compass to Diagnose Performance Problems in Your Cluster
Using Compass to Diagnose Performance Problems in Your Cluster
MongoDB
 
Using Compass to Diagnose Performance Problems
Using Compass to Diagnose Performance Problems Using Compass to Diagnose Performance Problems
Using Compass to Diagnose Performance Problems
MongoDB
 
Advanced web application architecture - PHP Barcelona
Advanced web application architecture  - PHP BarcelonaAdvanced web application architecture  - PHP Barcelona
Advanced web application architecture - PHP Barcelona
Matthias Noback
 

Similar to Top Tips for Better T-SQL (20)

SQL Server Optimization Checklist
SQL Server Optimization ChecklistSQL Server Optimization Checklist
SQL Server Optimization Checklist
 
Introducing Azure SQL Data Warehouse
Introducing Azure SQL Data WarehouseIntroducing Azure SQL Data Warehouse
Introducing Azure SQL Data Warehouse
 
Query Tuning Azure SQL Databases
Query Tuning Azure SQL DatabasesQuery Tuning Azure SQL Databases
Query Tuning Azure SQL Databases
 
Why new hardware may not make SQL Server faster
Why new hardware may not make SQL Server fasterWhy new hardware may not make SQL Server faster
Why new hardware may not make SQL Server faster
 
Grant Fritchey - Query Tuning In Azure SQL Database
Grant Fritchey - Query Tuning In Azure SQL DatabaseGrant Fritchey - Query Tuning In Azure SQL Database
Grant Fritchey - Query Tuning In Azure SQL Database
 
Владимир Бронников (Senior .NET Developer, Perfectial) “Performance optimizat...
Владимир Бронников (Senior .NET Developer, Perfectial) “Performance optimizat...Владимир Бронников (Senior .NET Developer, Perfectial) “Performance optimizat...
Владимир Бронников (Senior .NET Developer, Perfectial) “Performance optimizat...
 
Best practices with development of enterprise-scale SharePoint solutions - Pa...
Best practices with development of enterprise-scale SharePoint solutions - Pa...Best practices with development of enterprise-scale SharePoint solutions - Pa...
Best practices with development of enterprise-scale SharePoint solutions - Pa...
 
Top 3 design patterns in Map Reduce
Top 3 design patterns in Map ReduceTop 3 design patterns in Map Reduce
Top 3 design patterns in Map Reduce
 
Database and application performance vivek sharma
Database and application performance vivek sharmaDatabase and application performance vivek sharma
Database and application performance vivek sharma
 
SharePoint & jQuery Guide - SPSTC 5/18/2013
SharePoint & jQuery Guide - SPSTC 5/18/2013 SharePoint & jQuery Guide - SPSTC 5/18/2013
SharePoint & jQuery Guide - SPSTC 5/18/2013
 
Do you queue
Do you queueDo you queue
Do you queue
 
The Life-Changing Magic of Tidying Up in Salesforce
The Life-Changing Magic of Tidying Up in SalesforceThe Life-Changing Magic of Tidying Up in Salesforce
The Life-Changing Magic of Tidying Up in Salesforce
 
Performance By Design
Performance By DesignPerformance By Design
Performance By Design
 
Mrdp reduce side_join
Mrdp reduce side_joinMrdp reduce side_join
Mrdp reduce side_join
 
5 physical data modeling blunders 09092010
5 physical data modeling blunders 090920105 physical data modeling blunders 09092010
5 physical data modeling blunders 09092010
 
Using Compass to Diagnose Performance Problems in Your Cluster
Using Compass to Diagnose Performance Problems in Your ClusterUsing Compass to Diagnose Performance Problems in Your Cluster
Using Compass to Diagnose Performance Problems in Your Cluster
 
Using Compass to Diagnose Performance Problems
Using Compass to Diagnose Performance Problems Using Compass to Diagnose Performance Problems
Using Compass to Diagnose Performance Problems
 
Advanced web application architecture - PHP Barcelona
Advanced web application architecture  - PHP BarcelonaAdvanced web application architecture  - PHP Barcelona
Advanced web application architecture - PHP Barcelona
 
Keeping business logic out of your UIs
Keeping business logic out of your UIsKeeping business logic out of your UIs
Keeping business logic out of your UIs
 
World-class Data Engineering with Amazon Redshift
World-class Data Engineering with Amazon RedshiftWorld-class Data Engineering with Amazon Redshift
World-class Data Engineering with Amazon Redshift
 

More from Grant Fritchey

More from Grant Fritchey (20)

Migrating To PostgreSQL
Migrating To PostgreSQLMigrating To PostgreSQL
Migrating To PostgreSQL
 
PostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and AlertingPostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and Alerting
 
Automating Database Deployments Using Azure DevOps
Automating Database Deployments Using Azure DevOpsAutomating Database Deployments Using Azure DevOps
Automating Database Deployments Using Azure DevOps
 
Learn To Effectively Use Extended Events_Techorama.pdf
Learn To Effectively Use Extended Events_Techorama.pdfLearn To Effectively Use Extended Events_Techorama.pdf
Learn To Effectively Use Extended Events_Techorama.pdf
 
Using Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query PerformanceUsing Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query Performance
 
You Should Be Standing Here: Learn How To Present a Session
You Should Be Standing Here: Learn How To Present a SessionYou Should Be Standing Here: Learn How To Present a Session
You Should Be Standing Here: Learn How To Present a Session
 
Redgate Community Circle: Tools For SQL Server Performance Tuning
Redgate Community Circle: Tools For SQL Server Performance TuningRedgate Community Circle: Tools For SQL Server Performance Tuning
Redgate Community Circle: Tools For SQL Server Performance Tuning
 
10 Steps To Global Data Compliance
10 Steps To Global Data Compliance10 Steps To Global Data Compliance
10 Steps To Global Data Compliance
 
Time to Use the Columnstore Index
Time to Use the Columnstore IndexTime to Use the Columnstore Index
Time to Use the Columnstore Index
 
Introduction to SQL Server in Containers
Introduction to SQL Server in ContainersIntroduction to SQL Server in Containers
Introduction to SQL Server in Containers
 
DevOps for the DBA
DevOps for the DBADevOps for the DBA
DevOps for the DBA
 
SQL Injection: How It Works, How to Stop It
SQL Injection: How It Works, How to Stop ItSQL Injection: How It Works, How to Stop It
SQL Injection: How It Works, How to Stop It
 
Privacy and Protection in the World of Database DevOps
Privacy and Protection in the World of Database DevOpsPrivacy and Protection in the World of Database DevOps
Privacy and Protection in the World of Database DevOps
 
SQL Server Tools for Query Tuning
SQL Server Tools for Query TuningSQL Server Tools for Query Tuning
SQL Server Tools for Query Tuning
 
Extending DevOps to SQL Server
Extending DevOps to SQL ServerExtending DevOps to SQL Server
Extending DevOps to SQL Server
 
Introducing Azure Databases
Introducing Azure DatabasesIntroducing Azure Databases
Introducing Azure Databases
 
Statistis, Row Counts, Execution Plans and Query Tuning
Statistis, Row Counts, Execution Plans and Query TuningStatistis, Row Counts, Execution Plans and Query Tuning
Statistis, Row Counts, Execution Plans and Query Tuning
 
Databases; The Elephant in the ALM Room
Databases; The Elephant in the ALM RoomDatabases; The Elephant in the ALM Room
Databases; The Elephant in the ALM Room
 
Being a DBA in the Future: Global Azure Bootcamp 2015
Being a DBA in the Future: Global Azure Bootcamp 2015Being a DBA in the Future: Global Azure Bootcamp 2015
Being a DBA in the Future: Global Azure Bootcamp 2015
 
Automated Database Deployment at SQL Rally
Automated Database Deployment at SQL RallyAutomated Database Deployment at SQL Rally
Automated Database Deployment at SQL Rally
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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...
 

Top Tips for Better T-SQL

  • 1. Grant Fritchey | www.ScaryDBA.com www.ScaryDBA.com Top Tips for Better T-SQL Stored Procedures Grant Fritchey – Red Gate Software
  • 2. Grant Fritchey | www.ScaryDBA.com Goal  Learn methods for writingT-SQL for readability  Understand how to write T-SQL for performance 2
  • 3. Grant Fritchey | www.ScaryDBA.com Get in touch scarydba.com grant@scarydba.com @gfritchey Grant Fritchey
  • 4. Grant Fritchey | www.ScaryDBA.com Agenda  Writing for readability » Object Names & Format » Comments » Error Handling » Personal Preferences  Writing for performance » DataTypes » Functions inComparisons » ImproperUse of Functions » The “Run Faster” Switch » InappropriateUse ofQuery Hints » Recompiles » Row byAgonizing Row » NestingViews 4
  • 5. Grant Fritchey | www.ScaryDBA.com Writing for Readability  Define a local standard » Object names » Comments » Format » Error handling  Enforce the standard » Document it » Code reviews 5
  • 6. Grant Fritchey | www.ScaryDBA.com Object Names & Format  Names should be descriptive » Procedures should be a phrase » Abbreviations should be common (no Ddltbl)  Use aliases » Clear » Common  Be consistent » A foolish consistency is the hobgoblin of little minds » Keyword in that sentence is “foolish” 6
  • 7. Grant Fritchey | www.ScaryDBA.com Comments  Do something  Most important is describing the action, not documentation  Use source control for documentation  Self-documenting code is a lie 7
  • 8. Grant Fritchey | www.ScaryDBA.com Error Handling  TRY/CATCH  Deadlocks  Establish local best practices 8
  • 9. Grant Fritchey | www.ScaryDBA.com Personal Preferences  CamelCase  Uppercase for reserve words and key words  Line breaks » On SELECT list » Between JOIN criteria » BetweenWHERE criteria  Use the semicolon  Indent » After initial SELECT » With ON clause » AfterWHERE clause 9
  • 10. Grant Fritchey | www.ScaryDBA.com Writing For Performance  Write for your data structures  Write for your indexes  Write for the query optimizer  Avoid common issues: » Data types » Functions in comparisons » Improper use of functions » The “run faster” switch » Inappropriate Query Hints » Recompiles » NullValues » Row By Agonizing Row » NestedViews 10
  • 11. Grant Fritchey | www.ScaryDBA.com Data Types  Problem » Implicit or explicit data type conversion  Indications » Scans » Slow performance  Solution » Use appropriate data types 11
  • 12. Grant Fritchey | www.ScaryDBA.com Functions in Comparisons  Problem » Function on column in WHERE or JOIN criteria  Indications » Scans » Slow performance  Solution » Don’t run functions on columns » Use sargeable functions 12
  • 13. Grant Fritchey | www.ScaryDBA.com Improper Use of Functions  Problem » Multi-statement user defined functions cause poor performance  Indications » Zero cost scan operator in exec plan » Very slow performance  Solution » When working with more than a few (~50?) rows, don’t use them » When using operations such as JOIN that require statistics, don’t use them 13
  • 14. Grant Fritchey | www.ScaryDBA.com The “Run Faster” Switch  Problem » Use of the NO_LOCK query hint everywhere, or setting transaction isolation level to READ_UNCOMMITTED  Indications » Extra rows in result set » Missing rows in result set  Solution » Tune the queries » Tune the structures » Use snapshot isolation levels  http://www.jasonstrate.com/2012/06/the-side-effect-of- nolock/ 14
  • 15. Grant Fritchey | www.ScaryDBA.com Query Hints  Problem » Query hints in the code such as FAST n, index hints, JOIN hints  Indications » Inconsistent performance behavior » Bad performance » Odd looking execution plans  Solution » Use of query hints should be exceptional » Exceptions are rare, not standard practice 15
  • 16. Grant Fritchey | www.ScaryDBA.com Recompiles  Problem » Excessive blocking and CPU contention caused by constant or long statement recompiles  Indications » Recompile events in extended events or trace » Blocking » High CPU usage  Solutions » Avoid interleaving DDL & DML » Where viable, use table variables 16
  • 17. Grant Fritchey | www.ScaryDBA.com Row by Agonizing Row  Problem » Cursors instead of set-based operations » WHILE loops instead of set-based operations » Multiple statements where 1 will do  Indications » Extremely slow performance  Solutions » Eliminate unnecessary row-by-row processing 17
  • 18. Grant Fritchey | www.ScaryDBA.com Nested Views  Problem » Views within views causes optimizer timeout  Indications » Incredibly complex query plans for simple queries » Very poor performance  Solutions » Don’t nest views » Materialize views 18
  • 19. Grant Fritchey | www.ScaryDBA.com Writing for Readability  Define a local standard » Object names » Comments » Format » Error handling  Enforce the standard » Document it » Code reviews 19
  • 20. Grant Fritchey | www.ScaryDBA.com Writing For Performance  Write for your data structures  Write for your indexes  Write for the query optimizer  Avoid common issues: » Data types » Functions in comparisons » Improper use of functions » The “run faster” switch » Inappropriate Query Hints » Recompiles » Row By Agonizing Row » NestedViews 20
  • 21. Grant Fritchey | www.ScaryDBA.com Goal  Learn methods for writingTSQL for readability  Understand how to write TSQL for performance 21
  • 22. Grant Fritchey | www.ScaryDBA.com Get in touch scarydba.com grant@scarydba.com @gfritchey Grant Fritchey
  • 23. Grant Fritchey | www.ScaryDBA.com Questions? 24