1NF Eliminate Repeating Groups -
Make a separate table for each set of related attributes, and give each table a primary key.
2NF Eliminate Redundant Data -
If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3NF Eliminate Columns Not Dependent On Key -
If attributes do not contribute to a description of the key, remove them to a separate table.
BCNF Boyce-Codd Normal Form -
If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables.
4NF Isolate Independent Multiple Relationships -
No table may contain two or more 1:n or n:m relationships that are not directly related.
5NF Isolate Semantically Related Multiple Relationships -
There may be practical constrains on information that justify separating logically related many-to-many relationships.
ONF Optimal Normal Form -
a model limited to only simple (elemental) facts, as expressed in Object Role Model notation.
DKNF Domain-Key Normal Form -
a model free from all modification anomalies.
http://support.microsoft.com/kb/283878
Tuesday, February 12, 2008
Friday, February 1, 2008
Performance Counters
SQLServer: Buffer Manager - Buffer cache hit ratio
The percentage of pages that were found in the memory. Higher the value the better. Preferred around the 90% mark. This included the availability of the procedure and the data cache in the system.
SQLServer: General Statistics - User Connections
The number of users currently connected to the SQL Server.
SQLServer:Access Methods - Full Scans / sec
Value greater than 1 or 2 indicates that we are having table / Index page scans. We need to analyze how this can be avoided.
SQLServer:Access Methods - Table Lock Escalations/sec
This gives us the number of times a table lock was asked for in a second. A high number needs a revisit to the query and the indexes on the table.
Processor - %Processor Time
The percentage of time the processor spent executing a non-idle thread. This value is subtracted from the time the processor was idle 100 percent. This is an indicator to the overall CPU utilization in the system.
Processor - %Interrupt Time
The percentage of time the processor spent servicing hardware interrupts. This can be any activity on the server machine. This needs to be 0 while our testing process.
Processor - Processor Queue Length
This counter indicates the number of threads that are waiting in the processor queue. It can be also interpreted as the number of threads that are waiting to be run by the processor. If this value is greater than the number of processor then we have a CPU bottleneck in the system.
Processor - Context Switches/sec
A typical context switch occurs when the OS or the application is forced to change the executing thread on one processor to another thread executed on another processor. This value has to be as small as possible. Context switches are not avoidable in multi-processor machines. Hence any value below 10000 is fine.
PhysicalDisk - %Disk Read Time
Time spent by the disk for read operation. We can have disk by disk analysis also to narrow down any read IO bottlenecks.
PhysicalDisk - %Disk Write Time
Time spent by the disk for write operation. We can have disk by disk analysis also to narrow down any write IO bottlenecks.
PhysicalDisk - Avg. Disk Queue Length
Average number of requests that waited for the read and write requests in the particular disk. A high value suggests we have an IO bottleneck.
Memory - Page Faults/sec
Total number of faulted pages handled by the processor per second. This value needs to as small as possible.
Memory - Pages/sec
The number of pages written to disk or from disk to resolve page faults. This would be the sum of page reads/sec and page writes/sec counter.
The percentage of pages that were found in the memory. Higher the value the better. Preferred around the 90% mark. This included the availability of the procedure and the data cache in the system.
SQLServer: General Statistics - User Connections
The number of users currently connected to the SQL Server.
SQLServer:Access Methods - Full Scans / sec
Value greater than 1 or 2 indicates that we are having table / Index page scans. We need to analyze how this can be avoided.
SQLServer:Access Methods - Table Lock Escalations/sec
This gives us the number of times a table lock was asked for in a second. A high number needs a revisit to the query and the indexes on the table.
Processor - %Processor Time
The percentage of time the processor spent executing a non-idle thread. This value is subtracted from the time the processor was idle 100 percent. This is an indicator to the overall CPU utilization in the system.
Processor - %Interrupt Time
The percentage of time the processor spent servicing hardware interrupts. This can be any activity on the server machine. This needs to be 0 while our testing process.
Processor - Processor Queue Length
This counter indicates the number of threads that are waiting in the processor queue. It can be also interpreted as the number of threads that are waiting to be run by the processor. If this value is greater than the number of processor then we have a CPU bottleneck in the system.
Processor - Context Switches/sec
A typical context switch occurs when the OS or the application is forced to change the executing thread on one processor to another thread executed on another processor. This value has to be as small as possible. Context switches are not avoidable in multi-processor machines. Hence any value below 10000 is fine.
PhysicalDisk - %Disk Read Time
Time spent by the disk for read operation. We can have disk by disk analysis also to narrow down any read IO bottlenecks.
PhysicalDisk - %Disk Write Time
Time spent by the disk for write operation. We can have disk by disk analysis also to narrow down any write IO bottlenecks.
PhysicalDisk - Avg. Disk Queue Length
Average number of requests that waited for the read and write requests in the particular disk. A high value suggests we have an IO bottleneck.
Memory - Page Faults/sec
Total number of faulted pages handled by the processor per second. This value needs to as small as possible.
Memory - Pages/sec
The number of pages written to disk or from disk to resolve page faults. This would be the sum of page reads/sec and page writes/sec counter.
Lock-Unlock!
There are two scopes to this discussion - Lock modes & Lock granularity.
But before it, we begin with a prelude to Lock Escalation.
The process of converting many fine-grain locks into fewer coarse-grain locks, reducing system overhead while increasing the probability of concurrency contention, is known as
Lock Escalation.
As the Database Engine acquires low-level locks, it also places intent locks on the objects containing the lower-level objects:
1. When locking rows or index key ranges, the Database Engine places an intent lock on the pages containing the rows or keys.
2. When locking pages, the Database Engine places an intent lock on the higher level objects containing the pages. In addition to placing an intent object (OBJECT) lock on the table, intent heap or B-tree (HOBT) locks are requested on:
a.The nonclustered index if the pages are nonclustered index pages.
b. The clustered index if the pages are clustered index pages. This includes data pages in tables that have a clustered index.
c. The heap of data pages if the pages are data pages in a table that does not have a clustered index.
Lock escalation is initiated at either of these times:
1. When a single Transact-SQL statement acquires 5,000 locks on a single table or index.
2. When the number of locks in an instance of the Database Engine exceeds memory or configuration thresholds.
Assume that a single SELECT statement is a join that accesses three tables in this sequence: TableA, TableB, and TableC. The statement acquires 3,000 row locks in the clustered index for TableA and 5,000 row locks in the clustered index for TableB, but has not yet accessed TableC. When the Database Engine detects that the statement has acquired the 5,000 row locks in TableB, it attempts to escalate all locks held by the session in TableB. It also attempts to escalate all locks held by the session in TableA, but since the number of locks on TableA is < 5000, the escalation will not succeed. No lock escalation is attempted for TableC because it had not yet been accessed when the escalation occurred.
1. The simplest and safest way to prevent lock escalation is to keep transactions short and to reduce the lock footprint of expensive queries so that the lock escalation thresholds are not exceeded.
Break up large batch operations into several smaller operations.
2. Reduce the query's lock footprint by making the query as efficient as possible. Large scans or large numbers of Bookmark Lookups may increase the chance of lock escalation; additionally, it increases the chance of deadlocks, and generally adversely affects concurrency and performance. After you find the query that causes lock escalation, look for opportunities to create new indexes or to add columns to an existing index to remove index or table scans and to maximize the efficiency of index seeks.
3. Lock escalation cannot occur if a different SPID is currently holding an incompatible table lock. Lock escalation always escalates to a table lock, and never to page locks. Additionally, if a lock escalation attempt fails because another SPID holds an incompatible TAB lock, the query that attempted escalation does not block while waiting for a TAB lock. Instead, it continues to acquire locks at its original, more granular level (row, key, or page), periodically making additional escalation attempts. Therefore, one method to prevent lock escalation on a particular table is to acquire and to hold a lock on a different connection that is not compatible with the escalated lock type. For example, assume that you must run a batch job that modifies a large number of rows in the mytable table and that has caused blocking that occurs because of lock escalation. If this job always completes in less than an hour, you might create a Transact-SQL job that contains the following code, and schedule the new job to start several minutes before the batch job's start time:
BEGIN TRAN
SELECT * FROM mytable (UPDLOCK, HOLDLOCK) WHERE 1=0
WAITFOR DELAY '1:00:00'
COMMIT TRAN
This query acquires and holds an IX lock on mytable for one hour, which prevents lock escalation on the table during that time. This batch does not modify any data or block other queries
May disable lock escalation by enabling trace flag 1211. However, this trace flag disables all lock escalation globally in the instance of SQL Server.
Lock escalation serves a very useful purpose in SQL Server by maximizing the efficiency of queries that are otherwise slowed down by the overhead of acquiring and releasing several thousands of locks. Lock escalation also helps to minimize the required memory to keep track of locks.
To reduce the amount of locking by:
1. Using an isolation level that does not generate shared locks for read operations.
2. READ COMMITTED isolation level when the READ_COMMITTED_SNAPSHOT database option is ON.
3. SNAPSHOT isolation level.
4. READ UNCOMMITTED isolation level. This can only be used for systems that can operate with dirty reads.
Using the PAGLOCK or TABLOCK table hints to have the Database Engine use page, heap, or index locks instead of row locks. Using this option, however, increases the problems of users blocking other users attempting to access the same data and should not be used in systems with more than a few concurrent users.
You can also use trace flags 1211 and 1224 to disable all or some lock escalations.
Lock Modes
1. Shared (S)
Used for read operations that do not change or update data, such as a SELECT statement. No other transactions can modify the data while shared (S) locks exist on the resource.
2. Update (U)
Used on resources that can be updated. Prevents a common form of deadlock that occurs when multiple sessions are reading, locking, and potentially updating resources later.
Update (U) locks prevent a common form of deadlock. In a repeatable read or serializable transaction, the transaction reads data, acquiring a shared (S) lock on the resource (page or row), and then modifies the data, which requires lock conversion to an exclusive (X) lock. If two transactions acquire shared-mode locks on a resource and then attempt to update data concurrently, one transaction attempts the lock conversion to an exclusive (X) lock. The shared-mode-to-exclusive lock conversion must wait because the exclusive lock for one transaction is not compatible with the shared-mode lock of the other transaction; a lock wait occurs. The second transaction attempts to acquire an exclusive (X) lock for its update. Because both transactions are converting to exclusive (X) locks, and they are each waiting for the other transaction to release its shared-mode lock, a deadlock occurs.
To avoid this potential deadlock problem, update (U) locks are used. Only one transaction can obtain an update (U) lock to a resource at a time. If a transaction modifies a resource, the update (U) lock is converted to an exclusive (X) lock.
3. Exclusive (X)
Used for data-modification operations, such as INSERT, UPDATE, or DELETE. Ensures that multiple updates cannot be made to the same resource at the same time.
With an exclusive (X) lock, no other transactions can modify data; read operations can take place only with the use of the NOLOCK hint or read uncommitted isolation level.
4. Intent
Used to establish a lock hierarchy. The types of intent locks are: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).
Intent locks serve two purposes:
To prevent other transactions from modifying the higher-level resource in a way that would invalidate the lock at the lower level.
To improve the efficiency of the Database Engine in detecting lock conflicts at the higher level of granularity.
For example, a shared intent lock is requested at the table level before shared (S) locks are requested on pages or rows within that table. Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. Intent locks improve performance because the Database Engine examines intent locks only at the table level to determine if a transaction can safely acquire a lock on that table. This removes the requirement to examine every row or page lock on the table to determine if a transaction can lock the entire table.
5. Schema
Used when an operation dependent on the schema of a table is executing. The types of schema locks are: schema modification (Sch-M) and schema stability (Sch-S).
Schema modification (Sch-M) locks are used when performing a table data definition language (DDL) operation, such as adding a column or dropping a table. During the time the schema modification (Sch-M) lock is held, concurrent access to the table is prevented. This means that all operations outside of the schema modification (Sch-M) lock will be blocked until the lock is released.
Schema stability (Sch-S) locks are used when compiling queries. Schema stability (Sch-S) locks do not block any transactional locks, including exclusive (X) locks. Therefore, other transactions can continue to run while a query is being compiled, including transactions with exclusive (X) locks on a table. However, DDL operations cannot be performed on the table.
6. Bulk Update (BU)
Used when bulk copying data into a table and the TABLOCK hint is specified.
7. Key-range
Protects the range of rows read by a query when using the serializable transaction isolation level. Ensures that other transactions cannot insert rows that would qualify for the queries of the serializable transaction if the queries were run again.
Now the granularity:
1. RID - A row identifier used to lock a single row within a heap.
2. KEY - A row lock within an index used to protect key ranges in serializable transactions.
3. PAGE - An 8-kilobyte (KB) page in a database, such as data or index pages.
4. EXTENT - A contiguous group of eight pages, such as data or index pages.
5. HOBT - A heap or B-tree. A lock protecting an index or the heap of data pages in a table that does not have a clustered index.
6. TABLE - The entire table, including all data and indexes.
7. FILE - A database file.
8. APPLICATION - An application-specified resource.
9. METADATA - Metadata locks.
10. ALLOCATION_UNIT - An allocation unit.
11. DATABASE - The entire database.
But before it, we begin with a prelude to Lock Escalation.
The process of converting many fine-grain locks into fewer coarse-grain locks, reducing system overhead while increasing the probability of concurrency contention, is known as
Lock Escalation.
As the Database Engine acquires low-level locks, it also places intent locks on the objects containing the lower-level objects:
1. When locking rows or index key ranges, the Database Engine places an intent lock on the pages containing the rows or keys.
2. When locking pages, the Database Engine places an intent lock on the higher level objects containing the pages. In addition to placing an intent object (OBJECT) lock on the table, intent heap or B-tree (HOBT) locks are requested on:
a.The nonclustered index if the pages are nonclustered index pages.
b. The clustered index if the pages are clustered index pages. This includes data pages in tables that have a clustered index.
c. The heap of data pages if the pages are data pages in a table that does not have a clustered index.
Lock escalation is initiated at either of these times:
1. When a single Transact-SQL statement acquires 5,000 locks on a single table or index.
2. When the number of locks in an instance of the Database Engine exceeds memory or configuration thresholds.
Assume that a single SELECT statement is a join that accesses three tables in this sequence: TableA, TableB, and TableC. The statement acquires 3,000 row locks in the clustered index for TableA and 5,000 row locks in the clustered index for TableB, but has not yet accessed TableC. When the Database Engine detects that the statement has acquired the 5,000 row locks in TableB, it attempts to escalate all locks held by the session in TableB. It also attempts to escalate all locks held by the session in TableA, but since the number of locks on TableA is < 5000, the escalation will not succeed. No lock escalation is attempted for TableC because it had not yet been accessed when the escalation occurred.
1. The simplest and safest way to prevent lock escalation is to keep transactions short and to reduce the lock footprint of expensive queries so that the lock escalation thresholds are not exceeded.
Break up large batch operations into several smaller operations.
2. Reduce the query's lock footprint by making the query as efficient as possible. Large scans or large numbers of Bookmark Lookups may increase the chance of lock escalation; additionally, it increases the chance of deadlocks, and generally adversely affects concurrency and performance. After you find the query that causes lock escalation, look for opportunities to create new indexes or to add columns to an existing index to remove index or table scans and to maximize the efficiency of index seeks.
3. Lock escalation cannot occur if a different SPID is currently holding an incompatible table lock. Lock escalation always escalates to a table lock, and never to page locks. Additionally, if a lock escalation attempt fails because another SPID holds an incompatible TAB lock, the query that attempted escalation does not block while waiting for a TAB lock. Instead, it continues to acquire locks at its original, more granular level (row, key, or page), periodically making additional escalation attempts. Therefore, one method to prevent lock escalation on a particular table is to acquire and to hold a lock on a different connection that is not compatible with the escalated lock type. For example, assume that you must run a batch job that modifies a large number of rows in the mytable table and that has caused blocking that occurs because of lock escalation. If this job always completes in less than an hour, you might create a Transact-SQL job that contains the following code, and schedule the new job to start several minutes before the batch job's start time:
BEGIN TRAN
SELECT * FROM mytable (UPDLOCK, HOLDLOCK) WHERE 1=0
WAITFOR DELAY '1:00:00'
COMMIT TRAN
This query acquires and holds an IX lock on mytable for one hour, which prevents lock escalation on the table during that time. This batch does not modify any data or block other queries
May disable lock escalation by enabling trace flag 1211. However, this trace flag disables all lock escalation globally in the instance of SQL Server.
Lock escalation serves a very useful purpose in SQL Server by maximizing the efficiency of queries that are otherwise slowed down by the overhead of acquiring and releasing several thousands of locks. Lock escalation also helps to minimize the required memory to keep track of locks.
To reduce the amount of locking by:
1. Using an isolation level that does not generate shared locks for read operations.
2. READ COMMITTED isolation level when the READ_COMMITTED_SNAPSHOT database option is ON.
3. SNAPSHOT isolation level.
4. READ UNCOMMITTED isolation level. This can only be used for systems that can operate with dirty reads.
Using the PAGLOCK or TABLOCK table hints to have the Database Engine use page, heap, or index locks instead of row locks. Using this option, however, increases the problems of users blocking other users attempting to access the same data and should not be used in systems with more than a few concurrent users.
You can also use trace flags 1211 and 1224 to disable all or some lock escalations.
Lock Modes
1. Shared (S)
Used for read operations that do not change or update data, such as a SELECT statement. No other transactions can modify the data while shared (S) locks exist on the resource.
2. Update (U)
Used on resources that can be updated. Prevents a common form of deadlock that occurs when multiple sessions are reading, locking, and potentially updating resources later.
Update (U) locks prevent a common form of deadlock. In a repeatable read or serializable transaction, the transaction reads data, acquiring a shared (S) lock on the resource (page or row), and then modifies the data, which requires lock conversion to an exclusive (X) lock. If two transactions acquire shared-mode locks on a resource and then attempt to update data concurrently, one transaction attempts the lock conversion to an exclusive (X) lock. The shared-mode-to-exclusive lock conversion must wait because the exclusive lock for one transaction is not compatible with the shared-mode lock of the other transaction; a lock wait occurs. The second transaction attempts to acquire an exclusive (X) lock for its update. Because both transactions are converting to exclusive (X) locks, and they are each waiting for the other transaction to release its shared-mode lock, a deadlock occurs.
To avoid this potential deadlock problem, update (U) locks are used. Only one transaction can obtain an update (U) lock to a resource at a time. If a transaction modifies a resource, the update (U) lock is converted to an exclusive (X) lock.
3. Exclusive (X)
Used for data-modification operations, such as INSERT, UPDATE, or DELETE. Ensures that multiple updates cannot be made to the same resource at the same time.
With an exclusive (X) lock, no other transactions can modify data; read operations can take place only with the use of the NOLOCK hint or read uncommitted isolation level.
4. Intent
Used to establish a lock hierarchy. The types of intent locks are: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SIX).
Intent locks serve two purposes:
To prevent other transactions from modifying the higher-level resource in a way that would invalidate the lock at the lower level.
To improve the efficiency of the Database Engine in detecting lock conflicts at the higher level of granularity.
For example, a shared intent lock is requested at the table level before shared (S) locks are requested on pages or rows within that table. Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. Intent locks improve performance because the Database Engine examines intent locks only at the table level to determine if a transaction can safely acquire a lock on that table. This removes the requirement to examine every row or page lock on the table to determine if a transaction can lock the entire table.
5. Schema
Used when an operation dependent on the schema of a table is executing. The types of schema locks are: schema modification (Sch-M) and schema stability (Sch-S).
Schema modification (Sch-M) locks are used when performing a table data definition language (DDL) operation, such as adding a column or dropping a table. During the time the schema modification (Sch-M) lock is held, concurrent access to the table is prevented. This means that all operations outside of the schema modification (Sch-M) lock will be blocked until the lock is released.
Schema stability (Sch-S) locks are used when compiling queries. Schema stability (Sch-S) locks do not block any transactional locks, including exclusive (X) locks. Therefore, other transactions can continue to run while a query is being compiled, including transactions with exclusive (X) locks on a table. However, DDL operations cannot be performed on the table.
6. Bulk Update (BU)
Used when bulk copying data into a table and the TABLOCK hint is specified.
7. Key-range
Protects the range of rows read by a query when using the serializable transaction isolation level. Ensures that other transactions cannot insert rows that would qualify for the queries of the serializable transaction if the queries were run again.
Now the granularity:
1. RID - A row identifier used to lock a single row within a heap.
2. KEY - A row lock within an index used to protect key ranges in serializable transactions.
3. PAGE - An 8-kilobyte (KB) page in a database, such as data or index pages.
4. EXTENT - A contiguous group of eight pages, such as data or index pages.
5. HOBT - A heap or B-tree. A lock protecting an index or the heap of data pages in a table that does not have a clustered index.
6. TABLE - The entire table, including all data and indexes.
7. FILE - A database file.
8. APPLICATION - An application-specified resource.
9. METADATA - Metadata locks.
10. ALLOCATION_UNIT - An allocation unit.
11. DATABASE - The entire database.
Saturday, October 27, 2007
Analysing defragmentation
DBCC SHOWCONTIG(MyTable1)
GO
DBCC SHOWCONTIG scanning 'MyTable1' table...
Table: 'MyTable1' (1556968673); index ID: 1, database ID: 16
TABLE level scan performed.
- Pages Scanned................................: 18986
- Extents Scanned..............................: 2443
- Extent Switches..............................: 9238
- Avg. Pages per Extent........................: 7.8
- Scan Density [Best Count:Actual Count].......: 25.70% [2374:9239]
- Logical Scan Fragmentation ..................: 44.58%
- Extent Scan Fragmentation ...................: 87.07%
- Avg. Bytes Free per Page.....................: 1658.7
- Avg. Page Density (full).....................: 79.51%
DBCC execution completed. If DBCC printed error messages,
contact your system administrator.
* There were 18,986 pages examined to create the report. Those pages existed within 2,443 extents
* While examining the pages for fragmentation, the server had to switch extent locations 9,238 times.
The Scan Density restates this by indicating the percentage of all pages within all extents were contiguous. In an ideal environment, the density displayed would be close to 100.
* The Logical Scan Fragmentation and Extent Scan Fragmentation are indications of how well the indexes are stored within the system when a clustered index is present (and should be ignored for tables that do not have a clustered index).
In both cases, a number close to 0 is preferable.
* There are an average of 1659 bytes free per page, or that each page is 79.51% utilized. The closer that number gets to 100, the faster the database is able to read in records, since more records exist on a single page. However, this must be balanced with the cost of writing to the table. Since a page split will occur if a write is required on a page that is full, the overhead can be tremendous.
After DBCC INDEXDEFRAG/DBREINDEX
DBCC SHOWCONTIG scanning 'MyTable1' table...
Table: 'MyTable1' (1556968673); index ID: 1, database ID: 16
TABLE level scan performed.
- Pages Scanned................................: 15492
- Extents Scanned..............................: 1945
- Extent Switches..............................: 2363
- Avg. Pages per Extent........................: 8.0
- Scan Density [Best Count:Actual Count].......: 81.94% [1937:2364]
- Logical Scan Fragmentation ..................: 15.43%
- Extent Scan Fragmentation ...................: 20.15%
- Avg. Bytes Free per Page.....................: 159.8
- Avg. Page Density (full).....................: 98.03%
DBCC execution completed. If DBCC printed error messages,
contact your system administrator.
GO
DBCC SHOWCONTIG scanning 'MyTable1' table...
Table: 'MyTable1' (1556968673); index ID: 1, database ID: 16
TABLE level scan performed.
- Pages Scanned................................: 18986
- Extents Scanned..............................: 2443
- Extent Switches..............................: 9238
- Avg. Pages per Extent........................: 7.8
- Scan Density [Best Count:Actual Count].......: 25.70% [2374:9239]
- Logical Scan Fragmentation ..................: 44.58%
- Extent Scan Fragmentation ...................: 87.07%
- Avg. Bytes Free per Page.....................: 1658.7
- Avg. Page Density (full).....................: 79.51%
DBCC execution completed. If DBCC printed error messages,
contact your system administrator.
* There were 18,986 pages examined to create the report. Those pages existed within 2,443 extents
* While examining the pages for fragmentation, the server had to switch extent locations 9,238 times.
The Scan Density restates this by indicating the percentage of all pages within all extents were contiguous. In an ideal environment, the density displayed would be close to 100.
* The Logical Scan Fragmentation and Extent Scan Fragmentation are indications of how well the indexes are stored within the system when a clustered index is present (and should be ignored for tables that do not have a clustered index).
In both cases, a number close to 0 is preferable.
* There are an average of 1659 bytes free per page, or that each page is 79.51% utilized. The closer that number gets to 100, the faster the database is able to read in records, since more records exist on a single page. However, this must be balanced with the cost of writing to the table. Since a page split will occur if a write is required on a page that is full, the overhead can be tremendous.
After DBCC INDEXDEFRAG/DBREINDEX
DBCC SHOWCONTIG scanning 'MyTable1' table...
Table: 'MyTable1' (1556968673); index ID: 1, database ID: 16
TABLE level scan performed.
- Pages Scanned................................: 15492
- Extents Scanned..............................: 1945
- Extent Switches..............................: 2363
- Avg. Pages per Extent........................: 8.0
- Scan Density [Best Count:Actual Count].......: 81.94% [1937:2364]
- Logical Scan Fragmentation ..................: 15.43%
- Extent Scan Fragmentation ...................: 20.15%
- Avg. Bytes Free per Page.....................: 159.8
- Avg. Page Density (full).....................: 98.03%
DBCC execution completed. If DBCC printed error messages,
contact your system administrator.
Page it
We are most familiar with the data row. The row size is set only by the definition of the table that holds it (e.g. A table of addresses require more data per row then a table of class names). In SQL Server, a table may define a row as storing as little as 4 bytes to as much as 8060.This limit is set by the size of the data page, which stores up to 8,192 bytes (8 KB). The remaining 132 bytes are used by SQL Server to track other information under the covers. Although SQL Server is designed around 8 KB pages, the smallest unit of data that SQL Server can allocate is 64 KB. This is called an extent.
To store the data in a sorted order, as in a phone book, SQL Server uses something called a clustered index. When a typical database is created, clustered indexes exist on nearly all tables. However, just because the data exists in sorted order within the page does not mean that it exists as such within an extent. The reason for this derives from situations in which there is no more room on a given page in which it can insert a row. SQL Server then removes approximately half the page and moves it to another page, which is called a Page Split (Page Splits will not occur with clustered indexes on IDENTITY based columns, but hotspotting may). In some cases, it may move that data to another extent altogether, possibly even allocating a new extent to do so. So, while we start off with names beginning with A and ending with H on one page, and names beginning with I and ending with Z on the next page, through usage, we may see that names A through C are now located on one page in one extent, D through E on another extent and S through Z back on the fifth page of the first extent, etc. It is because of the page split that there are times in which we may prefer to use tables with no clustered indexes at all. However, these tables are usually scratch tables which are highly volatile. In those situations, we desire the quicker write times at the cost of slower reads.
To store the data in a sorted order, as in a phone book, SQL Server uses something called a clustered index. When a typical database is created, clustered indexes exist on nearly all tables. However, just because the data exists in sorted order within the page does not mean that it exists as such within an extent. The reason for this derives from situations in which there is no more room on a given page in which it can insert a row. SQL Server then removes approximately half the page and moves it to another page, which is called a Page Split (Page Splits will not occur with clustered indexes on IDENTITY based columns, but hotspotting may). In some cases, it may move that data to another extent altogether, possibly even allocating a new extent to do so. So, while we start off with names beginning with A and ending with H on one page, and names beginning with I and ending with Z on the next page, through usage, we may see that names A through C are now located on one page in one extent, D through E on another extent and S through Z back on the fifth page of the first extent, etc. It is because of the page split that there are times in which we may prefer to use tables with no clustered indexes at all. However, these tables are usually scratch tables which are highly volatile. In those situations, we desire the quicker write times at the cost of slower reads.
The row count question
select rowcnt from sysindexes where id = object_id('tablename') and indid = 1 --assuming there exist a clustered index
select rowcnt from sysindexes where id = object_id('tablename') and indid = 0 --assuming table is a heap
Run following to fix errors with non-clustered indexes:
dbcc updateusage(0,'tablename') with count_rows
select rowcnt from sysindexes where id = object_id('tablename') and indid = 0 --assuming table is a heap
Run following to fix errors with non-clustered indexes:
dbcc updateusage(0,'tablename') with count_rows
Query plan?
A query plan details how the SQL Query Optimizer will run the query. The optimizer plans which portion of the query to execute first and which index to use. Depending on the way the tables are set up, the nature of the query, the indexes available, etc. SQL Server will determine the optimal technique - be it to scan through the table from start to finish, to use one or more specific indexes or various other ways.
SET SHOWPLAN_TEXT ON – TSQL, Include Actual Execution Plan - SSMS
The query plan is stored in the SQL Server memory’s Procedure Cache.
SET SHOWPLAN_TEXT ON – TSQL, Include Actual Execution Plan - SSMS
The query plan is stored in the SQL Server memory’s Procedure Cache.
Subscribe to:
Posts (Atom)