SlideShare a Scribd company logo
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

Performance Tuning Azure SQL Database
Performance Tuning Azure SQL DatabasePerformance Tuning Azure SQL Database
Performance Tuning Azure SQL Database
Grant Fritchey
 
Understanding Your Servers, All Your Servers
Understanding Your Servers, All Your ServersUnderstanding Your Servers, All Your Servers
Understanding Your Servers, All Your Servers
Grant Fritchey
 
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
Grant Fritchey
 
التحدى 6 الإستعلام بطريقة المعالج
التحدى 6 الإستعلام بطريقة المعالجالتحدى 6 الإستعلام بطريقة المعالج
التحدى 6 الإستعلام بطريقة المعالج
bosy sadek
 
Trabalho fitos digitais
Trabalho fitos digitaisTrabalho fitos digitais
Trabalho fitos digitais
Guilherme Matias de Medeiros
 
Lesson4 Protect and maintain databases
Lesson4 Protect and maintain databases Lesson4 Protect and maintain databases
Lesson4 Protect and maintain databases
Abdullatif Tarakji
 
Lesson8 Manage Records
Lesson8 Manage RecordsLesson8 Manage Records
Lesson8 Manage Records
Abdullatif Tarakji
 
Lesson11 Create Query
Lesson11 Create QueryLesson11 Create Query
Lesson11 Create Query
Abdullatif Tarakji
 
MarketLine Country Statistics Database
MarketLine Country Statistics DatabaseMarketLine Country Statistics Database
MarketLine Country Statistics DatabaseMarketLine
 
Oracle hard and soft parsing
Oracle hard and soft parsingOracle hard and soft parsing
Oracle hard and soft parsingIshaan Guliani
 
Lesson5 Print and export databases
Lesson5 Print and export databases Lesson5 Print and export databases
Lesson5 Print and export databases
Abdullatif Tarakji
 
الوحدة التاسعة - قاعدة البيانات وادارتها
الوحدة التاسعة - قاعدة البيانات وادارتهاالوحدة التاسعة - قاعدة البيانات وادارتها
الوحدة التاسعة - قاعدة البيانات وادارتها
Amin Abu Hammad
 
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
Ramin Orujov
 
أساسيات التأمين
أساسيات التأمينأساسيات التأمين
Top frinds-انشاء-استعلام-بطريقه-المعالج-6-copy
Top frinds-انشاء-استعلام-بطريقه-المعالج-6-copyTop frinds-انشاء-استعلام-بطريقه-المعالج-6-copy
Top frinds-انشاء-استعلام-بطريقه-المعالج-6-copy
top friends
 
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
Mark Ginnebaugh
 
Database system concepts and architecture
Database system concepts and architectureDatabase system concepts and architecture
Database system concepts and architecture
Mahmoud Almadhoun
 
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
Tung Nguyen Thanh
 

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

SQL Server Optimization Checklist
SQL Server Optimization ChecklistSQL Server Optimization Checklist
SQL Server Optimization Checklist
Grant Fritchey
 
Introducing Azure SQL Data Warehouse
Introducing Azure SQL Data WarehouseIntroducing Azure SQL Data Warehouse
Introducing Azure SQL Data Warehouse
Grant Fritchey
 
Query Tuning Azure SQL Databases
Query Tuning Azure SQL DatabasesQuery Tuning Azure SQL Databases
Query Tuning Azure SQL Databases
Grant Fritchey
 
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
SolarWinds
 
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
Red Gate Software
 
Владимир Бронников (Senior .NET Developer, Perfectial) “Performance optimizat...
Владимир Бронников (Senior .NET Developer, Perfectial) “Performance optimizat...Владимир Бронников (Senior .NET Developer, Perfectial) “Performance optimizat...
Владимир Бронников (Senior .NET Developer, Perfectial) “Performance optimizat...
DataArt
 
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...
SPC Adriatics
 
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
Edureka!
 
Database and application performance vivek sharma
Database and application performance vivek sharmaDatabase and application performance vivek sharma
Database and application performance vivek sharma
aioughydchapter
 
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
Mark Rackley
 
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
InternetCreations
 
Performance By Design
Performance By DesignPerformance By Design
Performance By Design
Guy Harrison
 
Mrdp reduce side_join
Mrdp reduce side_joinMrdp reduce side_join
Mrdp reduce side_join
Edureka!
 
5 physical data modeling blunders 09092010
5 physical data modeling blunders 090920105 physical data modeling blunders 09092010
5 physical data modeling blunders 09092010ERwin Modeling
 
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
 
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
 
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
 
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
Petter Holmström
 
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
Lars Kamp
 

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
Using Compass to Diagnose Performance Problems Using Compass to Diagnose Performance Problems
Using Compass to Diagnose Performance Problems
 
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
 
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

Migrating To PostgreSQL
Migrating To PostgreSQLMigrating To PostgreSQL
Migrating To PostgreSQL
Grant Fritchey
 
PostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and AlertingPostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and Alerting
Grant Fritchey
 
Automating Database Deployments Using Azure DevOps
Automating Database Deployments Using Azure DevOpsAutomating Database Deployments Using Azure DevOps
Automating Database Deployments Using Azure DevOps
Grant Fritchey
 
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
Grant Fritchey
 
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
Grant Fritchey
 
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
Grant Fritchey
 
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
Grant Fritchey
 
10 Steps To Global Data Compliance
10 Steps To Global Data Compliance10 Steps To Global Data Compliance
10 Steps To Global Data Compliance
Grant Fritchey
 
Time to Use the Columnstore Index
Time to Use the Columnstore IndexTime to Use the Columnstore Index
Time to Use the Columnstore Index
Grant Fritchey
 
Introduction to SQL Server in Containers
Introduction to SQL Server in ContainersIntroduction to SQL Server in Containers
Introduction to SQL Server in Containers
Grant Fritchey
 
DevOps for the DBA
DevOps for the DBADevOps for the DBA
DevOps for the DBA
Grant Fritchey
 
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
Grant Fritchey
 
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
Grant Fritchey
 
SQL Server Tools for Query Tuning
SQL Server Tools for Query TuningSQL Server Tools for Query Tuning
SQL Server Tools for Query Tuning
Grant Fritchey
 
Extending DevOps to SQL Server
Extending DevOps to SQL ServerExtending DevOps to SQL Server
Extending DevOps to SQL Server
Grant Fritchey
 
Introducing Azure Databases
Introducing Azure DatabasesIntroducing Azure Databases
Introducing Azure Databases
Grant Fritchey
 
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
Grant Fritchey
 
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
Grant Fritchey
 
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
Grant Fritchey
 
Automated Database Deployment at SQL Rally
Automated Database Deployment at SQL RallyAutomated Database Deployment at SQL Rally
Automated Database Deployment at SQL Rally
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

GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 

Recently uploaded (20)

GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 

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