Sunday, September 19, 2010

Table variable indexes

Two types of indexes may be specified on a table variable - primary key (clustered) and unique. However, they need to be included in the table variable definition.

DECLARE @test TABLE
(
a INT PRIMARY KEY,
b varchar(50),
UNIQUE (b)
)


Generally, temp tables perform better in situations where an index is needed.

RAID for SQL Server

http://msdn.microsoft.com/en-us/library/ms190764.aspx

RAID 0 (disk striping)
This RAID level offers the highest throughput from a write perspective, but there is no redundancy built in. Since your backup files are your last line of defense and there is not a redundant set of data, I would not recommend this option.

RAID 1 (disk mirroring)
This level also offers a high level of I/O throughput as well as a redundant copy. The downside is that the size of the data partition using RAID 1 will be limited based on your physical disk size. One option would be to write your backup file to multiple RAID 1 arrays that are independent of each other and, possibly, to use different controllers or channels to further increase the I/O throughput.

RAID 5 (striping with parity)
With RAID 5 there is a write penalty because of the need to keep the parity in check. If you are really looking for faster backup processing, this RAID level does not make sense.

RAID 10 (mirroring with striping)
With RAID 10, you get the advantage of both RAID 0 and RAID 1. The downside is that it becomes very expensive to implement. But, the upside is your I/O throughput should be very fast. Since RAID 10 uses all of the drives in the array, to gain higher I/O rates, the more drives in the array will increase performance.


Recommended: Consider using independent pair of RAID1 volumes over RAID10

In addition to RAID levels, here are other things to take into consideration:

Controllers
In setting up your RAID arrays, try to isolate the different types of I/O traffic to different controller cards or channels on the controller cards. Also, the better the controller card, the better the performance.

Disk speeds
Disk drives come in multiple speeds. SCSI drives currently run as fast as 15 K rpm and are faster than the IDE drives. In most cases, enterprise-wide servers will probably be using SCSI technology which is the better choice.

Disk size
You can now get drives that are several GBs in size. This is great if you want to store a lot of data that is not accessed very often. But for writing out a large amount of data as fast as possible, large disk size doesn't help. What will be more advantageous are more drives in the array versus a couple of very large drives.


Refer: http://blogs.zdnet.com/Ou/?p=484



Tempdb - Separate RAID0
Data/Log- RAID 10 but pricey, or go for independent RAID1 arrays

Friday, September 10, 2010

Performance counters

Performance Object

Counter

Instance

Remarks

Memory

Pages/Sec

Rate of hard page faults;

Average value <>

Physical Disk

Average Disk Queue Length

Average number of queued disk requests;

Average value <>

Processor

% Processor Time

_Total

Average value <>

SQL Server: Access Methods

Freespace scans/sec

The areas where the count increases need to be monitored and proper indexes introduced to avoid such scans.

SQL Server: Access Methods

Full scans/sec

The areas where the count increases need to be monitored and indexes revisited.

SQL Server: Buffer Manager

Buffer Cache Hit Ratio

% of requests served out of the buffer cache;

Average value >= 90%

SQL Server: Locks

Lock timeouts/sec

_Total

Should be 0

SQL Server: Locks

Lock wait time (ms)

_Total

Should be low

SQL Server: Memory Manager

Memory Grants Pending

Number of processes waiting for workspace memory grant;

Average value = 0

SQL Server: SQL Statistics

SQL Re-compilations/sec

Should be 0 or near it

System

Processor Queue Length

Number of requests outstanding on the processor:

Average value <>

System

Context Switches/sec

Rate of switching processors from one thread to another:

Average value <>

Wednesday, August 18, 2010

Statistics test - when does it get updated?

create table t(a int, b varchar(20), c int)

declare @i int
select @i = 1
while @i <10000
begin
insert t select @i,'a' + convert(varchar(7),@i), @i + 100
select @i = @i + 1
end


select * from t
create clustered index ix_t_a on t(a)
create index ix_t_b on t(c)

dbcc show_statistics(t,'ix_t_a')
select * from sys.stats where object_id = object_id('t')
select * from t where c = 111
update statistics t with column

select name, auto_created, stats_date(object_id, stats_id) as update_date from sys.stats
where object_id = object_id('t')

