SlideShare a Scribd company logo
How to Build Fast
Multi-Parameter Stored Procs
About me
1999-05: dev, architect, DBA
2005-08: DBA, VM/SAN admin
2008-10: MCM, Quest Software
Ever since: consulting DBA
BrentOzar.com/go/dynamicsql
Agenda
What we’re trying to do
A few ways we shouldn’t do it, and why
The “right” way: sp_executesql
The drawbacks of the right way
Pro tips: troubleshooting and tuning
“I want a search page.”
Every user, ever
Q&A site: you ask, other people do your job
Whole database is available under Creative Commons
Download it free: BrentOzar.com/go/querystack
We’ll use the dbo.Users table
How big is our Users table today?
Stored proc in your resources
StackOverflow2010
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Our proc has to look like this:
CREATE OR ALTER PROC dbo.usp_SearchUsers
@SearchDisplayName NVARCHAR(100) = NULL,
@SearchLocation NVARCHAR(100) = NULL,
@SearchReputation INT = NULL…
And folks want to pass in 1, 2, or 3 parameters, like just
DisplayName, OR
both Location and Reputation, and filter both.
But we wanna do less reads, so…
CREATE INDEX IX_DisplayName
ON dbo.Users(DisplayName);
CREATE INDEX IX_Location
ON dbo.Users(Location);
CREATE INDEX IX_Reputation
ON dbo.Users(Reputation);
Version 1:
the really bad idea
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
At first glance, it works.
Granted, the results aren’t accurate,
but it is willing to use indexes.
But there’s a catch.
2 different param sets
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
The London sort is spilling to disk
Because we underestimated rows
Not even close
Remember, 7748 pages in the table
We’re hitting parameter sniffing.
SQL Server compiles the entire plan
the first time it runs,
using the parameter values it was first run with.
So it’s optimizing the @SearchLocation branch with a null
@SearchLocation value.
This design has 3 big problems.
1. It produces the wrong results for param combos.
2. It’s a little TOO willing to use indexes,
even when they’re worse than a table scan.
3. It underestimates memory grants.
Version 2, OR:
accurate results
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
2 different param sets
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
SQL Server builds a plan for a name
But it may not ALWAYS have a name
Oddly, this performs fine
IF you don’t have any indexes.
Version 3:
COALESCE
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Welcome to Scandinavia
Sure, key lookups too
Not great on reads, either
Version 4:
Dynamic SQL
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
2 different param sets
Logical reads look good, too
What if we run it for combos?
There’s a catch.
Clear the cache and run a few.
We bloat the plan cache a little.
The proc has its own entry, executed 6 times.
Each dynamic SQL string gets its own line.
But each dynamic plan is great* for that set of parameters!
* Not necessarily.
I got 99 problems plans
Each dynamic SQL plan has its own:
• Plan cache entry
• Memory grant
• Row estimations
• Parameter sniffing issues
Yes, I can still have param sniffing.
Chicago: big, but not huge.
London: big enough that a scan makes more sense.
If Chicago runs first…
We cache a plan with a seek.
And reuse it for London.
If London runs first…
We cache a plan with a scan.
And reuse it for Chicago
But the memory grant is too big.
Dynamic SQL
Gives you the luxury of multiple plans,
one for each set of parameters
But curses you with multiple plans,
each of which may have parameter sniffing issues.
There’s much more to learn.
Your demo scripts continue with pro tips for:
• Using comments inside the dynamic SQL string itself
for tracking down the source
• Formatting the strings with CR/LR
• Using debug variables to print at strategic times
• The perils of dynamic sorting
Download: BrentOzar.com/go/dynamicsql
Erland goes even deeper.
Alternate tables, forced recompilation, CLR…

More Related Content

