SlideShare a Scribd company logo
SQL Server Deep Dive
IT Talk
Denis Reznik
Data Architect at Intapp, Inc.
Microsoft Data Platform MVP
About Me
• Kyiv, Ukraine
• Data Architect at Intapp, Inc.
• Microsoft Data Platform MVP
• PASS Regional Mentor, CEE
• Ukrainian Data Community Kyiv Co-Founder
• Co-author of “SQL Server MVP Deep Dives vol. 2”
How We See SQL Server
3 |
Some Magic
Query Result Set
SQL Server Network Interface
SQL Server Protocols
• Shared Memory
• TCP/IP
• Named Pipes
• VIA (Deprecated)
TDS Endpoints
TCP/IP
Shared Memory
Named Pipes
VIA
DAC
TCP/IP
Note: TDS – Tabular Data Stream
Connection
• Connection can be Succeed or Not
• https://www.connectionstrings.com/
• Connection string contains settings for Connection Timeout (or Timeout)
• Connection Timeout just limit the time for establishing a connection
• Does not limit the query execution time
• sys.dm_exec_connections
• sys.dm_exec_sessions
• sys.dm_exec_requests
• sys.dm_os_tasks
• … down to the bottom of SQLOS
8 |
Query Processor
Parser Algebraizer Optimizer Executor
Query Processing
Plan Cache
Algebraizing
• Define types for every node in ParseTree
• Check that objects are exist and available in current execution context
• Extract literals from the query
• e.g. WHERE User_Id = 1, 1 is a literal
• Returns BoundTree (QueryTree)
• Logical representation of the query
• Goal – get the optimal execution plan
• “Optimal” = Plan with the smallest cost
• Cost = sum_of_all_operators_costs(I/O + CPU +
memory_consumption)
Optimizer
Query Tree
Pre-Optimization
Search for trivial plan
Load statistics (simple)
Simplification – syntax transformation
Optimization
Heap
1 .. 100
100 .. 1k
5K .. 6K
1K .. 5K
6K .. 7K
15K .. 21K
12K .. 15K
10K .. 11K
21K .. 22K
22K .. 41K
9K .. 10K
41K .. 51K
7K .. 8K
8K .. 9K
71K .. 1M
51K .. 71K
1M .. 2M
2M .. 3M
Clustered Index
…
…
1 .. 1M
1 .. 2K 2K+1 .. 4K 1M-2K .. 1M
1 .. 300 301 .. 800 801 .. 1,5K 1,5K+1 .. 2K
Index Seek
…
…
1 .. 1M
1 .. 2K 2K+1 .. 4K 1M-2K .. 1M
1 .. 300 301 .. 800 801 .. 1,5K 1,5K+1 .. 2K
SELECT * FROM Users
WHERE Id = 523
Index Scan
…
…
1 .. 1M
1 .. 2K 2K+1 .. 4K 1M-2K .. 1M
1 .. 300 301 .. 800 801 .. 1,5K 1,5K+1 .. 2K
SELECT * FROM Users
Index Range Scan
…
…
1 .. 1M
1 .. 2K 2K+1 .. 4K 1M-2K .. 1M
1 .. 300 301 .. 800 801 .. 1,5K 1,5K+1 .. 2K
SELECT * FROM Users
WHERE Id BETWEEN 700
AND 1700
Non-Clustered Index
…
A .. Z
A .. C C .. K X .. Z
…
1 .. 1M
1 .. 2K 2K+1 .. 4K 1M-2K .. 1M
SELECT * FROM Users
WHERE Name = 'Donald Trump'
1 .. 2K 2K .. 4K 1M-2K .. 1M
Clustered Index
(Id)
Non-Clustered Index
(Name)
Heap
Optimizer Phase 0
Load Statistics
Exploration – Plan Alternatives
Estimated cost < 0.2
Return Transaction Processing Plan
Optimization
Statistics
500
1000
10
1200
800
1 800 2000 2800 4500 5400
SELECT * FROM Users
WHERE Id BETWEEN 2100 AND 2500
SELECT * FROM Users
WHERE Id BETWEEN 200 AND 5000
Query Plan Alternatives SELECT * FROM Users u
INNER JOIN Posts p
ON u.Id = p.OwnerUserId
WHERE u.DisplayName = 'John Snow'
Users
Posts
Posts
Users
Query Plan Alternatives
• 1 Table – 1 option
• 2 Tables – 2 options
• 3 Tables – 6 options
• 4 Tables – 24 options
• …
• 10 Tables – 3628800 options
• 1 Table – 1!
• 2 Tables – 2!
• 3 Tables – 3!
• 4 Tables – 4!
• …
• 10 Tables – 10!
Optimizer Phase 1
Next set of query rules
Estimate parallel plan (estimation processed twice)
• Max Degree of Parallelism
• Cost Threshold for Parallelism
Estimated cost < 1.0
Returns Quick Plan
Optimization
Parallel Query Execution
• Amdal’s Law
Thread 1
Thread 2
Thread 3
Thread 4
1s2s
Optimizer Phase 2
Full Set of Optimization Rules
Indexed views
Returns Full Query Plan
• All planned checks were done
• Good Enough Plan was Found
• Timeout
• Memory Limit Exceeded
Optimization
Executing
• Execute query using its Query Plan
• Request data from the Storage Engine
Parameter Sniffing
Exec SomeProc @p
Optimizer
SQL Server Cache
Procedure cache@p
Plan is cached for the
first value of
Procedure cache
DEMO
Parameter Sniffing
Storage Engine
Buffer Pool
Data Cache
Database File
Access Methods
Buffer Manager
Data Selection
?
What if I load 2GB value from the
disk and read this data using
NOLOCK?
Data Modification
Buffer Pool
Data Cache
Database File
Access Methods Buffer Manager
Transaction Log
Log Manager
Log Buffer
?
?
Background
ProcessesLock Manager
? 3 cases
Transaction Log
Autogrow
Log Backup or CHECKPOINT
FULL Recovery Model
• Log all transactions
• Database can be restored to any point of time
• Highly recommended for critical data
• Transaction truncation occurs after log backup
BULK-LOGGED Model
• Log all transactions
• Minimally-Logged operations are logged in another way
• Database can’t be restored to any point of time
• Can be temporary interchanged with FULL recovery model to do
Minimally-Logged operations more effectively
• Transaction truncation occurs after log backup
SIMPLE Recovery Model
• Log all transactions like in BULK-LOGGED recovery model
• Transaction truncation occurs after CHECKPOINT
DEMO
Log Shrink
Lock Types - Shared
S S
X
Lock Types - Exclusive
X
X
S
Lock Types - Update
U
U
S
SX
Lock Types – Intent locks
S
ISIS
ID City
1 Kyiv
2 Kharkiv
3 Dnipropetrovsk
BEGIN TRAN
UPDATE Users
SET CityId = 2
WHERE Id = 4
UPDATE City
SET Name = 'Dnipro'
WHERE Id = 3
ID User City_Id
1 Tony Stark 2
2 John Smith 2
3 Clark Kent 2
4 Ivan Vanko 3
Classic Deadlock
X
BEGIN TRAN
UPDATE City
SET Name = 'Dnipro'
WHERE Id = 3
UPDATE Users
SET CityId = 2
WHERE Id = 4
X
DEADLOCK!
DEMO
Deadlock
SQLOS
CPU – Cooperative Multitasking
0
CPUsQueries
1
2
3
Time Quantum Length for each Scheduler is 4 ms
Windows Memory Management
0001 0010 0101
0000 1001 0101
0011 1010 1001
1110 0010 0110
0001 0010 0101
0000 1001 0101
0011 1010 1001
Physical Memory (RAM)
Page File
VirtualMemory
Virtual Memory
Manager
SQL Server
Browser
Word
Data Cache Query Cache
Locks Memory Memory Grants
Some Small Caches
External Memory
Buffer Pool
SQL Server Memory Consumers
Network
Bandwidth
TCP Packages
TCP Packages
TCP Packages
Bandwidth
TCP Packages
Query Execution
Thread Pool
Running
Suspended
Runnable
Sleeping
Scheduler
Logical CPU
Worker (Thread)
Connection
DEMO
Thread Pool Starvation
Summary
50 |
Thank You!
IT Talk
Denis Reznik
Twitter: @denisreznik
Email: denisreznik@gmail.com
Blog: http://reznik.uneta.com.ua
Facebook: https://www.facebook.com/denis.reznik.5
LinkedIn: http://ua.linkedin.com/pub/denis-reznik/3/502/234

