SlideShare a Scribd company logo
1 of 37
Gianluca Sartori
Owner
sqlconsulting.it
My query is slow,
now what?
2
Gianluca Sartori
• Independent SQL Server consultant
• Working with SQL Server since version 7
• MCTS, MCITP, MCT
• DBA @ Formula 1 team
Blog: spaghettidba.com
Twitter: @spaghettidba
3
Agenda
My query is slow!
The performance tuning pyramid
Schema design
Code optimization
Indexing
The performance tuning
pyramid
5
Schema design
7
Schema Design
Normalization
1NF:
Must have a key, atomic attributes only
2NF:
Each attribute depends on the whole key
3NF:
Each attribute depends only on the key
«The key, the whole key and nothing but the key,
so help me Codd»
8
Schema Design
Denormalization clues
• Data repeated  redundancy
• Inconsistent data  anomalies
• Data separated by «,»
eg: john@gmail.com, john@business.com
• Structured data in «notes» columns
• Column names with a numeric suffix
eg: Area1, Area2 , Area3…
9
Schema Design Worst Practices
No Primary Key or surrogate keys only
«Id» is not the only possible key!
No Foreign Keys
They’re «difficult» to deal with
No CHECK constraint
The application will enforce consistency…
Wrong data types
VAT number, Telephone number
Dates stored as strings
Use of NULL where inappropriate
Use of «dummy» values (eg: ‘.’ , 0)
Query Optimization
11
Query optimization
RBAR
Code Re-Use
Sort / DISTINCT
A query to rule them all
Redundant subqueries
12
Query optimization
• Row By Agonizing Row
• Cursors
• WHILE loops
• App-side cursors
• Scalar and multi-statement functions
http://www.sqlservercentral.com/Authors/Articles/Jeff_Moden/80567/
Jeff Moden
13
RBAR - Cursors
• Procedural code
• Fixed execution strategy  doesn’t scale!
• Use lots of memory and CPU
• Use lots of tempdb space
• Execute a huge amount of statements
• Can (almost) always be replaced with set-based code
14
RBAR
15
Code Reuse
• Stored procedures, functions and views encapsulate
the complexity
• Code reuse works as far as it doesn’t hurt performance
• What to avoid:
• Stored procedure invoked inside cursor loops
• Scalar functions with data access
• Multi-statement table-valued functions
• Views on views on views…
16
Code Reuse
Stored procedures encapsulate complex logic
• Different from OO
• No inheritance, polymorfism etc…
Impossible to combine with other constructs
• Require cursors to be applied on a set
• App-side cursors are no better!
• The same applies to ORMs
If no data modification happens, better use a function (ITVF if
possible)
17
Code Reuse – Cursors and stored procedures
18
Functions
Scalar functions work well for complex calculations with
NO data access
• Invoked for each row in the input set
• «hidden» RBAR
Better use inline table-valued functions
• Multi-statement table-valued functions return table
variables  estimated cardinality = 1
• Merged in the outer execution plan
19
Code Reuse – Scalar functions
Might look like a brilliant idea at first
• You can end up losing control
• Unneeded multiple accesses to the same tables
• Unnecessary JOINs
Views on views on views…
21
Code Reuse – Views on views on views…
22
SORT / DISTINCT
If not necessary, don’t sort results
DISTINCT is the refugium peccatorum for missed JOIN
predicates
EXISTS often helps avoiding CROSS JOINs for filter
predicates
UNION is always DISTINCT
Use UNION ALL whenever possible
One query to rule them all
• Set-based is ok, everything in one query is too much
• The optimizer is good, not perfect
• Too complex: where do we start from?
• Divide et impera
• Break the code into pieces
• CTEs
• Temporary tables
• Table Variables
• Functions
• Identify redundant pieces
• Re-assemble
• http://spaghettidba.com/2012/03/15/how-to-eat-a-sql-elephant/
24
Divide et impera
Redundant Subqueries
Indexing
26
Indexing
SARGAbility
Deciding which indexes to create?
Common mistakes
Included columns
Execution plan analysis
How to read an execution plan
What to look for
27
SARGAbility
SARGABLE = Search ARGument ABLE
A predicate is «sargable» when it can be evaluated by
means of an index
• Non-Sargable in general is every predicate that requires
transforming the column before evaluation
eg: functions
WHERE YEAR(order_date) = YEAR(GETDATE())
28
SARGabilty - examples
WHERE YEAR(SellStartDate) = YEAR(GETDATE())
WHERE SellStartDate >= DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
AND SellStartDate < DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)
WHERE ISNULL(ProductLine,'M') = 'M'
WHERE ProductLine = 'M' OR ProductLine IS NULL
WHERE LEFT(ProductNumber,2) = 'BK'
WHERE ProductNumber LIKE 'BK%'
29
Deciding which indexes to create
Create indexes to support the following predicates
• WHERE
• JOIN
• GROUP BY
• ORDER BY
Indexes are used effectively when the leading column appears
in the predicate
Execution plans suggest missing indexes
• Watch out from overly «aggressive» suggestions
30
Common mistakes
• One index for each column
• Missing indexes on Foreign Keys
• Accepting all suggestions from the DB Tuning Advisor
• Duplicate Indexes
• Sub-optimal clustered index
• Unique
• Small
• Invariable
• Ever-increasing
• Not testing on the whole workload
31
Included columns
Columns not present in filter predicates but only in the
SELECT list can be included
Included columns are not for free
• Present at leaf level in the B-tree
• Contribute to index size
Clustered index always includes all columns
Nonclustered indexes always include the clustering key
32
Execution plans
Output of the query optimizer
T-SQL
statement
Parser Algebrizer
Algebrizer
Tree
Optimizer
Statistics
Execution Plan
33
Execution plans
How to read an execution plan
34
Execution plans
What to look for:
Implicit conversions
Scans
Missing JOIN predicate alerts
Spools
Sorts
Parallelism
Wrong cardinality estimates
35
Recap
Simplify code
RBAR is the root of all evil
Remove redundant accesses
Divide et impera
Execution plans
Adding indexes may help
Unused indexes?
SARGability
Included columns
Schema design mistakes?
Q&A.
My Query is slow, now what?