PDF
Ruby で高速なプログラムを書く
PDF
これでBigQueryをドヤ顔で語れる!BigQueryの基本
PDF
MySQL・PostgreSQLだけで作る高速あいまい全文検索システム
PDF
How We Optimize Spark SQL Jobs With parallel and sync IO
PDF
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
PPTX
機械学習、グラフ分析、SQLによるサイバー攻撃対策事例(金融業界)
PPTX
How to Actually Tune Your Spark Jobs So They Work
PDF
10分で分かるLinuxブロックレイヤ
Ruby で高速なプログラムを書く
これでBigQueryをドヤ顔で語れる!BigQueryの基本
MySQL・PostgreSQLだけで作る高速あいまい全文検索システム
How We Optimize Spark SQL Jobs With parallel and sync IO
Deep Dive into Project Tungsten: Bringing Spark Closer to Bare Metal-(Josh Ro...
機械学習、グラフ分析、SQLによるサイバー攻撃対策事例(金融業界)
How to Actually Tune Your Spark Jobs So They Work
10分で分かるLinuxブロックレイヤ

What's hot (20)

PDF
手作業なしの安定環境実現に向けたZabbix活用方法紹介+Zabbix2.4最新機能紹介
PDF
XML と PHP のイケナイ関係 (セキュリティ的な意味で) -Introduction of XXE attack and XML Bomb with...
PDF
サイバージェント 秋葉原ラボのHBase 活用事例
PDF
2019/4/18 Zabbix勉強会 徹底活用本の改訂の話
PPTX
YARN Under The Hood
PDF
OSMC 2022 | Logstash, Beats, Elastic Agent, Open Telemetry — what’s the right...
PDF
Sherlock: an anomaly detection service on top of Druid
PDF
Parquet performance tuning: the missing guide
PPTX
なぜ、CData Softwareが Power BI 専用 コネクターを 開発したのか?
PDF
MongoDBを用いたソーシャルアプリのログ解析 〜解析基盤構築からフロントUIまで、MongoDBを最大限に活用する〜
PDF
システム監視のアラート大量発生を抑えるZabbixトリガー「依存関係」機能の紹介
PDF
より深く知るオプティマイザとそのチューニング
PDF
第11回ACRiウェビナー_インテル/竹村様ご講演資料
PDF
マルチコアのプログラミング技法 -- OpenCLとWebCL
PDF
Docker ComposeでMastodonが必要なものを梱包する話
PPTX
Get Your Insecure PostgreSQL Passwords to SCRAM
PDF
アクセスプラン(実行計画)の読み方入門
PDF
AWS Black Belt Techシリーズ Amazon Redshift
PDF
Holistic data application quality
PPTX
祝!PostgreSQLレプリケーション10周年!徹底紹介!!
手作業なしの安定環境実現に向けたZabbix活用方法紹介+Zabbix2.4最新機能紹介
XML と PHP のイケナイ関係 (セキュリティ的な意味で) -Introduction of XXE attack and XML Bomb with...
サイバージェント 秋葉原ラボのHBase 活用事例
2019/4/18 Zabbix勉強会 徹底活用本の改訂の話
YARN Under The Hood
OSMC 2022 | Logstash, Beats, Elastic Agent, Open Telemetry — what’s the right...
Sherlock: an anomaly detection service on top of Druid
Parquet performance tuning: the missing guide
なぜ、CData Softwareが Power BI 専用 コネクターを 開発したのか?
MongoDBを用いたソーシャルアプリのログ解析 〜解析基盤構築からフロントUIまで、MongoDBを最大限に活用する〜
システム監視のアラート大量発生を抑えるZabbixトリガー「依存関係」機能の紹介
より深く知るオプティマイザとそのチューニング
第11回ACRiウェビナー_インテル/竹村様ご講演資料
マルチコアのプログラミング技法 -- OpenCLとWebCL
Docker ComposeでMastodonが必要なものを梱包する話
Get Your Insecure PostgreSQL Passwords to SCRAM
アクセスプラン(実行計画)の読み方入門
AWS Black Belt Techシリーズ Amazon Redshift
Holistic data application quality
祝!PostgreSQLレプリケーション10周年!徹底紹介!!
Ad

Similar to Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures (20)

PPTX
"But It Worked In Development!" - 3 Hard SQL Server Problems
PPTX
What Your Database Query is Really Doing
PPTX
Introduction to SQL Server Internals: How to Think Like the Engine
PPTX
How to think like the engine
PDF
Catalyst - refactor large apps with it and have fun!
PPTX
7 Database Mistakes YOU Are Making -- Linuxfest Northwest 2019
PPTX
How to Think Like the SQL Server Engine
PDF
If NoSQL is your answer, you are probably asking the wrong question.
PPTX
SQL to NoSQL: Top 6 Questions
PPTX
DMDW Extra Lesson - NoSql and MongoDB
PDF
SQL Server Managing Test Data & Stress Testing January 2011
PDF
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
PPTX
Using Cassandra with your Web Application
PPTX
Scaling Up Machine Learning Experimentation at Tubi 5x and Beyond
PPTX
Machine Learning with ML.NET and Azure - Andy Cross
PPT
Enterprise NoSQL: Silver Bullet or Poison Pill
PDF
Live Query Statistics & Query Store in SQL Server 2016
PDF
Architecture by Accident
PDF
SQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginners
PPTX
Improving Drupal Performances
"But It Worked In Development!" - 3 Hard SQL Server Problems
What Your Database Query is Really Doing
Introduction to SQL Server Internals: How to Think Like the Engine
How to think like the engine
Catalyst - refactor large apps with it and have fun!
7 Database Mistakes YOU Are Making -- Linuxfest Northwest 2019
How to Think Like the SQL Server Engine
If NoSQL is your answer, you are probably asking the wrong question.
SQL to NoSQL: Top 6 Questions
DMDW Extra Lesson - NoSql and MongoDB
SQL Server Managing Test Data & Stress Testing January 2011
Ingesting Over Four Million Rows Per Second With QuestDB Timeseries Database ...
Using Cassandra with your Web Application
Scaling Up Machine Learning Experimentation at Tubi 5x and Beyond
Machine Learning with ML.NET and Azure - Andy Cross
Enterprise NoSQL: Silver Bullet or Poison Pill
Live Query Statistics & Query Store in SQL Server 2016
Architecture by Accident
SQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginners
Improving Drupal Performances
Ad

More from Brent Ozar (14)

PDF
Fundamentals of TempDB
PDF
Fundamentals of Columnstore - Introductions
PPTX
Top 10 Developer Mistakes That Won't Scale with SQL Server
PPTX
Deadlocks: Lets Do One, Understand It, and Fix It
PPTX
Help! SQL Server 2008 is Still Here!
PPTX
An Introduction to GitHub for DBAs - Brent Ozar
PPTX
SQL Query Optimization: Why Is It So Hard to Get Right?
PDF
Headaches of Blocking, Locking, and Deadlocking
PPTX
Columnstore Customer Stories 2016 by Sunil Agarwal
PPTX
500-Level Guide to Career Internals
PPTX
Building a Fast, Reliable SQL Server for kCura Relativity
PPTX
How to Make SQL Server Go Faster
PPTX
500-Level Guide to Career Internals
PPTX
What I Learned About SQL Server at Ignite 2015
Fundamentals of TempDB
Fundamentals of Columnstore - Introductions
Top 10 Developer Mistakes That Won't Scale with SQL Server
Deadlocks: Lets Do One, Understand It, and Fix It
Help! SQL Server 2008 is Still Here!
An Introduction to GitHub for DBAs - Brent Ozar
SQL Query Optimization: Why Is It So Hard to Get Right?
Headaches of Blocking, Locking, and Deadlocking
Columnstore Customer Stories 2016 by Sunil Agarwal
500-Level Guide to Career Internals
Building a Fast, Reliable SQL Server for kCura Relativity
How to Make SQL Server Go Faster
500-Level Guide to Career Internals
What I Learned About SQL Server at Ignite 2015

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Cloud computing and distributed systems.
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
Teaching material agriculture food technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Encapsulation_ Review paper, used for researhc scholars
Digital-Transformation-Roadmap-for-Companies.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
MYSQL Presentation for SQL database connectivity
Per capita expenditure prediction using model stacking based on satellite ima...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Spectral efficient network and resource selection model in 5G networks
“AI and Expert System Decision Support & Business Intelligence Systems”
Reach Out and Touch Someone: Haptics and Empathic Computing
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Network Security Unit 5.pdf for BCA BBA.
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Cloud computing and distributed systems.
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
The AUB Centre for AI in Media Proposal.docx
Chapter 3 Spatial Domain Image Processing.pdf
Teaching material agriculture food technology

Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures

  • 1. How to Build Fast Multi-Parameter Stored Procs
  • 2. About me 1999-05: dev, architect, DBA 2005-08: DBA, VM/SAN admin 2008-10: MCM, Quest Software Ever since: consulting DBA BrentOzar.com/go/dynamicsql
  • 3. Agenda What we’re trying to do A few ways we shouldn’t do it, and why The “right” way: sp_executesql The drawbacks of the right way Pro tips: troubleshooting and tuning
  • 4. “I want a search page.” Every user, ever
  • 5. Q&A site: you ask, other people do your job Whole database is available under Creative Commons Download it free: BrentOzar.com/go/querystack We’ll use the dbo.Users table
  • 6. How big is our Users table today? Stored proc in your resources StackOverflow2010
  • 8. Our proc has to look like this: CREATE OR ALTER PROC dbo.usp_SearchUsers @SearchDisplayName NVARCHAR(100) = NULL, @SearchLocation NVARCHAR(100) = NULL, @SearchReputation INT = NULL… And folks want to pass in 1, 2, or 3 parameters, like just DisplayName, OR both Location and Reputation, and filter both.
  • 9. But we wanna do less reads, so… CREATE INDEX IX_DisplayName ON dbo.Users(DisplayName); CREATE INDEX IX_Location ON dbo.Users(Location); CREATE INDEX IX_Reputation ON dbo.Users(Reputation);
  • 13. At first glance, it works. Granted, the results aren’t accurate, but it is willing to use indexes. But there’s a catch.
  • 16. The London sort is spilling to disk
  • 17. Because we underestimated rows Not even close
  • 18. Remember, 7748 pages in the table
  • 19. We’re hitting parameter sniffing. SQL Server compiles the entire plan the first time it runs, using the parameter values it was first run with. So it’s optimizing the @SearchLocation branch with a null @SearchLocation value.
  • 20. This design has 3 big problems. 1. It produces the wrong results for param combos. 2. It’s a little TOO willing to use indexes, even when they’re worse than a table scan. 3. It underestimates memory grants.
  • 25. SQL Server builds a plan for a name But it may not ALWAYS have a name
  • 26. Oddly, this performs fine IF you don’t have any indexes.
  • 29. Welcome to Scandinavia Sure, key lookups too
  • 30. Not great on reads, either
  • 34. Logical reads look good, too
  • 35. What if we run it for combos?
  • 37. Clear the cache and run a few.
  • 38. We bloat the plan cache a little. The proc has its own entry, executed 6 times. Each dynamic SQL string gets its own line. But each dynamic plan is great* for that set of parameters! * Not necessarily.
  • 39. I got 99 problems plans Each dynamic SQL plan has its own: • Plan cache entry • Memory grant • Row estimations • Parameter sniffing issues
  • 40. Yes, I can still have param sniffing. Chicago: big, but not huge. London: big enough that a scan makes more sense.
  • 41. If Chicago runs first… We cache a plan with a seek. And reuse it for London.
  • 42. If London runs first… We cache a plan with a scan. And reuse it for Chicago But the memory grant is too big.
  • 43. Dynamic SQL Gives you the luxury of multiple plans, one for each set of parameters But curses you with multiple plans, each of which may have parameter sniffing issues.
  • 44. There’s much more to learn. Your demo scripts continue with pro tips for: • Using comments inside the dynamic SQL string itself for tracking down the source • Formatting the strings with CR/LR • Using debug variables to print at strategic times • The perils of dynamic sorting Download: BrentOzar.com/go/dynamicsql
  • 45. Erland goes even deeper. Alternate tables, forced recompilation, CLR…