Showing posts with label SQL Server Best Practices. Show all posts
Showing posts with label SQL Server Best Practices. Show all posts

Friday, June 6, 2008

USERSTORE_TOKENPERM

On versions of SQL Server before 9.0.3171.0, a known issue can degrade query performance on 32-bit and 64-bit systems with 2 gigabytes (GB) or more of memory. When you execute queries under the context of a login that is not a member of the sysadmin fixed server role, you might encounter performance degradation symptoms that arise from a large and growing Security Token cache. These issues can include performance degradation of queries, high CPU usage for the SQL Server process, and a sharp increase in worker threads and SQL user connections. Systems that have less than 2 GB of memory should not experience these issues because normal memory usage requirements keep the Security Token cache from growing too large.

Symptoms

  1. A large number of users running queries on the SQL instance and intermittently you find that the duration of queries increases intermittently
  2. Most of the queries in the environment exhibit this pattern for random parameters and not any specific query/proc with any specific parameter
  3. DBCC MEMORYSTATUS output for the SQL instance shows that the memory usage for SQL is gradually increasing over a period of time
  4. High CPU during the problem period
  5. DBCC FREEPROCCACHE or DBCC FREESYSTEMCACHE fixes the issue temporarily

Related Articles

  • KB article 927396: Queries take a longer time to finish running when the size of the TokenAndPermUserStore cache grows in SQL Server 2005
  • KB article 933564: FIX: A gradual increase in memory consumption for the USERSTORE_TOKENPERM cache store occurs in SQL Server 2005
  • KB article 937745: FIX: You may receive error messages when you try to log in to an instance of SQL Server 2005 and SQL Server handles many concurrent connections
  • http://blogs.msdn.com/psssql/archive/2008/06/16/query-performance-issues-associated-with-a-large-sized-security-cache.aspx
  • Friday, May 30, 2008

    SQL Best Practices Analyzer - II

    I have already blogged about this in a previous post of mine (Best Practice Analyzer) but I was recently working on the SQL Server 2005 version of the tool and thought that this deserved a second mention.

    This tool has been enhanced a lot and provides a great deal more information than it's SQL 2000 counterpart. This creates a XML data output file in your %appdata%/Microsoft/SQL BPA folder. This output can be imported using the SQL BPA UI and then a set of reports can be generated to check the following:

  • Gathers configuration information from an instance of SQL Server.
  • Performs specific tests on the instance of SQL Server.
  • Proactively verifies that the configuration is set according to recommended best practices. Some high level checks are even performed on the Operating System level.
  • Reports all settings that differ from the default settings.
  • Reports recent changes in the instance of SQL Server.

     

    On a broader level, the tool verifies the above mentioned based on rules divided into the following categories:

    1. Security rules
    2. Database Engine rules
    3. Analysis Services rules
    4. Replication rules
    5. Integration Services rules

    For example, if you applied the initial release version of SQL Server 2005 SP2, existing SQL Server 2005 maintenance plans and SSIS packages that contain cleanup tasks might run those tasks at shorter intervals. The tool if it scans your SQL Server instance and finds out if you are on a build lower than the one mentioned in KB933508, then it would provide the recommendation to apply the fix.

    The SQL BPA UI can be used to run scans on remote machines also. So, there is no need to install the tool on the SQL Server box which you want to scan. You can also configure the type of scan you want the SQL BPA tool to perform on your server.

    Microsoft PSS also has the capability to include this tool as a part of the PSSDIAG collection that they send out to collect diagnostic data from the instance based on the need to collect BPA analytics data.

    For a more detailed information about the above mentioned points, you can always refer the SQL Server Best Practices Analyzer Help chm file.

  • Saturday, March 22, 2008

    Best Practice Analyzer

    I have seen a lot of people asking "Are we following best practices for our SQL Servers?". The Best Practice Analyzer cantry and guide you along a path which would lead to the right answer. A simple answer is not possible because of the following reasons:

    1. We are not conversant with your environment and setup
    2. We do not know what kind of business implementation this SQL Sever is
    3. We do not know what constraints are present which prevents some of the best practices from being followed
    4. We do not know which data/databases are critical/non-critical etc. and also do not know what kind of SLAs need to be met.

    Even then, an attempt is made using the Best Practice Analyzer to verify if common best practices are being implemented across your SQL Server. It creates a repository on the our server and stores the analysis for the server in the database which can be used at a later date.

    The SQL Server 2005 Best Practices Analyzer (BPA) gathers data from Microsoft Windows and SQL Server configuration settings. BPA uses a predefined list of SQL Server 2005 recommendations and best practices to determine if there are potential issues in the database environment.

    This tool is available at
    For SQL Server 2000
    http://www.microsoft.com/downloads/details.aspx?familyid=B352EB1F-D3CA-44EE-893E-9E07339C1F22&displaylang=en
    For SQL Server 2005
    http://www.microsoft.com/downloads/details.aspx?FamilyId=DA0531E4-E94C-4991-82FA-F0E3FBD05E63&displaylang=en

    Wednesday, October 24, 2007

    How to update statistics for large databases

    Statistics are something that the SQL Optimizer depends on to generate a plan. The more outdated your statistics are, greater are the chances that your query optimizer will land up with a sub-optimal plan.

    So what do you do when you have a database which is highly transactional in nature and is quite large in size. So, you might land up in a scenario where the database is online 24X7 and there is no downtime window where you can update your statistics with a FULLSCAN.

    Before we get into what my opinion is about updating statistics of a database is, lets make sure we understand what I mean by statistics being "up-to-date". Statistics being up-to-date is the sampling rate used while updating statistics was 100% or they were updated with a FULLSCAN. Statistics updated using AUTO UPDATE STATISTICS property of a database will not update statistics with a FULLSCAN contrary to popular belief. The sole reason for this being is that suppose a table has 1 GB of data and a query on the database initiated a AUTO UPDATE of a STAT on this database, then if the sampling was 100%, then your query duration would take an eternity.

    So, if you have a large database:
    1. Ensure that the AUTO UPDATE STATS is turned on for the database. This would provide for some relief to the database
    2. Identify which tables need to have their statistics updated with a fullscan. Only those would be required which have the maximum number of queries running on them
    3. Next identify a period when the database usage is low. This is the time when you can use to update the stats of the other tables which did not qualify the list in #2.
    4. Use a script to update statistics of the tables indentified step # 2 probably based on rowmodctr values (ROWMODCTR: Counts the total number of inserted, deleted, or updated rows since the last time statistics were updated for the table. In SQL Server 2005, this is not going to be always helpful [Ref: http://msdn2.microsoft.com/en-us/library/ms190283.aspx]. But in SQL 2000, this could be used as a deciding factor)

    Sample Script
    ============

    Let's say I had identified 4 tables in STEP 2:

    CREATE TABLE UPD_STATS_TBL (tblname varchar(10), dt_updated datetime, rowmodctr bigint)

    SELECT * FROM UPD_STATS_TBL
    tblname dt_updated rowmodctr
    TBL1 2007-10-24 21:13:46.123 20000
    TBL2 2007-10-23 21:13:46.123 400000
    TBL3 2007-10-22 21:13:46.123 508000
    TBL4 2007-10-24 20:13:46.123 87000

    **************************************************
    CREATE PROC UPD_STATS_DB
    AS
    DECLARE @tbl varchar(10)

    UPDATE upd_stats_tbl SET rowmodctr = (SELECT MAX(rowmodctr) from sys.sysindexes where id=OBJECT_ID(tblname))

    SELECT TOP 1 @tbl = tblname
    FROM UPD_STATS_TBL
    WHERE rowmodctr >
    ORDER BY dt_updated

    DECLARE @stmt varchar (100)

    SET @stmt = 'UPDATE STATISTICS'+SPACE(1)+@tbl+SPACE(1)+'WITH FULLSCAN'

    EXEC (@stmt)

    UPDATE upd_stats_tbl SET dt_updated = (SELECT GETDATE())
    WHERE tblname = @tbl

    **************************************************

    NOTE: You could refine this down to the table statistic if you wanted to.

    Missing Indexes in SQL Server 2005

    Indexes are essential in making sure that your queries have effecient query plans and for SELECTS, you don't end up doing searches on HEAPS.

    One of the biggest improvements in SQL Server 2005 is that it tracks all the transactions happening on the server and makes a list of indexes which could prove beneficial for those queries. Of course, one index might be beneficial for one query but detrimental to another. So, it is highly essential that we test the feasibility of implementing these indexes on a production environment before rolling out changes to our indexes.

    The missing indexes feature is on by default. No controls are provided to turn the feature on or off, or to reset any of the tables returned when the dynamic management objects are queried. When SQL Server is restarted, all of the missing index information is dropped. This feature can only be disabled if an instance of SQL Server is started by using the -x argument with the sqlservr command-prompt utility.

    So, the first thing I would do if a query or a set of queries are running slowly in SQL Server, I would query the DMVs related to these missing indexes and find out if there are an indexes related to the tables on which those slow running queries are executing. This feature becomes highly useful when the following conditions are true:
    1. NO CPU bottleneck
    2. NO Blocking on the server
    3. NO Disk bottleneck

    You can view a list of all the missing indexes using Performance Dashboard which can be used with SQL Server 2005 Service Pack 2 and above.

    Relate Links for Missing Indexes
    About Missing Indexes
    http://msdn2.microsoft.com/en-us/library/ms345524.aspx
    Finding Missing Indexes
    http://msdn2.microsoft.com/en-us/library/ms345417.aspx
    Limitations of this feature
    http://msdn2.microsoft.com/en-us/library/ms345485.aspx

    Friday, October 12, 2007

    SQL Server 2005 Upgrade

    Upgrading from SQL Server 2000 to SQL Server 2005 is always a daunting task if you have had a chance to contemplate as to what needs to be done before and after the upgrade process. On the other hand, if you had a chance to plan out everything before hand, then it is very unlikely that you would land yourself in a soup unless and until the Gods choose to be very unkind towards you on that fateful day. :)

    So, first let us understand what are the two procedures of upgrading from SQL Server 2000 to SQL Server 2005.

    1. IN PLACE UPGRADE
    2. SIDE BY SIDE UPGRADE

    So, before I go ahead and explain these two upgrade procedures, let us dwell on the pre-requisites for upgrading to SQL Server 2005.

    1. Testing: Make sure all your applications are thoroughly tested and function as expected on a SQL Server 2005 environment before deciding to take the final step
    2. Fall-back plan: This is what I call "insurance". It's a hassle but when a problem does happen, this is what takes care in helping you out of the problem. I believe it is better to be safe than sorry.
    3. Backups: This should have been included in Point 2 but this is something of utmost importance, so I thought I would re-iterate this again. We need to have backups of all the user and system (YES! we need them.) databases in case we need to use our fall-back plan.
    4. Upgrade Advisor: Run the upgrade advisor on your existing SQL Server 2000 installation and find out if there are any REDFLAGS in upgrading to SQL Server 2005 based on your current configuration. (Please check the following link for more details: https://partner.microsoft.com/40001607)

    In-place upgrade process
    The upgrade process which refers to upgrading all the existing installed components of SQL Server 2000 to SQL Server 2005 on the same server.

    Side-by-side upgrade process
    The upgrade process which refers to leaving your existing SQL Server installation intact and installing a fresh SQL Server 2005 instance on the same server or a different server and then migrating over all your databases. Once, all the components (Databases, Plans, DTS Packages etc.) have been migrated the SQL 2000 installation can then be phased out.

    Both these upgrade processes have their PROs and CONs which are clearly documented in the TechNet Article mentioned below.

    Upgrade Handbook for SQL Server 2005
    http://www.microsoft.com/technet/prodtechnol/sql/2005/sqlupgrd.mspx
    Upgrading to SQL Server 2005
    http://www.microsoft.com/sql/solutions/upgrade/default.mspx
    Technet Article on Upgrading SQL Server 2000 to SQL Server 2005
    http://www.microsoft.com/downloads/details.aspx?FamilyID=3d5e96d9-0074-46c4-bd4f-c3eb2abf4b66&DisplayLang=en

    So, what do we need to take care of when upgrading to SQL Server 2005 from SQL Server 2000?

    1. Replication: If you do have replication configured (subscriber/publisher/distributor), you need to find out if your replication topology is compatible and will continue to function smoothly if the current server is upgraded?
    2. DTS Packages: These need to migrated to SQL Server 2005 using the Migration Wizard. Related Article: http://msdn2.microsoft.com/en-us/library/ms143501.aspx
    3. Maintenance Plans: Again they are different from their SQL Server 2000 counterparts because in SQL 2005, we use SSIS in the background.
    4. Logins: In case of an side-by-side upgrade, then these need to be migrated too.

    These are a few of prime areas of concern that come to my mind. A whole bunch of other considerations are mentioned in the above mentioned Technet Whitepaper. Please do read through that if you are planning to upgrade to SQL Server 2005.

    Wednesday, October 3, 2007

    Backup Strategy

    Backup strategy needs to be designed in such a manner that it causes minimum amount of downtime in case during a disaster recovery scenario if backups need to be restored. The backup strategy depends on the following:

    1. Size of the database – This would determine how often a FULL BACKUP can be taken
    2. Recovery Model – This would determine if transaction log/differential backups are possible
    3. The importance of the database – This would determined how often transaction log backups need to be takenIf the database is in “simple” recovery model, then the only option that we would have is to take full backups.

    If the database is in FULL/BULK-LOGGED recovery models, then we have the option of taking transaction log/differential backups.

    Now the next question is how often to take a transaction log backup. Depending of the importance of the database, transaction log backups can be taken every 10-15 minutes or even every hour. This needs to be determined at your end. Furthermore, if the transaction log backups are being taken very frequently and a full backup is taken once a week, then it is advisable to take differential backups during the middle of the week. This would ensure that the process of restore becomes less cumbersome as after the full backup, then differential backup can be applied followed by the transactional log backups.

    In case of full/bulk-logged recovery models, the following backup strategy would be ideal:

    1. Full backup

    a. Differential backup(s)

    i. Transaction log backup(s)

    b. Differential backup(s)

    i. Transaction log backup(s)

    2. Full backup (and repeat the above cycle)


    Furthermore, for creating sound fail-over strategies for disaster recovery scenarios, the following can be considered:
    1. Log shipping
    2. Database Mirroring (For SQL 2005 SP1 and above)
    3. Replication

    Also, it is considered a good practice to restore a backup on a test server and a CHECKDB run on the restored database to make sure that the backup is in good shape. This becomes of utmost importance when it is not possible to run a CHECKDB before taking a backup. In SQL Server 2005, you have the option to perform a piece meal restore which would allow you to restore up to the page level in case you have database corruption.

    The following articles could be helpful:
    Overview of Restore and Recovery in SQL Server
    http://msdn2.microsoft.com/en-us/library/ms191253.aspx
    SQL Server 2005 provides the option of performing an online restore which is available for SQL Server 2005.

    Please refer the following for more information:
    Performing Online Restores
    http://msdn2.microsoft.com/en-us/library/ms188671.aspx
    Storage Top 10 Best Practices
    http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/storage-top-10.mspx
    Using Recovery Models
    http://msdn2.microsoft.com/en-us/library/aa173678(SQL.80).aspx

    Statistics Update

    This is an important task in terms of database maintenance. This ensures the statistics are up-to-date which in turn would ensure that the query optimizer doesn’t land up with sub-optimal plans. The two ways to monitor for the need for an update on statistics are:

    1. STATS_DATE function (http://msdn2.microsoft.com/en-us/library/ms190330.aspx) 2. rowmodctr value in the sysindexes (For SQL 2000) and sys.sysindexes (For SQL 2005) output

    The STATS_DATE function would give you the date when the statistics were updated last. The rowmodctr value would tell you how many changes have taken place in terms of update, inserts and deletes in the data of the column the index is associated with.

    The frequency of statistics update depends on the following:
    1. Do BULK operations happen on the database tables in question?
    2. Is there an off-peak period where a statistics update with full scan can be done?
    3. How often is the data modified in the database tables in question?

    Statistics update can be a resource intensive operation depending on the size of the table. If the data in the tables in question change very rarely, then a statistics update with a full scan can be done during a maintenance window. Statistics update is always an ONLINE operation and doesn’t cause the database to be in an OFFLINE mode.
    If there are BULK operations happening in a table, then statistics have a tendency to getting skewed after the BULK operation. The best option is do perform a statistics update on this table if this tables is to be used by an application after the bulk operation.
    If the database is updated very frequently and the database is very large in size, then it needs to be determined which tables are most frequently updated. Based on this, a statistics updated can be performed for only those tables and a statistics update can be done for the entire database with a lower sampling rate like 20-30% depending on what is suitable. This can be determined by comparing historical data and finding out what kind of sampling rate is suitable for your needs.
    Another option is to enable AUTO UPDATE STATISTICS option for the database. But it needs to be monitored whether this is a boon or a bane. AUTO UPDATE STATISTICS can be good when the statistics are relatively updated and it makes sure that the statistics don’t fall too out of place. This feature has a downside when the statistics become out-dated too frequently, then you would have AUTO UPDATE STATISTICS being fired every time and this would cause all cached plans associated with the rows whose statistics have been updated to be recompiled. This can cause a serious bottleneck if there are too many auto update statistics events fired in short time span.

    The following methods can be used to update the statistics:
    1. UPDATE STATISTICS WITH FULLSCAN (or a lower sampling rate) Please refer the following article for further details: http://msdn2.microsoft.com/en-us/library/aa260645(SQL.80).aspx
    2. sp_updatestats (http://msdn2.microsoft.com/en-us/library/ms173804.aspx)
    3. A maintenance plan or SQL Agent job to update the statistics

    The following script for SQL Server 2005 would be helpful in determining how badly affected the statistics are for the index associated with it. The rowmodctr counts the total number of inserted, deleted, or updated rows since the last time statistics were updated for the table.



    A DBCC DBREINDEX would update the statistics associated with those indexes. But this would not update the AUTO CREATED STATISTICS. The DBCC SHOW_STATISTICS (http://msdn2.microsoft.com/en-us/library/aa258821(SQL.80).aspx) command could also help you to determine the statistics condition for the particular index. The “Row Sampled” and “Rows” if equal would indicate that the sampling is currently 100%.


    Statistics for INDEX 'pk_customers'.

    Updated Rows Rows Sampled Steps Density Average key length -------------------- -------------------- -------------------- ------ ------------------------ ------------------------
    Jun 23 2007 5:03PM 91 91 91 1.0989011E-2 10.0



    The following articles could be helpful:

    UPDATE STATISTICS
    http://msdn2.microsoft.com/en-us/library/aa260645(SQL.80).aspx
    Statistics used by Query Optimizer in SQL Server 2005
    http://www.microsoft.com/technet/prodtechnol/sql/2005/qrystats.mspx

    Re-organize data and index pages

    There are a few ways that this can be achieved:

    1. Shrinking the database files (data file or transaction log file)

    2. DBCC DBREINDEX (Similar to dropping and re-creating the indexes)

    3. DBBC INDEXDEFRAG (De-fragmenting the indexed pages to remove logical scan fragmentation)

    Note: It needs to be kept in mind that DBREINDEX is a fully-logged operation and can cause the transaction log to grow by large amounts when the database size is considerably large. So there have been situations when the transaction log has grown out of proportion and filled up the entire disk. If the T-log does grow out of proportion and you do choose to truncate/shrink the file, then please do so after verifying the points below:

    1. Transactional replication is not configured for the database

    2. Log shipping is not configured for the database

    3. Database mirroring is not configured for the database (For SQL 2005 SP1 and above)

    4. Any other operations are not being performed which need transactional log consistency in terms of LSN chains

    Online re-indexing is a feature which is available in SQL Server 2005 Enterprise Edition only. Please note that rebuilding the indexes would cause the statistics associated with those indexes to also be updated. This however would not update the AUTO CREATED statistics.

    The following articles could be useful:

    SET OPTION considerations when running DBCC with indexes on computed columns

    http://support.microsoft.com/kb/301292/

    DBCC DBREINDEX

    http://msdn2.microsoft.com/en-us/library/ms181671.aspx

    The DBCC SHOWCONTIG output (http://msdn2.microsoft.com/en-us/library/aa258803(SQL.80).aspx) for SQL Server 2000 and 2005 will help you find out the current status of fragmentation for the database. A sample output would look like this:

    DBCC SHOWCONTIG scanning 'Customers' table...

    Table: 'Customers' (2073058421); index ID: 1, database ID: 6

    TABLE level scan performed.

    - Pages Scanned................................: 3

    - Extents Scanned..............................: 2

    - Extent Switches..............................: 1

    - Avg. Pages per Extent........................: 1.5

    - Scan Density [Best Count:Actual Count].......: 50.00% [1:2]

    - Logical Scan Fragmentation ..................: 0.00%

    - Extent Scan Fragmentation ...................: 50.00%

    - Avg. Bytes Free per Page.....................: 246.7

    - Avg. Page Density (full).....................: 96.95%

    The logical scan fragmentation should ideally be below 20% but anything above 40% would mean an INDEXDEFRAG or DBREINDEX is required. The script which is from the same MSDN article can help you run an INDEXDEFRAG or DBREINDEX based on the logical scan fragmentation count.

    A sample script for the same can be found under the topic of "DBCC SHOWCONTIG" in SQL Server Books Online (2000 and 2005)

    In SQL Server 2005, the following features may be helpful to you while using the ALTER INDEX command:

    REBUILD [ WITH ( [ ,... n]) ]

    Specifies the index will be rebuilt using the same columns, index type, uniqueness attribute, and sort order. This clause is equivalent to DBCC DBREINDEX. REBUILD enables a disabled index. Rebuilding a clustered index does not rebuild associated nonclustered indexes unless the keyword ALL is specified. If index options are not specified, the existing index option values stored in sys.indexes are applied. For any index option whose value is not stored in sys.indexes, the default indicated in the argument definition of the option applies.

    The options ONLINE and IGNORE_DUP_KEY are not valid when you rebuild an XML index.

    If ALL is specified and the underlying table is a heap, the rebuild operation has no affect on the table. Any nonclustered indexes associated with the table are rebuilt.

    The rebuild operation can be minimally logged if the database recovery model is set to either bulk-logged or simple.

    WITH ( LOB_COMPACTION = { ON OFF } )

    Specifies that all pages that contain large object (LOB) data are compacted. The LOB data types are image, text, ntext, varchar(max), nvarchar(max), varbinary(max), and xml. Compacting this data can improve disk space use. The default is ON.

    ON

    All pages that contain large object data are compacted.Reorganizing a specified clustered index compacts all LOB columns that are contained in the clustered index. Reorganizing a nonclustered index compacts all LOB columns that are nonkey (included) columns in the index. For more information, see Creating Indexes with Included Columns. When ALL is specified, all indexes that are associated with the specified table or view are reorganized, and all LOB columns that are associated with the clustered index, underlying table, or nonclustered index with included columns are compacted. OFF Pages that contain large object data are not compacted.

    OFF

    has no affect on a heap.The LOB_COMPACTION clause is ignored if LOB columns are not present.

    REORGANIZE

    Specifies the index leaf level will be reorganized. This clause is equivalent to DBCC INDEXDEFRAG. ALTER INDEX REORGANIZE statement is always performed online. This means long-term blocking table locks are not held and queries or updates to the underlying table can continue during the ALTER INDEX REORGANIZE transaction. REORGANIZE cannot be specified for a disabled index or an index with ALLOW_PAGE_LOCKS set to OFF.

    Furthermore, the dynamic management view sys.dm_db_index_physical_stats (http://msdn2.microsoft.com/en-us/library/ms188917.aspx) would help you get statistical information pertaining to indexes on SQL Server 2005. The columns mentioned below in this DMV output could be helpful in analyzing the need for index reorganization.

    avg_fragmentation_in_percent: Logical fragmentation for indexes, or extent fragmentation for heaps in the IN_ROW_DATA allocation unit. The value is measured as a percentage and takes into account multiple files. For definitions of logical and extent fragmentation, see Remarks. 0 for LOB_DATA and ROW_OVERFLOW_DATA allocation units.NULL for heaps when mode = SAMPLED.

    fragment_count: Number of fragments in the leaf level of an IN_ROW_DATA allocation unit. For more information about fragments, see Remarks.NULL for nonleaf levels of an index, and LOB_DATA or ROW_OVERFLOW_DATA allocation units. NULL for heaps when mode = SAMPLED.

    avg_fragment_size_in_pages: Average number of pages in one fragment in the leaf level of an IN_ROW_DATA allocation unit. NULL for nonleaf levels of an index, and LOB_DATA or ROW_OVERFLOW_DATA allocation units. NULL for heaps when mode = SAMPLED.

    The following article could be helpful:Microsoft SQL Server 2000 Index Defragmentation Best Practices

    http://www.microsoft.com/technet/prodtechnol/sql/2000/maintain/ss2kidbp.mspx

    Database Maintenance Plans

    Database Maintenance Plans for SQL Server 2000

    Database Maintenance Plans offer the following features in SQL Server 2000:

    1. Backing up databases
    2. Reorganization of indexes and data pages
    3. Statistics Update
    4. Shrinking the database
    5. Database integrity checks

    The above tasks of the maintenance plans would have associated with respective SQL Agent jobs and also these could be scheduled to suit your needs. Furthermore, these jobs could be created manually also without the help of maintenance plans.

    Database Maintenance Plans for SQL Server 2005
    In addition to the above mentioned features, SQL Server 2005 Enterprise Edition provides the option of rebuilding the indexes as an online operation. This makes it possible for the indexes to remain online while a rebuild index task is being performed on the database.


    ONLINE = { ON OFF }
    Specifies whether underlying tables and associated indexes are available for queries and data modification during the index operation. The default is OFF.
    Note: Online index operations are available only in SQL Server 2005 Enterprise Edition.

    ON
    Long-term table locks are not held for the duration of the index operation. During the main phase of the index operation, only an Intent Share (IS) lock is held on the source table. This enables queries or updates to the underlying table and indexes to continue. At the start of the operation, a Shared (S) lock is held on the source object for a very short amount of time. At the end of the operation, for a short time, an S (Shared) lock is acquired on the source if a nonclustered index is being created; or an SCH-M (Schema Modification) lock is acquired when a clustered index is created or dropped online and when a clustered or nonclustered index is being rebuilt. ONLINE cannot be set to ON when an index is being created on a local temporary table.

    OFF
    Table locks are applied for the duration of the index operation. An offline index operation that creates, rebuilds, or drops a clustered index, or rebuilds or drops a nonclustered index, acquires a Schema modification (Sch-M) lock on the table. This prevents all user access to the underlying table for the duration of the operation. An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. This prevents updates to the underlying table but allows read operations, such as SELECT statements.


    The frequency of these tasks and which tasks are needed need to be performed need to be decided on the following factors:
    1. Importance of the database in question
    2. Size of the database
    3. Maintenance window frequency
    4. Load on the server
    5. Whether it is an OLTP or OLAP database or both
    6. The kind of transactions that take place on the database (Point 5 and 6 would decide how often index reorganization/index rebuild/statistics updates are required and whether a shrink database/file is required)

    Monday, September 3, 2007

    Database Integrity Checks

    Database Integrity Checks Database integrity checks are recommended to ensure that the database consistency is intact and if there is a problem with consistency, then it is reported to the appropriate team(s) so that necessary action can be taken to rectify it. This can be done with the help of Database Maintenance Plans. In the event that a CHECKDB on a database fails, then it needs to be reported by Email(using xp_sendmail or SQL Agent Mail or Database Mail for SQL Server 2005) or events fired in the Operating System Event Logs (if these are monitored regularly) with the help of Operators which can be configured for SQL Server Agent. The xp_sendmail feature is not available for SQL 2005 64-bit versions.

    The frequency of these checks largely depends on the following factors:
    1. Importance of the database
    2. How often data changes in the database (If a database integrity check fails for a database where data is not modified, then it would be advisable to restore the last known good backup rather than trying to repair the consistency database)
    3. The size of the database
    4. In the event of consistency checks failing, it needs to be determined which is the most feasible option:
    a. Restore the last known good backups in accordance with the recovery model for that database to allow for a minimum amount of data loss
    b. Or try and repair the database and falling back on Option (a) only if this fails In case a repair option is suggested in the CHECKDB output, it is important to note that a REPAIR_ALLOW_DATA_LOSS be never performed on the database without understanding its full consequences and consulting Microsoft PSS. In the event, that this route needs to be taken, it is always recommended to fall back on the last known good backups if possible. The REPAIR_FAST and REPAIR_REBUILD repair options can be performed without having any data loss. Please note that these are time consuming operations and in the event of database inconsistency it is not possible for us to predict how long these tasks would run for. Also, the time taken for CHECKDB on a database cannot be predicted. An educated guess can be made to how long it would take by referring to the last durations of the CHECKDB operations on that particular database. For the above mentioned repair options, please refer the following article: http://msdn2.microsoft.com/en-us/library/aa258278(SQL.80).aspx

    REPAIR_ALLOW_DATA_LOSS
    Performs all repairs done by REPAIR_REBUILD and includes allocation and deallocation of rows and pages for correcting allocation errors, structural row or page errors, and deletion of corrupted text objects. These repairs can result in some data loss. The repair may be done under a user transaction to allow the user to roll back the changes made. If repairs are rolled back, the database will still contain errors and should be restored from a backup. If a repair for an error has been skipped due to the provided repair level, any repairs that depend on the repair are also skipped. After repairs are completed, back up the database.

    REPAIR_FAST
    Performs minor, nontime-consuming repair actions such as repairing extra keys in nonclustered indexes. These repairs can be done quickly and without risk of data loss.

    REPAIR_REBUILD
    Performs all repairs done by REPAIR_FAST and includes time-consuming repairs such as rebuilding indexes. These repairs can be done without risk of data loss. In case of SQL Server 2005, you have the option of checking the suspect_pages in the MSDB database to find out the affected pages.

    Please refer the following articles for more detailed information:
    Suspect_pages table (SQL 2005)
    http://msdn2.microsoft.com/en-us/library/ms174425.aspx
    Understanding and managing the suspect_pages table
    http://msdn2.microsoft.com/en-us/library/ms191301.aspx
    Designing a Backup and Restore Strategy
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/adminsql/ad_bkprst_63eh.asp

    In the event, that only a few pages have a problem, then for SQL Server 2005 a page level restore can be performed. Online page restore operation is a feature available in SQL Server 2005 Enterprise Edition but all other Editions of SQL Server 2005 support offline page level restores. The page level restores are done using the NORECOVERY option for that database. Then a backup of the current transaction log is taken and applied to the database with the RECOVERY option. This feature is applicable to databases in FULL or BULK-LOGGED recovery models.

    For performing page level restores, please refer the following article: http://msdn2.microsoft.com/en-us/library/ms175168.aspx

    It is highly important that a disaster recovery plan is in place to ensure the following:
    · A plan to acquire hardware in the event of hardware failure
    · A communication plan.
    · A list of people to be contacted in the event of a disaster.
    · Instructions for contacting the people involved in the response to the disaster.
    · Information on who owns the administration of the plan.
    · A checklist of required tasks for each recovery scenario. To help you review how disaster recovery progressed, initial each task as it is completed, and indicate the time of completion on the checklist.

    In conclusion, if the database is of a considerably large size, then an integrity check needs to be scheduled during a window when the load on the server is at a minimum. The definition of minimum here refers to a load which is lesser than the normal workload on the server. If the database sizes are quite small, then daily integrity checks on the database would be the order of the day.

    It is recommended that DBCC CHECKDB be run during hours when the load is light on the server. If DBCC CHECKDB is run during heavy peak usage time, expect a performance hit on the transaction throughput as well as DBCC CHECKDB completion time.

    Recommendations for Good DBCC Performance
    · Run CHECKDB when the system usage is low.
    · Be sure that you are not performing other disk I/O operations, such as disk backups.
    · Place tempdb on a separate disk system or a fast disk subsystem.
    · Allow enough room for tempdb to expand on the drive. Use DBCC with ESTIMATE ONLY to estimate how much space will be needed for tempdb.
    · Avoid running CPU-intensive queries or batch jobs.
    · Reduce active transactions while a DBCC command is running.
    · Use the NO_INFOMSGS option to reduce processing and tempdb usage significantly.