More Related Content

Similar to SQL Server Deep Drive

"Query Execution: Expectation - Reality (Level 300)" Денис Резник
"Query Execution: Expectation - Reality (Level 300)" Денис Резник"Query Execution: Expectation - Reality (Level 300)" Денис Резник
"Query Execution: Expectation - Reality (Level 300)" Денис Резник
Fwdays
 
Se2017 query-optimizer
Se2017 query-optimizerSe2017 query-optimizer
Se2017 query-optimizer
Mary Prokhorova
 
Scalable IoT platform
Scalable IoT platformScalable IoT platform
Scalable IoT platform
Swapnil Bawaskar
 
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
Fwdays
 
"What database can tell about application issues? What application can tell a...
"What database can tell about application issues? What application can tell a..."What database can tell about application issues? What application can tell a...
"What database can tell about application issues? What application can tell a...
Fwdays
 
Performance Scenario: Diagnosing and resolving sudden slow down on two node RAC
Performance Scenario: Diagnosing and resolving sudden slow down on two node RACPerformance Scenario: Diagnosing and resolving sudden slow down on two node RAC
Performance Scenario: Diagnosing and resolving sudden slow down on two node RAC
Kristofferson A
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
Jonathan Levin
 
Understanding Performance with DTrace
Understanding Performance with DTraceUnderstanding Performance with DTrace
Understanding Performance with DTrace
ahl0003
 
Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"
Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"
Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"
Fwdays
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Zohar Elkayam
 
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
DataStax
 
SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1
sqlserver.co.il
 
10x Performance Improvements
10x Performance Improvements10x Performance Improvements
10x Performance Improvements
Ronald Bradford
 
10x improvement-mysql-100419105218-phpapp02
10x improvement-mysql-100419105218-phpapp0210x improvement-mysql-100419105218-phpapp02
10x improvement-mysql-100419105218-phpapp02
promethius
 
Apache zookeeper seminar_trinh_viet_dung_03_2016
Apache zookeeper seminar_trinh_viet_dung_03_2016Apache zookeeper seminar_trinh_viet_dung_03_2016
Apache zookeeper seminar_trinh_viet_dung_03_2016
Viet-Dung TRINH
 
Apache Zookeeper
Apache ZookeeperApache Zookeeper
Apache Zookeeper
Nguyen Quang
 
Moving Toward Deep Learning Algorithms on HPCC Systems
Moving Toward Deep Learning Algorithms on HPCC SystemsMoving Toward Deep Learning Algorithms on HPCC Systems
Moving Toward Deep Learning Algorithms on HPCC Systems
HPCC Systems
 
AWS re:Invent 2016| GAM301 | How EA Leveraged Amazon Redshift and AWS Partner...
AWS re:Invent 2016| GAM301 | How EA Leveraged Amazon Redshift and AWS Partner...AWS re:Invent 2016| GAM301 | How EA Leveraged Amazon Redshift and AWS Partner...
AWS re:Invent 2016| GAM301 | How EA Leveraged Amazon Redshift and AWS Partner...
Amazon Web Services
 
AWS re:Invent 2016: [REPEAT] How EA Leveraged Amazon Redshift and AWS Partner...
AWS re:Invent 2016: [REPEAT] How EA Leveraged Amazon Redshift and AWS Partner...AWS re:Invent 2016: [REPEAT] How EA Leveraged Amazon Redshift and AWS Partner...
AWS re:Invent 2016: [REPEAT] How EA Leveraged Amazon Redshift and AWS Partner...
Amazon Web Services
 
30334823 my sql-cluster-performance-tuning-best-practices
30334823 my sql-cluster-performance-tuning-best-practices30334823 my sql-cluster-performance-tuning-best-practices
30334823 my sql-cluster-performance-tuning-best-practices
David Dhavan
 

Similar to SQL Server Deep Drive (20)

"Query Execution: Expectation - Reality (Level 300)" Денис Резник
"Query Execution: Expectation - Reality (Level 300)" Денис Резник"Query Execution: Expectation - Reality (Level 300)" Денис Резник
"Query Execution: Expectation - Reality (Level 300)" Денис Резник
 
Se2017 query-optimizer
Se2017 query-optimizerSe2017 query-optimizer
Se2017 query-optimizer
 
Scalable IoT platform
Scalable IoT platformScalable IoT platform
Scalable IoT platform
 
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
Денис Резник "Зачем мне знать SQL и Базы Данных, ведь у меня есть ORM?"
 