name auto_created update_date
ix_t_a 0 2010-08-05 18:53:52.730
ix_t_b 0 2010-08-05 18:54:03.690
name auto_created update_date
_WA_Sys_00000002_09CAFFB2 1 2010-08-05 18:55:01.667
select * from t where b = 'a245'

alter index all on t rebuild


drop table t

Thursday, July 1, 2010

Performance story

Identifying Missing indexes using DMV and other useful DMVs

http://www.sql-server-performance.com/articles/per/Identify_Missing_Indexes_Using_SQL_Server_DMVs_p1.aspx


http://blogs.msdn.com/b/queryoptteam/archive/2006/04/06/570176.aspx


http://blogs.msdn.com/b/heynen/archive/2008/06/28/best-practices-for-dynamic-management-views.aspx



Top 10 worst CPU consuming queries on the SQL Server (since the last time the server was restarted)

SELECT TOP 10
sql.text as sql
, qp.query_plan
, creation_time
, last_execution_time
, execution_count
, (total_worker_time / execution_count) as avg_cpu
, total_worker_time as total_cpu
, last_worker_time as last_cpu
, min_worker_time as min_cpu
, max_worker_time as max_cpu
, (total_physical_reads + total_logical_reads) as total_reads
, (max_physical_reads + max_logical_reads) as max_reads
, (total_physical_reads + total_logical_reads) / execution_count as avg_reads
, max_elapsed_time as max_duration
, total_elapsed_time as total_duration
, ((total_elapsed_time / execution_count)) / 1000000 as avg_duration_sec
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(sql_handle) sql
CROSS APPLY sys.dm_exec_query_plan (plan_handle) qp
ORDER BY qs. total_worker_time DESC


Best practices and bottleneck identification

http://www.sqlserver-easy.com/content/view/33/44/


Performance dashboard query:

SELECT migs.avg_user_impact,
*
FROM sys.dm_db_missing_index_details AS mid
INNER JOIN sys.dm_db_missing_index_groups AS mig
ON mig.index_handle = mid.index_handle
INNER JOIN sys.dm_db_missing_index_group_stats AS migs
ON mig.index_group_handle=migs.group_handle
ORDER BY migs.avg_user_impact desc



http://searchsqlserver.techtarget.com/resources/Microsoft-SQL-Server-Performance-Monitoring-and-Tuning?adg=301324&bucket=ETA


Finding the indexes not used:

select i.name as indexname,
object_name(s.[object_id]) as tablename, s.database_id, s.[object_id], s.User_seeks, last_user_seek, user_scans, last_user_scan,
user_lookups, Last_user_lookup, user_updates, last_user_update
from sys.dm_db_index_usage_stats s
join sys.indexes i on s.object_id = i.object_id
and s.index_id = i.index_id
where OBJECTPROPERTY(s.OBJECT_ID,'IsUserTable') = 1
and user_scans + user_lookups + user_seeks = 0

Tuesday, March 30, 2010

Notes on Index Rebuild/Reorganize

you should rebuild when an index is over 30% fragmented and reorganize when an index is between 10% and 30% fragmented. If fragmentation is below 10%, you can probably just leave that index alone. Rebuilding takes more server resources (and uses locks unless you use the ONLINE option available in 2005 Enterprise and Development editions), so reorg when possible. Syntax below to rebuild or reorg all indexes on a table named tTable follows…

ALTER INDEX ALL ON dbo.tTable REBUILD
GO

ALTER INDEX ALL ON dbo.tTable REORGANIZE
GO



The differences between the two:

1) Index rebuild re-creates the index internally again and when that has been achieved, it drops the existing index.(Therefore the rebuild needs space for storing the new index.) Index reorganize is the process of physically re-organizing the leaf nodes of the index.

2) During index rebuild, the statistics are also re-computed – same as when a new index gets created. Reorganize on the other hand does not update the statistics. Reorganize essentially just swaps one page with another and thus does not require free space for this operation like rebuild does. Infact, reorganize can free up some pages as it does the reorg in two phases – compaction and defrag. A reorganize can remove almost all of the logical fragmentation but it cannot necessarily fix extent fragmentation in which the previous and the next extents are physically contiguous.

3) Another point to note is that an index (clustered or non-clustered) cannot be built online if it contains LOB data (text, ntext, varchar(max), nvarchar(max), varbinary(max), image and xml data type columns). The ALTER INDEX…REORGANIZE command shown above is the same as DBCC INDEXDEFRAG but there is one difference. ALTER INDEX…REORGANIZE has some additional features like large objects compaction (LOB_COMPACTION). And this is an online operation.