More Related Content

Viewers also liked

Consolidation of diamond mines final draft
Consolidation of diamond mines  final draftConsolidation of diamond mines  final draft
Consolidation of diamond mines final draftZELA_infor
 
The Tipping Point - Final Presentation
The Tipping Point - Final PresentationThe Tipping Point - Final Presentation
The Tipping Point - Final PresentationCamilh
 
презентация Costa alta copy (1)
презентация Costa alta copy (1)презентация Costa alta copy (1)
презентация Costa alta copy (1)safework12
 
аз жаргалтай үлгэр
аз жаргалтай үлгэраз жаргалтай үлгэр
аз жаргалтай үлгэрNyamzaya Gerelzaya
 
A review of Zimbabwe's draft minerals policy by ZELA
A review of Zimbabwe's draft minerals policy by ZELA A review of Zimbabwe's draft minerals policy by ZELA
A review of Zimbabwe's draft minerals policy by ZELA ZELA_infor
 
How to make a relationship last
How to make a relationship lastHow to make a relationship last
How to make a relationship lastJen Vuhuong
 
68 transaction scheduling in distributed real time systems
68 transaction scheduling in distributed real time systems68 transaction scheduling in distributed real time systems
68 transaction scheduling in distributed real time systemsRoyalzig Luxury Furniture
 
Research, social media and getting published
Research, social media and getting publishedResearch, social media and getting published
Research, social media and getting publishedLeah Emary
 

Viewers also liked (10)

Consolidation of diamond mines final draft
Consolidation of diamond mines  final draftConsolidation of diamond mines  final draft
Consolidation of diamond mines final draft
 
The Tipping Point - Final Presentation
The Tipping Point - Final PresentationThe Tipping Point - Final Presentation
The Tipping Point - Final Presentation
 
презентация Costa alta copy (1)
презентация Costa alta copy (1)презентация Costa alta copy (1)
презентация Costa alta copy (1)
 
аз жаргалтай үлгэр
аз жаргалтай үлгэраз жаргалтай үлгэр
аз жаргалтай үлгэр
 
A review of Zimbabwe's draft minerals policy by ZELA
A review of Zimbabwe's draft minerals policy by ZELA A review of Zimbabwe's draft minerals policy by ZELA
A review of Zimbabwe's draft minerals policy by ZELA
 
How to make a relationship last
How to make a relationship lastHow to make a relationship last
How to make a relationship last
 
Pregunta de investigacion
Pregunta  de  investigacionPregunta  de  investigacion
Pregunta de investigacion
 
68 transaction scheduling in distributed real time systems
68 transaction scheduling in distributed real time systems68 transaction scheduling in distributed real time systems
68 transaction scheduling in distributed real time systems
 
Research, social media and getting published
Research, social media and getting publishedResearch, social media and getting published
Research, social media and getting published
 
2014 the boulder history museum
2014 the boulder history museum2014 the boulder history museum
2014 the boulder history museum
 

