SlideShare una empresa de Scribd logo
1 de 31
23ª Reunião Lisboa - 24/09/2011   http://netponto.org




            Know your SQL Server - DMVs
                                    Vítor Pombeiro
Patrocinadores desta reunião
Patrocinadores desta reunião
Vítor Pombeiro
Developer no Banco Primus
.Net 2.0 Web e Windows Applications
SQL Server 2000
BI
Agenda
•   DMVs
•   CPU
•   Memória
•   Índices e Estatísticas
•   IO
DMVs
• “Dynamic management views and functions
  return server state information that can be used to
  monitor the health of a server instance, diagnose
  problems, and tune performance.” (Books Online)
CPU
CPU
select
       scheduler_id,
       current_tasks_count,
       runnable_tasks_count -->Valor a verificar
from sys.dm_os_schedulers
where scheduler_id < 1048576
CPU
SELECT TOP 10
 (total_worker_time * 1.0) / 1000000 AS Total_Worker_Time_in_Seconds,
 execution_count,
 ((total_worker_time * 1.0) / 1000000) / execution_count AS Avg_Worker_Time_in_Seconds,
 (min_worker_time * 1.0) / 1000000 AS Min_Worker_Time_in_Seconds,
 (max_worker_time * 1.0) / 1000000 AS Max_Worker_Time_in_Seconds,
 text
FROM sys.dm_exec_query_stats
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
order by total_worker_time desc
CPU
select top 25
         sql_text.text,
         plan_generation_num,
         execution_count
from sys.dm_exec_query_stats a
cross apply sys.dm_exec_sql_text(sql_handle) as sql_text
where plan_generation_num >1
order by plan_generation_num desc
CPU
select
         timestamp,
         convert(xml, record) as info
from sys.dm_os_ring_buffers
where ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
and record like '%<SystemHealth>%'
CPU
• Causas de bottleneck no CPU
  – Estatísticas
  – “WITH RECOMPILE” nas SPs
     • OPTION (RECOMPILE)
  – Paralelismo OPTION (MAXDOP) hint
Memória
Memória
select
       text,
       query_plan,
       requested_memory_kb,
       granted_memory_kb,
       used_memory_kb
from sys.dm_exec_query_memory_grants MG
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
CROSS APPLY sys.dm_exec_query_plan(MG.plan_handle)
Memória
SELECT
      Getdate() report_time,
      [cntr_value] as value_sec,
      cast(@@SERVERNAME as varchar) as ServerName
FROM sys.dm_os_performance_counters
WHERE [object_name] LIKE '%Manager%'
      AND [counter_name] = 'Page life expectancy'
Memória
• Causas
  – Configuração do SQL Server
  – AWE inactivo (32 bits)
  – Nº sessões activas
Índices e estatísticas
                          ROOT




        Intermediate                Intermediate




     Leaf          Leaf          Leaf          Leaf
Índices e estatísticas
select
           OBJECT_NAME(ps.object_id) as TableName
           ,si.Name ,ps.Avg_Fragmentation_in_percent
           ,STATS_DATE(ss.object_id,ss.stats_id) as LastUpdatedStatistics
from sys.dm_db_index_physical_stats(DB_ID(DB_NAME()),null,null,null,null) ps
join sysindexes si on ps.object_id = si.id
           and ps.index_id = si.indid
left outer join sys.stats ss on ss.object_id = ps.object_id
           and ss.name = si.name
where ps.avg_fragmentation_in_percent > 10
order by ps.avg_fragmentation_in_percent desc
Índices e estatísticas
SELECT TOP 10
    [Total Cost] = ROUND(avg_total_user_cost * avg_user_impact * (user_seeks + user_scans),0)
    , avg_user_impact , statement as TableName
    , equality_columns , inequality_columns
    , included_columns
FROM       sys.dm_db_missing_index_groups g
INNER JOIN sys.dm_db_missing_index_group_stats s
   ON s.group_handle = g.index_group_handle
INNER JOIN sys.dm_db_missing_index_details d
   ON d.index_handle = g.index_handle