4) Regarding partitions of an index, if an index has multiple partitions, then you cannot rebuild a single partition online. You can reorganize a single index partition online. If you want to rebuild an index with multiple partitions in an online environment, you need to rebuild the entire index which means rebuilding all the partitions.


Reorganizing an index defragments the leaf level of clustered and nonclustered indexes on tables and views by physically reordering the leaf-level pages to match the logical order (left to right) of the leaf nodes. Having the pages in order improves index-scanning performance. The index is reorganized within the existing pages allocated to it; no new pages are allocated. If an index spans more than one file, the files are reorganized one at a time. Pages do not migrate between files.

Reorganizing also compacts the index pages. Any empty pages created by this compaction are removed providing additional available disk space. Compaction is based on the fill factor value in the sys.indexes catalog view.

The reorganize process uses minimal system resources. Also, reorganizing is automatically performed online. The process does not hold long-term blocking locks; therefore, it will not block running queries or updates.

Reorganize an index when the index is not heavily fragmented. See the previous table for fragmentation guidelines. However, if the index is heavily fragmented, you will achieve better results by rebuilding the index.

http://technet.microsoft.com/en-us/library/ms189858.aspx





----------------
further notes - to rework


Types of searches

* Full scans
* Binary searches
* Linear interpolation - fixed record size, monotonely increasing key

Singleton Lookup

* Index Seek / Clustered Index Seek
* Find record using index pages

Allocation Order Scan

* Table Scan or unordered Clustered/Index Scan
* Pages splits during allocation order scans
* Table lock helps (TABLOCK, TABLOCKX) but not required

Advanced scanning

* Also known as "Merry-go-round" scan
* Multiple scans on the same table
* First scan starts, second scan joins in the middle, later scans the rest
* Enterprise edition only
* allocation order scans only
* See http://www.sqlmag.com/Article/ArticleID/49285/sql_server_49285.html
* See http://msdn2.microsoft.com/en-us/library/ms191475.aspx

Range Scan

* Index Scan / Clustered Index Scan
* Find first, then follw next page pointer

Readahead

* Pre-reading of pages in the leaf level during Range Scans
* 1, 8 or 32 pages (8KB, 64KB or 256KB) - only if pages are contiguous
* 128 pages (1024KB) only in Enterprise edition
* Logical fragmentation prevents optimal readahead
* See http://msdn.microsoft.com/en-us/library/ms191475.aspx

Logical Fragmentation

* Next page pointer does not point to next physical page
* DBCC SHOWCONTIG is deprecated now
* Look at avg_fragmentation_in_percent in sys.dm_db_index_physical_stats
* Not relevant if you have a small number of pages (less than 100?)
* Not relevant if all pages are already in the buffer pool (in cache)
* Logical IOs are not necessarily physical IOs

When to do something about it

* When to rebuild/reorganize? It always depends...
* Different for data warehouse or OLTP, for instance
* If you must have a number: 5-30% - ALTER INDEX REORGANIZE
* If you must have a number: >30% - ALTER INDEX REBUILD WITH (ONLINE = ON)*
* See http://msdn.microsoft.com/en-us/library/ms189858.aspx
* Many just rebuild everything every week (could be totally unnecessary)

Extent Fragmentation

* Extents are not contiguous
* Affects readahead, but not much (can read 8 but not 32 pages)
* In a heap, logical fragmentation is actually extent fragmentation
* With multiple files, round robin does not necessarily mean fragmentation
* Interesting KB: http://support.microsoft.com/kb/329526

Page Density

* How much space is actually in use in the page
* Affected by row size (5K fixed-length row leaves 3K unused in every page)
* Affected by page splits
* Affected by FILLFACTOR
* In the end, low page density leads to more IOs
* This is actually a kind of fragmentation

Page Splits

* Page is full and you need to add something (INSERT, UPDATE with larger data)
* Take half the rows to a new page, fix up all the pointers in both
* Could lead to page splits to non-leaf levels, all the way up to the root
* All fully logged, not matter what log level you are in
* Typically creates two low-density pages and are not contiguous
* Does not happen with a heap, only with a clustered index
* Does not happen with a key that is ever increasing (like identity)

Things that cause fragmentation