Similar to My Query is slow, now what?

Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014Ike Ellis
 
SqlDay 2018 - Brief introduction into SQL Server Execution Plans
SqlDay 2018 - Brief introduction into SQL Server Execution PlansSqlDay 2018 - Brief introduction into SQL Server Execution Plans
SqlDay 2018 - Brief introduction into SQL Server Execution PlansMarek Maśko
 
The Plan Cache Whisperer - Performance Tuning SQL Server
The Plan Cache Whisperer - Performance Tuning SQL ServerThe Plan Cache Whisperer - Performance Tuning SQL Server
The Plan Cache Whisperer - Performance Tuning SQL ServerJason Strate
 
Postgres for MySQL (and other database) people
Postgres for MySQL (and other database) peoplePostgres for MySQL (and other database) people
Postgres for MySQL (and other database) peopleCommand Prompt., Inc
 
SQL Server Tips & Tricks
SQL Server Tips & TricksSQL Server Tips & Tricks
SQL Server Tips & TricksIke Ellis
 
Geek Sync I Consolidating Indexes in SQL Server
Geek Sync I Consolidating Indexes in SQL ServerGeek Sync I Consolidating Indexes in SQL Server
Geek Sync I Consolidating Indexes in SQL ServerIDERA Software
 
3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sqlŁukasz Grala
 
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019Dave Stokes
 
Optimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptxOptimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptxJasonTuran2
 
SQL Server Worst Practices - EN
SQL Server Worst Practices - ENSQL Server Worst Practices - EN
SQL Server Worst Practices - ENGianluca Sartori
 
Performance Tuning with Execution Plans
Performance Tuning with Execution PlansPerformance Tuning with Execution Plans
Performance Tuning with Execution PlansGrant Fritchey
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statementsxKinAnx
 
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...Dave Stokes
 
Database and application performance vivek sharma
Database and application performance vivek sharmaDatabase and application performance vivek sharma
Database and application performance vivek sharmaaioughydchapter
 
Oracle SQL tuning with SQL Plan Management
Oracle SQL tuning with SQL Plan ManagementOracle SQL tuning with SQL Plan Management
Oracle SQL tuning with SQL Plan ManagementBjoern Rost
 
Sql Performance Tuning For Developers
Sql Performance Tuning For DevelopersSql Performance Tuning For Developers
Sql Performance Tuning For Developerssqlserver.co.il
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysisRiteshkiit
 
Saleforce For Domino Dogs
Saleforce For Domino DogsSaleforce For Domino Dogs
Saleforce For Domino DogsMark Myers
 

Similar to My Query is slow, now what? (20)

Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014
 
SqlDay 2018 - Brief introduction into SQL Server Execution Plans
SqlDay 2018 - Brief introduction into SQL Server Execution PlansSqlDay 2018 - Brief introduction into SQL Server Execution Plans
SqlDay 2018 - Brief introduction into SQL Server Execution Plans
 
The Plan Cache Whisperer - Performance Tuning SQL Server
The Plan Cache Whisperer - Performance Tuning SQL ServerThe Plan Cache Whisperer - Performance Tuning SQL Server
The Plan Cache Whisperer - Performance Tuning SQL Server
 
Postgres for MySQL (and other database) people
Postgres for MySQL (and other database) peoplePostgres for MySQL (and other database) people
Postgres for MySQL (and other database) people
 
SQL Server Tips & Tricks
SQL Server Tips & TricksSQL Server Tips & Tricks
SQL Server Tips & Tricks
 
Geek Sync I Consolidating Indexes in SQL Server
Geek Sync I Consolidating Indexes in SQL ServerGeek Sync I Consolidating Indexes in SQL Server
Geek Sync I Consolidating Indexes in SQL Server
 
Exploring T-SQL Anti-Patterns
Exploring T-SQL Anti-Patterns Exploring T-SQL Anti-Patterns
Exploring T-SQL Anti-Patterns
 
3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql3 CityNetConf - sql+c#=u-sql
3 CityNetConf - sql+c#=u-sql
 
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
 
Optimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptxOptimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptx
 
SQL Server Worst Practices - EN
SQL Server Worst Practices - ENSQL Server Worst Practices - EN
SQL Server Worst Practices - EN
 
Performance Tuning with Execution Plans
Performance Tuning with Execution PlansPerformance Tuning with Execution Plans
Performance Tuning with Execution Plans
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
 
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
 
Database and application performance vivek sharma
Database and application performance vivek sharmaDatabase and application performance vivek sharma
Database and application performance vivek sharma
 