ORDER BY [Total Cost] DESC;
Índices e estatísticas
SELECT TOP 10
            DB_NAME() as DatabaseName , OBJECT_NAME(s.[object_id]) as TableName ,
            IndexName = i.name,
            user_updates, system_updates
FROM sys.dm_db_index_usage_stats s
INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id
WHERE s.database_id = DB_ID()
  AND OBJECTPROPERTY(s.[object_id], 'IsMsShipped') = 0
  AND user_seeks = 0 AND user_scans = 0 AND user_lookups = 0
  AND i.name IS NOT NULL -- Ignore HEAP indexes.
ORDER BY user_updates DESC
Índices e estatísticas
• Causas
  – Muitos inserts, updates e deletes
  – Plano manutenção ineficaz
  – Excesso ou falta de índices
  – Shrink
IO
IO
SELECT DB_NAME(fs.database_id) AS [Database Name], mf.physical_name, io_stall_read_ms, num_of_reads,
  CAST(io_stall_read_ms/(1.0 + num_of_reads) AS NUMERIC(10,1)) AS [avg_read_stall_ms],io_stall_write_ms,
  num_of_writes,CAST(io_stall_write_ms/(1.0+num_of_writes) AS NUMERIC(10,1)) AS [avg_write_stall_ms],
  io_stall_read_ms + io_stall_write_ms AS [io_stalls], num_of_reads + num_of_writes AS [total_io],
  CAST((io_stall_read_ms + io_stall_write_ms)/(1.0 + num_of_reads + num_of_writes) AS NUMERIC(10,1))
  AS [avg_io_stall_ms]
FROM sys.dm_io_virtual_file_stats(null,null) AS fs
INNER JOIN sys.master_files AS mf
  ON fs.database_id = mf.database_id
  AND fs.[file_id] = mf.[file_id]
ORDER BY avg_io_stall_ms DESC OPTION (RECOMPILE);
IO
Select wait_type,
    waiting_tasks_count,
    wait_time_ms / 1000 as wait_time_in_sec
from sys.dm_os_wait_stats
where wait_type like 'PAGEIOLATCH%'
order by wait_type
IO
•   tempDB
•   Índices
•   Recolha excessiva de dados
•   Base de dados com problemas no schema
•   Pouca memória
Questões?
Referências
Books OnLine
   – http://msdn.microsoft.com/en-us/library/ms188754.aspx

SQL Server DMV Starter Pack
   – http://www.red-gate.com/products/dba/sql-monitor/entrypage/dmv

Glenn Berry
   – http://www.sqlservercentral.com/blogs/glennberry/archive/tags/DMV/defau
     lt.aspx
   – http://sqlserverperformance.wordpress.com
Patrocinadores desta reunião
Patrocinadores desta reunião
Próximas reuniões presenciais
• 24/09/2011 – Setembro (2 anos!)
• 29/10/2011 – Outubro
• 19/11/2011 – Outubro (Coimbra)
• 26/11/2011 – Novembro
  Reserva estes dias na agenda! :)
Obrigado!
Vítor Pombeiro
vitor.pombeiro@hotmail.com
vitor.pombeiro@gmail.com
http://twitter.com/creative_byte

Más contenido relacionado

Similar a Know your SQL Server - DMVs

Kåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your servicesKåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your servicesNordic Infrastructure Conference
 
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And WhatPerformance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And Whatudaymoogala
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant TrainingAidIQ
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLCommand Prompt., Inc
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLMark Wong
 
TechEd 2006: Trabalhando com DMV e DMF
TechEd 2006: Trabalhando com DMV e DMFTechEd 2006: Trabalhando com DMV e DMF
TechEd 2006: Trabalhando com DMV e DMFFabrício Catae
 
The MySQL Performance Schema & New SYS Schema
The MySQL Performance Schema & New SYS SchemaThe MySQL Performance Schema & New SYS Schema
The MySQL Performance Schema & New SYS SchemaTed Wennmark
 
AWR DB performance Data Mining - Collaborate 2015
AWR DB performance Data Mining - Collaborate 2015AWR DB performance Data Mining - Collaborate 2015
AWR DB performance Data Mining - Collaborate 2015Yury Velikanov
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - PresentationBiju Thomas
 