* GUID as high order key (NEWSEQUENTIALID can help)
* Variable lenght colums
* Misconfigured FILLFACTOR
* Wide rows (with 5K rows being the typical example)
* Clustered indexes that cause random insertion order (sales with customer,date)

FILLFACTOR

* Leave space on pages to avoid page splits in leaf level
* Applies only on rebuild, not when doing INSERT/UPDATE
* PAD_INDEX will do the same thing for non-leaf level
* For data warehouse, no need for FILLFACTOR
* For OLTP, it's hard to calculate the ideal factor, no quick answer
* Look at how many splits, how frequently you can rebuild
* Pick a value, watch how it goes. Then change factor or rebuild frequency
* If you must choose a number, try 70%

Symptoms of at Fragmentation

* Longer run times
* More disk activity (SET STATISTICS IO ON)
* More logging activity

Looking at Fragmentation

* Query sys.dm_db_index_physical_stats (replaces DBCC SHOWCONTIG)
* Look at avg_fragmentation_in_percent for fragmentation
* Look at avg_page_space_used_in_percent for page density
* You can summarize the results, join with sys.indexes to show index names
* See sample query at http://www.sqlskills.com/blogs/paul/post/Can-GUID-cluster-keys-cause-non-clustered-index-fragmentation.aspx

Querying sys.dm_db_index_physical_stats

* It could be expensive, since it bring lots of pages into the buffer pool
* DETAILED (reads everything)
* SAMPLED (reads 1% of the pages if less than 10,000 pages)
* LIMITED (parent level of b-tree, same as DBCC SHOWCONTIG WITH FAST)
* Limited can't tell you page density, since it does not read the page level

Fixing fragmentation

* Three main choices
* Rebuild - ALTER INDEX ... REBUILD (replaces DBCC REINDEX)
* Recreate - CREATE INDEX WITH DROP_EXISTING
* Reorganize - ALTER INDEX ... REORGANIZE (replaces DBCC INDEXDEFRAG)
* DROP, CREATE (separately) not good due to possible issue with constraints
* You can also decide not to do anything at all
* You don't necessarily have to rebuild everything every day...

Rebuild

* Can be done online (unless you have LOB columns)
* Can use multiple CPUs (control with MAXDOP)
* Works single partition or all partitions
* Rebuilds index statistics (equivalent of a full scan)
* Does not update column statistics
* Can be minimally logged
* Atomic. If you interrupt, it rolls back.
* Online - short-hold Shared lock, short-hold SCHema_Mod lock
* Offline clustered - eXclusive lock
* Offline non-clustered - Shared lock
* Creates new before dropping old. Reads from the old index.
* Always rebuilds everything. Faster for largely fragmented indexes.

Online Index Rebuild

* 1) Preparation - New index is created and set to write-only
* very short Shared lock
* 2) Build - Data is inserted from source.
* Two copies of the data being updated
* Scans know they shouldn't use the other - "anti-matter" record
* 3) Final - Index metadata is updated.
* short-hold SCHema_Mod lock
* Old data is dropped
* Details at http://msdn.microsoft.com/en-us/library/ms191261.aspx

Recreate

* Basically same as rebuild
* Can move to a new location
* Can change the schema
* Good way to do a shrink without using shrink

Reorganize

* Is always online (even if you have LOB columns)
* Always single threaded
* Works single partition or all partitions
* Table IX lock - locks only TABLOCKs and escalated locks
* Addresses only existing fragmentation
* Faster for lightly fragemented indexes
* Does not use much extra space

Reorganize Phase 1 - Page compaction

* Moves data from neighbor pages to get closer to FILLFACTOR
* Leaf level only. Works on a sliding window (a few pages at a time)
* Tries eXclusive lock on the pages involved. If can't, moves on.
* If it can empty pages, it will deallocated them.
* It will also remove ghost records.

Reorganize Phase 2 - Page defragment

* Make logical order the same as the allocation order
* Leaf level only. Shuffle pages arounds without using extra space.
* Uses one extra free page (page type 19 - unlinked reorg page)
* Locks enough pages to get the operation done without blocking others.
* Reminded me of the "towers of hanoi" problem :-)

Wednesday, March 17, 2010

Statistics basic

To list all of the statistics being maintained on a table-

select * from sys.stats where object_id = object_id('brkprd')


To retrieve detailed information about an index or statistic

dbcc show_statistics ('brkprd','IX_Brkprd_AcctIdIsNonZeroBP')