"What database can tell about application issues? What application can tell a...
"What database can tell about application issues? What application can tell a..."What database can tell about application issues? What application can tell a...
"What database can tell about application issues? What application can tell a...
 
Performance Scenario: Diagnosing and resolving sudden slow down on two node RAC
Performance Scenario: Diagnosing and resolving sudden slow down on two node RACPerformance Scenario: Diagnosing and resolving sudden slow down on two node RAC
Performance Scenario: Diagnosing and resolving sudden slow down on two node RAC
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 
Understanding Performance with DTrace
Understanding Performance with DTraceUnderstanding Performance with DTrace
Understanding Performance with DTrace
 
Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"
Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"
Denis Reznik "Оптимизация запроса. Не знаешь что делать? Делай то, что знаешь"
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
 
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
 
SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1SQL Explore 2012: P&T Part 1
SQL Explore 2012: P&T Part 1
 
10x Performance Improvements
10x Performance Improvements10x Performance Improvements
10x Performance Improvements
 
10x improvement-mysql-100419105218-phpapp02
10x improvement-mysql-100419105218-phpapp0210x improvement-mysql-100419105218-phpapp02
10x improvement-mysql-100419105218-phpapp02
 
Apache zookeeper seminar_trinh_viet_dung_03_2016
Apache zookeeper seminar_trinh_viet_dung_03_2016Apache zookeeper seminar_trinh_viet_dung_03_2016
Apache zookeeper seminar_trinh_viet_dung_03_2016
 
Apache Zookeeper
Apache ZookeeperApache Zookeeper
Apache Zookeeper
 
Moving Toward Deep Learning Algorithms on HPCC Systems
Moving Toward Deep Learning Algorithms on HPCC SystemsMoving Toward Deep Learning Algorithms on HPCC Systems
Moving Toward Deep Learning Algorithms on HPCC Systems
 
AWS re:Invent 2016| GAM301 | How EA Leveraged Amazon Redshift and AWS Partner...
AWS re:Invent 2016| GAM301 | How EA Leveraged Amazon Redshift and AWS Partner...AWS re:Invent 2016| GAM301 | How EA Leveraged Amazon Redshift and AWS Partner...
AWS re:Invent 2016| GAM301 | How EA Leveraged Amazon Redshift and AWS Partner...
 
AWS re:Invent 2016: [REPEAT] How EA Leveraged Amazon Redshift and AWS Partner...
AWS re:Invent 2016: [REPEAT] How EA Leveraged Amazon Redshift and AWS Partner...AWS re:Invent 2016: [REPEAT] How EA Leveraged Amazon Redshift and AWS Partner...
AWS re:Invent 2016: [REPEAT] How EA Leveraged Amazon Redshift and AWS Partner...
 
30334823 my sql-cluster-performance-tuning-best-practices
30334823 my sql-cluster-performance-tuning-best-practices30334823 my sql-cluster-performance-tuning-best-practices
30334823 my sql-cluster-performance-tuning-best-practices
 

More from DataArt

DataArt Custom Software Engineering with a Human Approach
DataArt Custom Software Engineering with a Human ApproachDataArt Custom Software Engineering with a Human Approach
DataArt Custom Software Engineering with a Human Approach
DataArt
 
DataArt Healthcare & Life Sciences
DataArt Healthcare & Life SciencesDataArt Healthcare & Life Sciences
DataArt Healthcare & Life Sciences
DataArt
 
DataArt Financial Services and Capital Markets
DataArt Financial Services and Capital MarketsDataArt Financial Services and Capital Markets
DataArt Financial Services and Capital Markets
DataArt
 
About DataArt HR Partners
About DataArt HR PartnersAbout DataArt HR Partners
About DataArt HR Partners
DataArt
 
Event management в IT
Event management в ITEvent management в IT
Event management в IT
DataArt
 
Digital Marketing from inside
Digital Marketing from insideDigital Marketing from inside
Digital Marketing from inside
DataArt
 
What's new in Android, Igor Malytsky ( Google Post I|O Tour)
What's new in Android, Igor Malytsky ( Google Post I|O Tour)What's new in Android, Igor Malytsky ( Google Post I|O Tour)
What's new in Android, Igor Malytsky ( Google Post I|O Tour)
DataArt
 