OTN tour 2015 AWR data mining
OTN tour 2015 AWR data miningOTN tour 2015 AWR data mining
OTN tour 2015 AWR data miningAndrejs Vorobjovs
 
Oracle 12c Automatic Data Optimization (ADO) - ILM
Oracle 12c Automatic Data Optimization (ADO) - ILMOracle 12c Automatic Data Optimization (ADO) - ILM
Oracle 12c Automatic Data Optimization (ADO) - ILMMonowar Mukul
 
My SYSAUX tablespace is full - please help
My SYSAUX tablespace is full - please helpMy SYSAUX tablespace is full - please help
My SYSAUX tablespace is full - please helpMarkus Flechtner
 
Oracle database performance tuning
Oracle database performance tuningOracle database performance tuning
Oracle database performance tuningYogiji Creations
 
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )Neeraj Bhandari
 
OSA Con 2022 - Building Event Collection SDKs and Data Models - Paul Boocock ...
OSA Con 2022 - Building Event Collection SDKs and Data Models - Paul Boocock ...OSA Con 2022 - Building Event Collection SDKs and Data Models - Paul Boocock ...
OSA Con 2022 - Building Event Collection SDKs and Data Models - Paul Boocock ...Altinity Ltd
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialjbellis
 
How to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better PerformanceHow to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better Performanceoysteing
 
Sql server performance tuning
Sql server performance tuningSql server performance tuning
Sql server performance tuningJugal Shah
 

Similar a Know your SQL Server - DMVs (20)

Kåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your servicesKåre Rude Andersen - Be a hero – optimize scom and present your services
Kåre Rude Andersen - Be a hero – optimize scom and present your services
 
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And WhatPerformance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
 
TechEd 2006: Trabalhando com DMV e DMF
TechEd 2006: Trabalhando com DMV e DMFTechEd 2006: Trabalhando com DMV e DMF
TechEd 2006: Trabalhando com DMV e DMF
 
The MySQL Performance Schema & New SYS Schema
The MySQL Performance Schema & New SYS SchemaThe MySQL Performance Schema & New SYS Schema
The MySQL Performance Schema & New SYS Schema
 
AWR DB performance Data Mining - Collaborate 2015
AWR DB performance Data Mining - Collaborate 2015AWR DB performance Data Mining - Collaborate 2015
AWR DB performance Data Mining - Collaborate 2015
 
2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation2013 Collaborate - OAUG - Presentation
2013 Collaborate - OAUG - Presentation
 
Optimizando MySQL
Optimizando MySQLOptimizando MySQL
Optimizando MySQL
 
OTN tour 2015 AWR data mining
OTN tour 2015 AWR data miningOTN tour 2015 AWR data mining
OTN tour 2015 AWR data mining
 
Oracle 12c Automatic Data Optimization (ADO) - ILM
Oracle 12c Automatic Data Optimization (ADO) - ILMOracle 12c Automatic Data Optimization (ADO) - ILM
Oracle 12c Automatic Data Optimization (ADO) - ILM
 
My SYSAUX tablespace is full - please help
My SYSAUX tablespace is full - please helpMy SYSAUX tablespace is full - please help
My SYSAUX tablespace is full - please help
 
It Depends
It DependsIt Depends
It Depends
 
Oracle database performance tuning
Oracle database performance tuningOracle database performance tuning
Oracle database performance tuning
 
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )Database management system by Neeraj Bhandari ( Surkhet.Nepal )
Database management system by Neeraj Bhandari ( Surkhet.Nepal )
 
OSA Con 2022 - Building Event Collection SDKs and Data Models - Paul Boocock ...
OSA Con 2022 - Building Event Collection SDKs and Data Models - Paul Boocock ...OSA Con 2022 - Building Event Collection SDKs and Data Models - Paul Boocock ...
OSA Con 2022 - Building Event Collection SDKs and Data Models - Paul Boocock ...
 
PyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorialPyCon 2010 SQLAlchemy tutorial
PyCon 2010 SQLAlchemy tutorial
 
How to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better PerformanceHow to Analyze and Tune MySQL Queries for Better Performance
How to Analyze and Tune MySQL Queries for Better Performance
 