Oracle SQL tuning with SQL Plan Management
Oracle SQL tuning with SQL Plan ManagementOracle SQL tuning with SQL Plan Management
Oracle SQL tuning with SQL Plan Management
 
JSSUG: SQL Sever Index Tuning
JSSUG: SQL Sever Index TuningJSSUG: SQL Sever Index Tuning
JSSUG: SQL Sever Index Tuning
 
Sql Performance Tuning For Developers
Sql Performance Tuning For DevelopersSql Performance Tuning For Developers
Sql Performance Tuning For Developers
 
Sql query performance analysis
Sql query performance analysisSql query performance analysis
Sql query performance analysis
 
Saleforce For Domino Dogs
Saleforce For Domino DogsSaleforce For Domino Dogs
Saleforce For Domino Dogs
 

More from Gianluca Sartori

SQL Server 2016 New Security Features
SQL Server 2016 New Security FeaturesSQL Server 2016 New Security Features
SQL Server 2016 New Security FeaturesGianluca Sartori
 
Responding to extended events in near real time
Responding to extended events in near real timeResponding to extended events in near real time
Responding to extended events in near real timeGianluca Sartori
 
Sql server security in an insecure world
Sql server security in an insecure worldSql server security in an insecure world
Sql server security in an insecure worldGianluca Sartori
 
TSQL Advanced Query Techniques
TSQL Advanced Query TechniquesTSQL Advanced Query Techniques
TSQL Advanced Query TechniquesGianluca Sartori
 
SQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisSQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisGianluca Sartori
 
A performance tuning methodology
A performance tuning methodologyA performance tuning methodology
A performance tuning methodologyGianluca Sartori
 
SQL Server Worst Practices
SQL Server Worst PracticesSQL Server Worst Practices
SQL Server Worst PracticesGianluca Sartori
 

More from Gianluca Sartori (9)

Benchmarking like a pro
Benchmarking like a proBenchmarking like a pro
Benchmarking like a pro
 
Sql server infernals
Sql server infernalsSql server infernals
Sql server infernals
 
SQL Server 2016 New Security Features
SQL Server 2016 New Security FeaturesSQL Server 2016 New Security Features
SQL Server 2016 New Security Features
 
Responding to extended events in near real time
Responding to extended events in near real timeResponding to extended events in near real time
Responding to extended events in near real time
 
Sql server security in an insecure world
Sql server security in an insecure worldSql server security in an insecure world
Sql server security in an insecure world
 
TSQL Advanced Query Techniques
TSQL Advanced Query TechniquesTSQL Advanced Query Techniques
TSQL Advanced Query Techniques
 
SQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload AnalysisSQL Server Benchmarking, Baselining and Workload Analysis
SQL Server Benchmarking, Baselining and Workload Analysis
 
A performance tuning methodology
A performance tuning methodologyA performance tuning methodology
A performance tuning methodology
 
SQL Server Worst Practices
SQL Server Worst PracticesSQL Server Worst Practices
SQL Server Worst Practices
 

Recently uploaded

How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 

Recently uploaded (20)

How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 