DevOps Workshop:Что бывает, когда DevOps приходит на проект
DevOps Workshop:Что бывает, когда DevOps приходит на проектDevOps Workshop:Что бывает, когда DevOps приходит на проект
DevOps Workshop:Что бывает, когда DevOps приходит на проект
DataArt
 
IT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArt
IT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArtIT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArt
IT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArt
DataArt
 
«Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han...
 «Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han... «Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han...
«Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han...
DataArt
 
Communication in QA's life
Communication in QA's lifeCommunication in QA's life
Communication in QA's life
DataArt
 
Нельзя просто так взять и договориться, или как мы работали со сложными людьми
Нельзя просто так взять и договориться, или как мы работали со сложными людьмиНельзя просто так взять и договориться, или как мы работали со сложными людьми
Нельзя просто так взять и договориться, или как мы работали со сложными людьми
DataArt
 
Знакомьтесь, DevOps
Знакомьтесь, DevOpsЗнакомьтесь, DevOps
Знакомьтесь, DevOps
DataArt
 
DevOps in real life
DevOps in real lifeDevOps in real life
DevOps in real life
DataArt
 
Codeless: автоматизация тестирования
Codeless: автоматизация тестированияCodeless: автоматизация тестирования
Codeless: автоматизация тестирования
DataArt
 
Selenoid
SelenoidSelenoid
Selenoid
DataArt
 
Selenide
SelenideSelenide
Selenide
DataArt
 
A. Sirota "Building an Automation Solution based on Appium"
A. Sirota "Building an Automation Solution based on Appium"A. Sirota "Building an Automation Solution based on Appium"
A. Sirota "Building an Automation Solution based on Appium"
DataArt
 
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
DataArt
 
IT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNGIT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNG
DataArt
 

More from DataArt (20)

DataArt Custom Software Engineering with a Human Approach
DataArt Custom Software Engineering with a Human ApproachDataArt Custom Software Engineering with a Human Approach
DataArt Custom Software Engineering with a Human Approach
 
DataArt Healthcare & Life Sciences
DataArt Healthcare & Life SciencesDataArt Healthcare & Life Sciences
DataArt Healthcare & Life Sciences
 
DataArt Financial Services and Capital Markets
DataArt Financial Services and Capital MarketsDataArt Financial Services and Capital Markets
DataArt Financial Services and Capital Markets
 
About DataArt HR Partners
About DataArt HR PartnersAbout DataArt HR Partners
About DataArt HR Partners
 
Event management в IT
Event management в ITEvent management в IT
Event management в IT
 
Digital Marketing from inside
Digital Marketing from insideDigital Marketing from inside
Digital Marketing from inside
 
What's new in Android, Igor Malytsky ( Google Post I|O Tour)
What's new in Android, Igor Malytsky ( Google Post I|O Tour)What's new in Android, Igor Malytsky ( Google Post I|O Tour)
What's new in Android, Igor Malytsky ( Google Post I|O Tour)
 
DevOps Workshop:Что бывает, когда DevOps приходит на проект
DevOps Workshop:Что бывает, когда DevOps приходит на проектDevOps Workshop:Что бывает, когда DevOps приходит на проект
DevOps Workshop:Что бывает, когда DevOps приходит на проект
 
IT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArt
IT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArtIT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArt
IT Talk Kharkiv: «‎Soft skills в IT. Польза или вред? Максим Бастион, DataArt
 
«Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han...
 «Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han... «Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han...