Sql server performance tuning
Sql server performance tuningSql server performance tuning
Sql server performance tuning
 

Más de Comunidade NetPonto

Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...
Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...
Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...Comunidade NetPonto
 
Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...
Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...
Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...Comunidade NetPonto
 
MVVM Light e Cimbalino Toolkits - Sara Silva
MVVM Light e Cimbalino Toolkits - Sara SilvaMVVM Light e Cimbalino Toolkits - Sara Silva
MVVM Light e Cimbalino Toolkits - Sara SilvaComunidade NetPonto
 
Deep dive into Windows Azure Mobile Services - Ricardo Costa
Deep dive into Windows Azure Mobile Services - Ricardo CostaDeep dive into Windows Azure Mobile Services - Ricardo Costa
Deep dive into Windows Azure Mobile Services - Ricardo CostaComunidade NetPonto
 
The power of templating.... with NVelocity - Nuno Cancelo
The power of templating.... with NVelocity - Nuno CanceloThe power of templating.... with NVelocity - Nuno Cancelo
The power of templating.... with NVelocity - Nuno CanceloComunidade NetPonto
 
ASP.Net Performance – A pragmatic approach - Luis Paulino
ASP.Net Performance – A pragmatic approach - Luis PaulinoASP.Net Performance – A pragmatic approach - Luis Paulino
ASP.Net Performance – A pragmatic approach - Luis PaulinoComunidade NetPonto
 
NoSQL em Windows Azure Table Storage - Vitor Tomaz
NoSQL em Windows Azure Table Storage - Vitor TomazNoSQL em Windows Azure Table Storage - Vitor Tomaz
NoSQL em Windows Azure Table Storage - Vitor TomazComunidade NetPonto
 
De Zero a Produção - João Jesus
De Zero a Produção - João JesusDe Zero a Produção - João Jesus
De Zero a Produção - João JesusComunidade NetPonto
 
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone AppsComo deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone AppsComunidade NetPonto
 
Case studies about Layout & View States & Scale in Windows 8 Store Apps
Case studies about Layout & View States & Scale in Windows 8 Store AppsCase studies about Layout & View States & Scale in Windows 8 Store Apps
Case studies about Layout & View States & Scale in Windows 8 Store AppsComunidade NetPonto
 
Aspect-oriented Programming (AOP) com PostSharp
Aspect-oriented Programming (AOP) com PostSharpAspect-oriented Programming (AOP) com PostSharp
Aspect-oriented Programming (AOP) com PostSharpComunidade NetPonto
 
Utilização de Mock Objects em Testes Unitários
Utilização de Mock Objects em Testes UnitáriosUtilização de Mock Objects em Testes Unitários
Utilização de Mock Objects em Testes UnitáriosComunidade NetPonto
 
Dinâmica e Motivacao de Equipas de Projecto
Dinâmica e Motivacao de Equipas de ProjectoDinâmica e Motivacao de Equipas de Projecto
Dinâmica e Motivacao de Equipas de ProjectoComunidade NetPonto
 
KnockoutJS com ASP.NET MVC3: Utilização na vida real
KnockoutJS com ASP.NET MVC3: Utilização na vida realKnockoutJS com ASP.NET MVC3: Utilização na vida real
KnockoutJS com ASP.NET MVC3: Utilização na vida realComunidade NetPonto
 
Como ser programador durante o dia e mesmo assim dormir bem à noite
Como ser programador durante o dia e mesmo assim dormir bem à noiteComo ser programador durante o dia e mesmo assim dormir bem à noite
Como ser programador durante o dia e mesmo assim dormir bem à noiteComunidade NetPonto
 
Windows 8: Desenvolvimento de Metro Style Apps - C. Augusto Proiete
Windows 8: Desenvolvimento de Metro Style Apps - C. Augusto ProieteWindows 8: Desenvolvimento de Metro Style Apps - C. Augusto Proiete
Windows 8: Desenvolvimento de Metro Style Apps - C. Augusto ProieteComunidade NetPonto
 
Uma Introdução a ASP.NET Web API
Uma Introdução a ASP.NET Web APIUma Introdução a ASP.NET Web API
Uma Introdução a ASP.NET Web APIComunidade NetPonto
 