My Query is slow, now what?

  • 2. 2 Gianluca Sartori • Independent SQL Server consultant • Working with SQL Server since version 7 • MCTS, MCITP, MCT • DBA @ Formula 1 team Blog: spaghettidba.com Twitter: @spaghettidba
  • 3. 3 Agenda My query is slow! The performance tuning pyramid Schema design Code optimization Indexing
  • 5. 5
  • 7. 7 Schema Design Normalization 1NF: Must have a key, atomic attributes only 2NF: Each attribute depends on the whole key 3NF: Each attribute depends only on the key «The key, the whole key and nothing but the key, so help me Codd»
  • 8. 8 Schema Design Denormalization clues • Data repeated  redundancy • Inconsistent data  anomalies • Data separated by «,» eg: john@gmail.com, john@business.com • Structured data in «notes» columns • Column names with a numeric suffix eg: Area1, Area2 , Area3…
  • 9. 9 Schema Design Worst Practices No Primary Key or surrogate keys only «Id» is not the only possible key! No Foreign Keys They’re «difficult» to deal with No CHECK constraint The application will enforce consistency… Wrong data types VAT number, Telephone number Dates stored as strings Use of NULL where inappropriate Use of «dummy» values (eg: ‘.’ , 0)
  • 11. 11 Query optimization RBAR Code Re-Use Sort / DISTINCT A query to rule them all Redundant subqueries
  • 12. 12 Query optimization • Row By Agonizing Row • Cursors • WHILE loops • App-side cursors • Scalar and multi-statement functions http://www.sqlservercentral.com/Authors/Articles/Jeff_Moden/80567/ Jeff Moden
  • 13. 13 RBAR - Cursors • Procedural code • Fixed execution strategy  doesn’t scale! • Use lots of memory and CPU • Use lots of tempdb space • Execute a huge amount of statements • Can (almost) always be replaced with set-based code
  • 15. 15 Code Reuse • Stored procedures, functions and views encapsulate the complexity • Code reuse works as far as it doesn’t hurt performance • What to avoid: • Stored procedure invoked inside cursor loops • Scalar functions with data access • Multi-statement table-valued functions • Views on views on views…
  • 16. 16 Code Reuse Stored procedures encapsulate complex logic • Different from OO • No inheritance, polymorfism etc… Impossible to combine with other constructs • Require cursors to be applied on a set • App-side cursors are no better! • The same applies to ORMs If no data modification happens, better use a function (ITVF if possible)
  • 17. 17 Code Reuse – Cursors and stored procedures
  • 18. 18 Functions Scalar functions work well for complex calculations with NO data access • Invoked for each row in the input set • «hidden» RBAR Better use inline table-valued functions • Multi-statement table-valued functions return table variables  estimated cardinality = 1 • Merged in the outer execution plan
  • 19. 19 Code Reuse – Scalar functions
  • 20. Might look like a brilliant idea at first • You can end up losing control • Unneeded multiple accesses to the same tables • Unnecessary JOINs Views on views on views…
  • 21. 21 Code Reuse – Views on views on views…
  • 22. 22 SORT / DISTINCT If not necessary, don’t sort results DISTINCT is the refugium peccatorum for missed JOIN predicates EXISTS often helps avoiding CROSS JOINs for filter predicates UNION is always DISTINCT Use UNION ALL whenever possible
  • 23. One query to rule them all • Set-based is ok, everything in one query is too much • The optimizer is good, not perfect • Too complex: where do we start from? • Divide et impera • Break the code into pieces • CTEs • Temporary tables • Table Variables • Functions • Identify redundant pieces • Re-assemble • http://spaghettidba.com/2012/03/15/how-to-eat-a-sql-elephant/
  • 26. 26 Indexing SARGAbility Deciding which indexes to create? Common mistakes Included columns Execution plan analysis How to read an execution plan What to look for
  • 27. 27 SARGAbility SARGABLE = Search ARGument ABLE A predicate is «sargable» when it can be evaluated by means of an index • Non-Sargable in general is every predicate that requires transforming the column before evaluation eg: functions WHERE YEAR(order_date) = YEAR(GETDATE())
  • 28. 28 SARGabilty - examples WHERE YEAR(SellStartDate) = YEAR(GETDATE()) WHERE SellStartDate >= DATEADD(yy, DATEDIFF(yy,0,getdate()), 0) AND SellStartDate < DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0) WHERE ISNULL(ProductLine,'M') = 'M' WHERE ProductLine = 'M' OR ProductLine IS NULL WHERE LEFT(ProductNumber,2) = 'BK' WHERE ProductNumber LIKE 'BK%'
  • 29. 29 Deciding which indexes to create Create indexes to support the following predicates • WHERE • JOIN • GROUP BY • ORDER BY Indexes are used effectively when the leading column appears in the predicate Execution plans suggest missing indexes • Watch out from overly «aggressive» suggestions
  • 30. 30 Common mistakes • One index for each column • Missing indexes on Foreign Keys • Accepting all suggestions from the DB Tuning Advisor • Duplicate Indexes • Sub-optimal clustered index • Unique • Small • Invariable • Ever-increasing • Not testing on the whole workload
  • 31. 31 Included columns Columns not present in filter predicates but only in the SELECT list can be included Included columns are not for free • Present at leaf level in the B-tree • Contribute to index size Clustered index always includes all columns Nonclustered indexes always include the clustering key
  • 32. 32 Execution plans Output of the query optimizer T-SQL statement Parser Algebrizer Algebrizer Tree Optimizer Statistics Execution Plan
  • 33. 33 Execution plans How to read an execution plan
  • 34. 34 Execution plans What to look for: Implicit conversions Scans Missing JOIN predicate alerts Spools Sorts Parallelism Wrong cardinality estimates
  • 35. 35 Recap Simplify code RBAR is the root of all evil Remove redundant accesses Divide et impera Execution plans Adding indexes may help Unused indexes? SARGability Included columns Schema design mistakes?
  • 36. Q&A.