«Ноль копеек. Спастись от выгорания» — Сергей Чеботарев (Head of Design, Han...
 
Communication in QA's life
Communication in QA's lifeCommunication in QA's life
Communication in QA's life
 
Нельзя просто так взять и договориться, или как мы работали со сложными людьми
Нельзя просто так взять и договориться, или как мы работали со сложными людьмиНельзя просто так взять и договориться, или как мы работали со сложными людьми
Нельзя просто так взять и договориться, или как мы работали со сложными людьми
 
Знакомьтесь, DevOps
Знакомьтесь, DevOpsЗнакомьтесь, DevOps
Знакомьтесь, DevOps
 
DevOps in real life
DevOps in real lifeDevOps in real life
DevOps in real life
 
Codeless: автоматизация тестирования
Codeless: автоматизация тестированияCodeless: автоматизация тестирования
Codeless: автоматизация тестирования
 
Selenoid
SelenoidSelenoid
Selenoid
 
Selenide
SelenideSelenide
Selenide
 
A. Sirota "Building an Automation Solution based on Appium"
A. Sirota "Building an Automation Solution based on Appium"A. Sirota "Building an Automation Solution based on Appium"
A. Sirota "Building an Automation Solution based on Appium"
 
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
Эмоциональный интеллект или как не сойти с ума в условиях сложного и динамичн...
 
IT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNGIT talk: Как я перестал бояться и полюбил TestNG
IT talk: Как я перестал бояться и полюбил TestNG
 

Recently uploaded

Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 

Recently uploaded (20)

Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 

SQL Server Deep Drive

  • 1. SQL Server Deep Dive IT Talk Denis Reznik Data Architect at Intapp, Inc. Microsoft Data Platform MVP
  • 2. About Me • Kyiv, Ukraine • Data Architect at Intapp, Inc. • Microsoft Data Platform MVP • PASS Regional Mentor, CEE • Ukrainian Data Community Kyiv Co-Founder • Co-author of “SQL Server MVP Deep Dives vol. 2”
  • 3. How We See SQL Server 3 | Some Magic Query Result Set
  • 4.
  • 5. SQL Server Network Interface
  • 6. SQL Server Protocols • Shared Memory • TCP/IP • Named Pipes • VIA (Deprecated)
  • 7. TDS Endpoints TCP/IP Shared Memory Named Pipes VIA DAC TCP/IP Note: TDS – Tabular Data Stream
  • 8. Connection • Connection can be Succeed or Not • https://www.connectionstrings.com/ • Connection string contains settings for Connection Timeout (or Timeout) • Connection Timeout just limit the time for establishing a connection • Does not limit the query execution time • sys.dm_exec_connections • sys.dm_exec_sessions • sys.dm_exec_requests • sys.dm_os_tasks • … down to the bottom of SQLOS 8 |
  • 10. Parser Algebraizer Optimizer Executor Query Processing Plan Cache
  • 11. Algebraizing • Define types for every node in ParseTree • Check that objects are exist and available in current execution context • Extract literals from the query • e.g. WHERE User_Id = 1, 1 is a literal • Returns BoundTree (QueryTree) • Logical representation of the query
  • 12. • Goal – get the optimal execution plan • “Optimal” = Plan with the smallest cost • Cost = sum_of_all_operators_costs(I/O + CPU + memory_consumption) Optimizer Query Tree Pre-Optimization Search for trivial plan Load statistics (simple) Simplification – syntax transformation Optimization
  • 13. Heap 1 .. 100 100 .. 1k 5K .. 6K 1K .. 5K 6K .. 7K 15K .. 21K 12K .. 15K 10K .. 11K 21K .. 22K 22K .. 41K 9K .. 10K 41K .. 51K 7K .. 8K 8K .. 9K 71K .. 1M 51K .. 71K 1M .. 2M 2M .. 3M
  • 14. Clustered Index … … 1 .. 1M 1 .. 2K 2K+1 .. 4K 1M-2K .. 1M 1 .. 300 301 .. 800 801 .. 1,5K 1,5K+1 .. 2K
  • 15. Index Seek … … 1 .. 1M 1 .. 2K 2K+1 .. 4K 1M-2K .. 1M 1 .. 300 301 .. 800 801 .. 1,5K 1,5K+1 .. 2K SELECT * FROM Users WHERE Id = 523
  • 16. Index Scan … … 1 .. 1M 1 .. 2K 2K+1 .. 4K 1M-2K .. 1M 1 .. 300 301 .. 800 801 .. 1,5K 1,5K+1 .. 2K SELECT * FROM Users
  • 17. Index Range Scan … … 1 .. 1M 1 .. 2K 2K+1 .. 4K 1M-2K .. 1M 1 .. 300 301 .. 800 801 .. 1,5K 1,5K+1 .. 2K SELECT * FROM Users WHERE Id BETWEEN 700 AND 1700
  • 18. Non-Clustered Index … A .. Z A .. C C .. K X .. Z … 1 .. 1M 1 .. 2K 2K+1 .. 4K 1M-2K .. 1M SELECT * FROM Users WHERE Name = 'Donald Trump' 1 .. 2K 2K .. 4K 1M-2K .. 1M Clustered Index (Id) Non-Clustered Index (Name) Heap
  • 19. Optimizer Phase 0 Load Statistics Exploration – Plan Alternatives Estimated cost < 0.2 Return Transaction Processing Plan Optimization
  • 20. Statistics 500 1000 10 1200 800 1 800 2000 2800 4500 5400 SELECT * FROM Users WHERE Id BETWEEN 2100 AND 2500 SELECT * FROM Users WHERE Id BETWEEN 200 AND 5000
  • 21. Query Plan Alternatives SELECT * FROM Users u INNER JOIN Posts p ON u.Id = p.OwnerUserId WHERE u.DisplayName = 'John Snow' Users Posts Posts Users
  • 22. Query Plan Alternatives • 1 Table – 1 option • 2 Tables – 2 options • 3 Tables – 6 options • 4 Tables – 24 options • … • 10 Tables – 3628800 options • 1 Table – 1! • 2 Tables – 2! • 3 Tables – 3! • 4 Tables – 4! • … • 10 Tables – 10!
  • 23. Optimizer Phase 1 Next set of query rules Estimate parallel plan (estimation processed twice) • Max Degree of Parallelism • Cost Threshold for Parallelism Estimated cost < 1.0 Returns Quick Plan Optimization
  • 24. Parallel Query Execution • Amdal’s Law Thread 1 Thread 2 Thread 3 Thread 4 1s2s
  • 25. Optimizer Phase 2 Full Set of Optimization Rules Indexed views Returns Full Query Plan • All planned checks were done • Good Enough Plan was Found • Timeout • Memory Limit Exceeded Optimization
  • 26. Executing • Execute query using its Query Plan • Request data from the Storage Engine
  • 27. Parameter Sniffing Exec SomeProc @p Optimizer SQL Server Cache Procedure cache@p Plan is cached for the first value of Procedure cache
  • 30. Buffer Pool Data Cache Database File Access Methods Buffer Manager Data Selection ? What if I load 2GB value from the disk and read this data using NOLOCK?
  • 31. Data Modification Buffer Pool Data Cache Database File Access Methods Buffer Manager Transaction Log Log Manager Log Buffer ? ? Background ProcessesLock Manager ? 3 cases
  • 33. FULL Recovery Model • Log all transactions • Database can be restored to any point of time • Highly recommended for critical data • Transaction truncation occurs after log backup
  • 34. BULK-LOGGED Model • Log all transactions • Minimally-Logged operations are logged in another way • Database can’t be restored to any point of time • Can be temporary interchanged with FULL recovery model to do Minimally-Logged operations more effectively • Transaction truncation occurs after log backup
  • 35. SIMPLE Recovery Model • Log all transactions like in BULK-LOGGED recovery model • Transaction truncation occurs after CHECKPOINT
  • 37. Lock Types - Shared S S X
  • 38. Lock Types - Exclusive X X S
  • 39. Lock Types - Update U U S SX
  • 40. Lock Types – Intent locks S ISIS
  • 41. ID City 1 Kyiv 2 Kharkiv 3 Dnipropetrovsk BEGIN TRAN UPDATE Users SET CityId = 2 WHERE Id = 4 UPDATE City SET Name = 'Dnipro' WHERE Id = 3 ID User City_Id 1 Tony Stark 2 2 John Smith 2 3 Clark Kent 2 4 Ivan Vanko 3 Classic Deadlock X BEGIN TRAN UPDATE City SET Name = 'Dnipro' WHERE Id = 3 UPDATE Users SET CityId = 2 WHERE Id = 4 X DEADLOCK!
  • 43. SQLOS
  • 44. CPU – Cooperative Multitasking 0 CPUsQueries 1 2 3 Time Quantum Length for each Scheduler is 4 ms
  • 45. Windows Memory Management 0001 0010 0101 0000 1001 0101 0011 1010 1001 1110 0010 0110 0001 0010 0101 0000 1001 0101 0011 1010 1001 Physical Memory (RAM) Page File VirtualMemory Virtual Memory Manager SQL Server Browser Word
  • 46. Data Cache Query Cache Locks Memory Memory Grants Some Small Caches External Memory Buffer Pool SQL Server Memory Consumers
  • 47. Network Bandwidth TCP Packages TCP Packages TCP Packages Bandwidth TCP Packages
  • 51. Thank You! IT Talk Denis Reznik Twitter: @denisreznik Email: denisreznik@gmail.com Blog: http://reznik.uneta.com.ua Facebook: https://www.facebook.com/denis.reznik.5 LinkedIn: http://ua.linkedin.com/pub/denis-reznik/3/502/234