Como não entalar os dedos nas janelas: Finger-based apps no Windows 8
Como não entalar os dedos nas janelas: Finger-based apps no Windows 8Como não entalar os dedos nas janelas: Finger-based apps no Windows 8
Como não entalar os dedos nas janelas: Finger-based apps no Windows 8Comunidade NetPonto
 

Más de Comunidade NetPonto (20)

Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...
Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...
Continuous Delivery for Desktop Applications: a case study - Miguel Alho & Jo...
 
Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...
Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...
Criando aplicações para windows phone 8.1 e windows 8.1 com o app studio da...
 
MVVM Light e Cimbalino Toolkits - Sara Silva
MVVM Light e Cimbalino Toolkits - Sara SilvaMVVM Light e Cimbalino Toolkits - Sara Silva
MVVM Light e Cimbalino Toolkits - Sara Silva
 
Deep dive into Windows Azure Mobile Services - Ricardo Costa
Deep dive into Windows Azure Mobile Services - Ricardo CostaDeep dive into Windows Azure Mobile Services - Ricardo Costa
Deep dive into Windows Azure Mobile Services - Ricardo Costa
 
The power of templating.... with NVelocity - Nuno Cancelo
The power of templating.... with NVelocity - Nuno CanceloThe power of templating.... with NVelocity - Nuno Cancelo
The power of templating.... with NVelocity - Nuno Cancelo
 
ASP.Net Performance – A pragmatic approach - Luis Paulino
ASP.Net Performance – A pragmatic approach - Luis PaulinoASP.Net Performance – A pragmatic approach - Luis Paulino
ASP.Net Performance – A pragmatic approach - Luis Paulino
 
ASP.NET Signal R - Glauco Godoi
ASP.NET Signal R - Glauco GodoiASP.NET Signal R - Glauco Godoi
ASP.NET Signal R - Glauco Godoi
 
NoSQL em Windows Azure Table Storage - Vitor Tomaz
NoSQL em Windows Azure Table Storage - Vitor TomazNoSQL em Windows Azure Table Storage - Vitor Tomaz
NoSQL em Windows Azure Table Storage - Vitor Tomaz
 
HTML5 - Pedro Rosa
HTML5 - Pedro RosaHTML5 - Pedro Rosa
HTML5 - Pedro Rosa
 
De Zero a Produção - João Jesus
De Zero a Produção - João JesusDe Zero a Produção - João Jesus
De Zero a Produção - João Jesus
 
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone AppsComo deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
Como deixar de fazer "copy and paste" entre Windows Store e Windows Phone Apps
 
Case studies about Layout & View States & Scale in Windows 8 Store Apps
Case studies about Layout & View States & Scale in Windows 8 Store AppsCase studies about Layout & View States & Scale in Windows 8 Store Apps
Case studies about Layout & View States & Scale in Windows 8 Store Apps
 
Aspect-oriented Programming (AOP) com PostSharp
Aspect-oriented Programming (AOP) com PostSharpAspect-oriented Programming (AOP) com PostSharp
Aspect-oriented Programming (AOP) com PostSharp
 
Utilização de Mock Objects em Testes Unitários
Utilização de Mock Objects em Testes UnitáriosUtilização de Mock Objects em Testes Unitários
Utilização de Mock Objects em Testes Unitários
 
Dinâmica e Motivacao de Equipas de Projecto
Dinâmica e Motivacao de Equipas de ProjectoDinâmica e Motivacao de Equipas de Projecto
Dinâmica e Motivacao de Equipas de Projecto
 
KnockoutJS com ASP.NET MVC3: Utilização na vida real
KnockoutJS com ASP.NET MVC3: Utilização na vida realKnockoutJS com ASP.NET MVC3: Utilização na vida real
KnockoutJS com ASP.NET MVC3: Utilização na vida real
 
Como ser programador durante o dia e mesmo assim dormir bem à noite
Como ser programador durante o dia e mesmo assim dormir bem à noiteComo ser programador durante o dia e mesmo assim dormir bem à noite
Como ser programador durante o dia e mesmo assim dormir bem à noite
 
Windows 8: Desenvolvimento de Metro Style Apps - C. Augusto Proiete
Windows 8: Desenvolvimento de Metro Style Apps - C. Augusto ProieteWindows 8: Desenvolvimento de Metro Style Apps - C. Augusto Proiete
Windows 8: Desenvolvimento de Metro Style Apps - C. Augusto Proiete
 
Uma Introdução a ASP.NET Web API
Uma Introdução a ASP.NET Web APIUma Introdução a ASP.NET Web API
Uma Introdução a ASP.NET Web API
 
Como não entalar os dedos nas janelas: Finger-based apps no Windows 8
Como não entalar os dedos nas janelas: Finger-based apps no Windows 8Como não entalar os dedos nas janelas: Finger-based apps no Windows 8
Como não entalar os dedos nas janelas: Finger-based apps no Windows 8
 

Último

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 

Último (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 

Know your SQL Server - DMVs

  • 1. 23ª Reunião Lisboa - 24/09/2011 http://netponto.org Know your SQL Server - DMVs Vítor Pombeiro
  • 4. Vítor Pombeiro Developer no Banco Primus .Net 2.0 Web e Windows Applications SQL Server 2000 BI
  • 5. Agenda • DMVs • CPU • Memória • Índices e Estatísticas • IO
  • 6. DMVs • “Dynamic management views and functions return server state information that can be used to monitor the health of a server instance, diagnose problems, and tune performance.” (Books Online)
  • 7. CPU
  • 8. CPU select scheduler_id, current_tasks_count, runnable_tasks_count -->Valor a verificar from sys.dm_os_schedulers where scheduler_id < 1048576
  • 9. CPU SELECT TOP 10 (total_worker_time * 1.0) / 1000000 AS Total_Worker_Time_in_Seconds, execution_count, ((total_worker_time * 1.0) / 1000000) / execution_count AS Avg_Worker_Time_in_Seconds, (min_worker_time * 1.0) / 1000000 AS Min_Worker_Time_in_Seconds, (max_worker_time * 1.0) / 1000000 AS Max_Worker_Time_in_Seconds, text FROM sys.dm_exec_query_stats CROSS APPLY sys.dm_exec_sql_text(sql_handle) order by total_worker_time desc
  • 10. CPU select top 25 sql_text.text, plan_generation_num, execution_count from sys.dm_exec_query_stats a cross apply sys.dm_exec_sql_text(sql_handle) as sql_text where plan_generation_num >1 order by plan_generation_num desc
  • 11. CPU select timestamp, convert(xml, record) as info from sys.dm_os_ring_buffers where ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR' and record like '%<SystemHealth>%'
  • 12. CPU • Causas de bottleneck no CPU – Estatísticas – “WITH RECOMPILE” nas SPs • OPTION (RECOMPILE) – Paralelismo OPTION (MAXDOP) hint
  • 14. Memória select text, query_plan, requested_memory_kb, granted_memory_kb, used_memory_kb from sys.dm_exec_query_memory_grants MG CROSS APPLY sys.dm_exec_sql_text(sql_handle) CROSS APPLY sys.dm_exec_query_plan(MG.plan_handle)
  • 15. Memória SELECT Getdate() report_time, [cntr_value] as value_sec, cast(@@SERVERNAME as varchar) as ServerName FROM sys.dm_os_performance_counters WHERE [object_name] LIKE '%Manager%' AND [counter_name] = 'Page life expectancy'
  • 16. Memória • Causas – Configuração do SQL Server – AWE inactivo (32 bits) – Nº sessões activas
  • 17. Índices e estatísticas ROOT Intermediate Intermediate Leaf Leaf Leaf Leaf
  • 18. Índices e estatísticas select OBJECT_NAME(ps.object_id) as TableName ,si.Name ,ps.Avg_Fragmentation_in_percent ,STATS_DATE(ss.object_id,ss.stats_id) as LastUpdatedStatistics from sys.dm_db_index_physical_stats(DB_ID(DB_NAME()),null,null,null,null) ps join sysindexes si on ps.object_id = si.id and ps.index_id = si.indid left outer join sys.stats ss on ss.object_id = ps.object_id and ss.name = si.name where ps.avg_fragmentation_in_percent > 10 order by ps.avg_fragmentation_in_percent desc
  • 19. Índices e estatísticas SELECT TOP 10 [Total Cost] = ROUND(avg_total_user_cost * avg_user_impact * (user_seeks + user_scans),0) , avg_user_impact , statement as TableName , equality_columns , inequality_columns , included_columns FROM sys.dm_db_missing_index_groups g INNER JOIN sys.dm_db_missing_index_group_stats s ON s.group_handle = g.index_group_handle INNER JOIN sys.dm_db_missing_index_details d ON d.index_handle = g.index_handle ORDER BY [Total Cost] DESC;
  • 20. Índices e estatísticas SELECT TOP 10 DB_NAME() as DatabaseName , OBJECT_NAME(s.[object_id]) as TableName , IndexName = i.name, user_updates, system_updates FROM sys.dm_db_index_usage_stats s INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id WHERE s.database_id = DB_ID() AND OBJECTPROPERTY(s.[object_id], 'IsMsShipped') = 0 AND user_seeks = 0 AND user_scans = 0 AND user_lookups = 0 AND i.name IS NOT NULL -- Ignore HEAP indexes. ORDER BY user_updates DESC
  • 21. Índices e estatísticas • Causas – Muitos inserts, updates e deletes – Plano manutenção ineficaz – Excesso ou falta de índices – Shrink
  • 22. IO
  • 23. IO SELECT DB_NAME(fs.database_id) AS [Database Name], mf.physical_name, io_stall_read_ms, num_of_reads, CAST(io_stall_read_ms/(1.0 + num_of_reads) AS NUMERIC(10,1)) AS [avg_read_stall_ms],io_stall_write_ms, num_of_writes,CAST(io_stall_write_ms/(1.0+num_of_writes) AS NUMERIC(10,1)) AS [avg_write_stall_ms], io_stall_read_ms + io_stall_write_ms AS [io_stalls], num_of_reads + num_of_writes AS [total_io], CAST((io_stall_read_ms + io_stall_write_ms)/(1.0 + num_of_reads + num_of_writes) AS NUMERIC(10,1)) AS [avg_io_stall_ms] FROM sys.dm_io_virtual_file_stats(null,null) AS fs INNER JOIN sys.master_files AS mf ON fs.database_id = mf.database_id AND fs.[file_id] = mf.[file_id] ORDER BY avg_io_stall_ms DESC OPTION (RECOMPILE);
  • 24. IO Select wait_type, waiting_tasks_count, wait_time_ms / 1000 as wait_time_in_sec from sys.dm_os_wait_stats where wait_type like 'PAGEIOLATCH%' order by wait_type
  • 25. IO • tempDB • Índices • Recolha excessiva de dados • Base de dados com problemas no schema • Pouca memória
  • 27. Referências Books OnLine – http://msdn.microsoft.com/en-us/library/ms188754.aspx SQL Server DMV Starter Pack – http://www.red-gate.com/products/dba/sql-monitor/entrypage/dmv Glenn Berry – http://www.sqlservercentral.com/blogs/glennberry/archive/tags/DMV/defau lt.aspx – http://sqlserverperformance.wordpress.com
  • 30. Próximas reuniões presenciais • 24/09/2011 – Setembro (2 anos!) • 29/10/2011 – Outubro • 19/11/2011 – Outubro (Coimbra) • 26/11/2011 – Novembro Reserva estes dias na agenda! :)

Notas del editor

  1. VIEW SERVER STATE or VIEW DATABASE STATE permissionServer-scope e Database-scope
  2. Se os valores se mantiverem altos com frequência pode ser sinal de CPU bottleneck.Runnable_tasks_count : nº de querys a aguardar pelo processador
  3. Atenção que a DMV sys.dm_exec_query_stats pode dar resultados incorretos quando o servidor está em cargaVamos analisar as querys que correm menos vezes e com tempos muito altos ou as que correm muitas vezes e com tempos relativamente baixos
  4. Plan_generation_num indica o nº de vezes que a query foi recompiladaRazões: alterações de schema, alguns SET options e alterações nos dados das tabelas utilizadas
  5. Só mostra querys a aguardar por memória
  6. Não funciona para filtered index, spacial data