Archive for November, 2012

Cut the stress, enjoy your life November 30th, 2012

Vinod Kumar

After a long wait and multiple requests from my friends I thought of writing this topic. In these times of high expectations, we see people over commit and ultimately get into stressed mode. Let me tell you some of the ways you can control your stress levels and have fun in your life.

If you are an IT Professional, I have a big request to all. Never let your personal life’s stress affect your professional work. Most importantly, don’t let the stress of your professional world shadow the beautiful evening your family is waiting for. So controlling stress is an essential part I wish everyone masters in their life slowly but surely. Here are my top 7 ways to de-stress yourself from the distress. I surely looking to learn some tips from you too, so please do drop in your comments.

In most cases stress is the root cause of death; illnesses are just the wrap up – Yordan Yordanov

1. Don’t take it to heart

Most of the stress is caused by us taking things too personal. Either we get irritated over what others do to us or we get agitated over why we didn’t get that opportunity others have got. Sometimes we are crossed by our very own actions, so don’t think hard – go with the flow and enjoy what you do.

2. Be reasonable

It is sometimes worth to change your expectations and be more reasonable in what you can expect from others. If you expect *everyone* to be always nice to you, someday you will get disappointed. Understand, you are making a conscious choice of getting disappointed when you expect others to do something for you even when you know the likelihood of this is highly unlikely.

Stress: The confusion created when one’s mind overrides the body’s basic desire to choke the living daylights out of some jerk who desperately deserves it

3. Laugh out to your heart’s desire

Humor is the opposite of stress and you will always find that humor opens your mind. When you are stressed you are emotionally connected with the problem and you are holding it tight that it blinds you of any solution. When you laugh out the situation in hand, you are solving the problem with new open mind.

4. What you want is different from what you need

A lot of times we get stressed by comparing ourselves with someone who we really don’t want to be like. That want is one of the major reasons for getting our stress levels going high. Know what your responsibilities are, they will meet your own needs provided you do the right things. Being ambitious and not working towards it is the problem. This inner liberation can be such a revelation that it open’s the potential inside you. Don’t look for compliments, look for explanations.

Give your stress wings and let it fly away – Terri Guillemets

5. Assumptions are mother of all downfall

One thing I have learnt in MTC (@work) is not to assume anything. What BI means to me is totally different to what every customer thinks. In the same way, don’t assume to what others think of you or you think of them. Clarify, open up, speak up and don’t leave anything to chances. It is better to know you are wrong upfront rather than doing something based on that assumptions while permanently damaging the situation and getting heart burns for the efforts we put in.

6. Check your emotions in place

One of the things I tell my dear ones is – face your feelings. Running away from the problem never solves it. The problem most of us face is, we never open up to face our emotions even when we get home. Suppressing the feelings is like a time bomb ready to explode in the most inappropriate time. Know your steam valve to vent out the emotions from time to time so that you don’t have to take time off just to recover from something you never intended to do. This can be stress balls, punching bags, watching a movie – whatever works, do it :).

Releasing the pressure, it’s good for the teapot and the water. Try it sometime – Jeb Dickerson

7. Look within

We don’t control what others do and if we keep our cool, we exactly know how to avoid stressful conversations. It takes two to start any argument, if you are not the one who started it and if you refuse to end it, I think you are complicating the situation and getting stressed unnecessarily.

Sometimes the most important thing in a whole day is the rest we take between two deep breaths – Etty Hillesum

Continue reading...


 

SQL Server: Basics of Database Snapshot November 26th, 2012

Vinod Kumar

In our day-today life we have needs for photocopies. Now if we take that concept and mimic the same inside SQL Server it is called as Snapshots. Inside SQL Server the concept of snapshots were there with replication for a while, but from SQL Server 2005 a new feature called as Database Snapshot were introduced.

The feature usage of Database Snapshots have been minimal in organizations, but there are some unique ways people use snapshots and a lot don’t know how this feature works too. This feature is different from SAN based snapshots and not to be confused. As we are in the topic, understanding that snapshots can be implemented as a  software solution or hardware vendor approach. In this blog post we will look at the feature within SQL Server called as database snapshots.

  1. Database snapshot is a process where DBAs can create a point-in-time read-only copy of any database. They can create multiple snapshots of the same database at different points in time.
  2. Space needed for each snapshot is typically much less because snapshot only stores pages that have changed.
  3. Database snapshots allows you to do the following:
    1. Turn a database mirror into a reporting server (you cannot read from a mirror but you can create a read only snapshot of the mirror and read from that)
    2. Generate reports without blocking or being blocked by production operations.
    3. Protect against administrative and user errors.
    4. This is yet another way to protect against database application upgrades and functioning like a backup before the process
  4. Each file in a snapshot is created as a sparse file (feature of NTFS). The database recovery models don’t have an impact on creating snapshots.
  5. Use the DMV sys.databases to check the source databases for snapshots.
  6. Write: Snapshot files contain only data that has changed from source, and for every file, SQL creates a bitmap that is kept in cache with a bit for each page of the file indicating whether the page has been copied to the snapshot. Every time a page in the source is updated, SQL Server checks the bitmap for the file to see if the page has already been copied, if not, copies it. This operation is called copy-on-write or COW process.
  7. Read: When a process reads from a snapshot, if first accesses the bitmap to see whether the page it wants is in the snapshot file or the source. When it reads from a snapshot database, no locks are taken regardless of what isolation level it’s in (true for reads from file and from source database).
  8. When SQL Server is shut down or the database is closed, the bitmaps are lost and need to re-created at startup. It checks whether each page of the database is in the sparse file as it is accessed and it records the information for future use using the memory maps.
  9. Allocations to the sparse files are made in units called regions, each region is 64KB. When a region is allocated, all the pages are zeroed except for the page that has changed leaving room for 7 more pages. A new region isn’t allocated till all 8 pages are used.
  10. The snapshot operated in pages as discussed above to fill up the regions.
  11. Keep monitoring your IO overheads that come because of COW for the snapshot databases.
  12. Also because of sparse file configuration, keep an eye on the drive space where the snapshots are present.
  13. If a snapshot exists for a source database, the source database cannot be dropped, detached or restored.
  14. You can replace a source database with one of the snapshots thereby reverting the source database to the state when the snapshot was taken using the RESTORE command.
  15. The restore cannot be performed for offline databases and corrupted databases.
  16. Snapshots can also be used to recover deleted tables from the source database.
  17. Snapshots cannot be created for the model, master, resourcedb or tempdb database
  18. Database snapshots have no relation to the concepts of snapshot backups, snapshot isolation of transactions or snapshot replication.
  19. We cannot backup, restore, attach or detach an snapshot database.
  20. FILESTREAM datatype is not supported by database snapshots.
  21. With the introduction of ALWAYSON technologies in SQL Server 2012, snapshots cannot be created on the databases part of availability groups.
  22. NOTE: Please DONOT use Database snapshots as a replacement for backups. The usual backup strategies must be done and in place.

Thanks for reading this far. Feel free to drop a comment to tell us if you have used the database snapshot feature in your production environments.

Continue reading...


 

SQL Server: Database Page Basics November 22nd, 2012

Vinod Kumar

As you have been reading multiple posts around the database fundamentals topic in the past few weeks. Here is yet another post that will discuss around the basics of SQL Server Database Pages concept. I have seen there are many junior DBA’s who come from other platforms and ask what is a page, why is it restrictive, Is there a way to configure, are there optimizations I need to be aware etc. For most part the answer to this question is – there is hardly anything we can configure as parameters, but there is a reason why one must learn why SQL Server uses these defaults, what are the nuances we need to be aware and how can we understand the inner working. In this post, we just take a look at the basics of what constitute a database page and what are the various functions of each of these page types. This is not exhaustive, but still the learning can never stop right :).

  1. Logical pages are 8KB in size by design and default.
  2. The pages are numbered sequentially from 0 to N in each file, while the size of the file decides the number of pages that it contains.
  3. SQL Server can identify any page using the database-id, file-id and page-number combination. Many times there are error messages with this nomenclature for reference.
  4. With all math done, it means SQL Server has 128 pages per MB.
  5. When new space is allocated to a file because of expanding file, the first page of the newly created space is page# is N + 1.
  6. Though shrinking removes pages, SQL Server also ensures page numbers within a file are always contiguous.

SPACE ALLOCATIONS

  1. Space in a database file is managed in units called extents.
  2. Extent is made up of 8 logically contiguous pages therefore having a capacity of 64KB.
  3. 96 byte of each page is allocated for header information such as what type of page, amount of free space on page, object owing it etc.
  4. Post the header information is the data rows placed serially.
  5. Bottom of the page contains a row offset – there is one entry for every row inside that page and its offset from the start of the page.
  6. Row Offsets are in reverse sequence from the sequence of the rows.
  7. Maximum amount of data that one can store in a single row is 8060 bytes. Whenever we are able to fit the rows in this limit – it is called In-Row Data.
    1. From SQL 2008, the page restriction has been relaxed with an concept called as Row-Overflow Data. Read more from MSDN.
  8. SQL Server doesn’t allocate entire extents to tables which have small amounts of data.
  9. Extents are of 2 Types:
    1. Uniform extents: As name suggests it is owned by a single object; all eight pages in the extent can be used only by this single object
    2. Mixed extents: These are shared between objects. Up to eight objects can share an extent (a.k.a each object using a single page)
  10. Whenever a new table or index needs allocation it is given a mixed extents; when the table or index grows to eight pages, future allocations can use uniform extents. Between versions of SQL Server the # of pages post which uniform extents are given may vary.
  11. If a table or index needs more space and is still less than 8 pages total, SQL Server must find a mixed extent with space available, else if it is 8 pages or larger, uniform extents are located.
  12. When there is no mixed extents with free space, a new extent marked as mixed extent is allocated and SGAM updated accordingly.
  13. Basic Page Layouts:
    1. Page 0 is the File Header
    2. Page 1 is the Page Free Space (PFS)
    3. Page 2 is GAM
    4. Page 3 is SGAM
    5. Page 6 is Differential Changed Map (DCM)
    6. Page 7 is Bulk Changed Map (BCM)
  14. 2 special types of pages to record which extents have been allocated and what type it is being use for:
    1. Global Allocation Map (GAM) pages (always on page 2)

      1. These pages record which extents have been allocated for any type of use.
      2. GAM has a bit to indicate value 0 means in use and 1 means free extent.
      3. After header and other overhead are accounted, there are 8000 bytes or 64000 bits to cover 64000 extents.
      4. Each GAM page covers 4 GB of data and a GAM page exists in a file for every 4 GB of file size.
    2. Shared Global Allocation Map (SGAM) pages (always on page 3)
      1. Record which extents are currently used as mixed events and have at least one unused page.
      2. Similar to GAM, it covers 64000 extents every 4GB of data.
      3. Has a bit for each extent in the interval it covers: 1 if the extent is being used a mixed extent and has free pages, 0 if the extent isn’t being used a mixed extent or it’s a mixed extent with no free pages

Index Allocation Maps (IAM)

  1. Any structure of data or index needs an IAM page.
  2. IAM pages keep track of the extents in a 4 GB section of a database file.
  3. An allocation unit is a set of pages belonging to a single partition in a table or index. The pages of can be of three storage types:
    1. Pages with regular in-row data
    2. Pages with Large Object (LOB) data
    3. Pages with row-overflow data
  4. IAM page contains a 96 byte page header, followed by IAM header which contains 8 page-pointer slots.
  5. IAM pages contain a set of 8 bits that map a range of extents onto a file. The IAM header has the address of the first extent in the range mapped by the IAM.
  6. A bit in the IAM bitmap represents an extent in the range: 1 means extent is allocated to the object owning the IAM, 0 means the extent isn’t allocated to the object owning the IAM.
  7. IAMs are allocated as needed for each object. Each of the IAM covers a possible range of 512,000 pages.

Misc. Notes

  1. PFS (page 1) – keeps track of how each particular page in a file is used.
  2. PFS also tracks if the page is empty, 1 to 50 percent full, 51 to 80 percent full, 81 to 95 percent full or 96 to 100 percent full.
  3. There is a PFS page approximately 8,000 pages in size after the first PFS page.
  4. Differential Changed Map (DCM page 6) – keeps track of which extents in a file have been modified since the last full database backup.
  5. Bulk Changed Map (BCM page 7)- is used when a page in a file is in a minimally or bulk-logged operation.
  6. Like the GAM and SGAM pages, DCM and BCM pages have 1 bit for each extent in the section of the file they represent.
  7. There is a GAM page 64,000 extents after the first GAM page on page 2 and another SGAM page 64,000 extents after the first SGAM page on page 3.
  8. Log files donot have the concepts of pages, they are a series of log entries written sequentially.
  9. In the previous versions the text, ntext and image data are stored in separate pages and are not inside the Data pages.

I think I have touched most parts of how database pages exist inside SQL Server. Though there are even more subtle nuances on the page functioning, we will keep it outside of this post for later. Please refer to MSDN BOL for more information on the page architectures.

Continue reading...


 

SQL Server: Database Basics November 19th, 2012

Vinod Kumar

Database learning can never stop. Based on the previous posts on the basics I saw few comments asking to cover some of the basics in a one liner mode. In this blog post, we will talk about the database fundamentals of system DB’s, what are the DB files and what are the filegroups. I get an opportunity to talk to a lot of developers who come from the compete platform and are often asking these fundamental and basic questions. I am sure this blog post will help them understand these fundamentals.

System Databases

  1. Master: composed of system tables that keep track of server installation as a whole and all other databases that are eventually created. Master DB has system catalogs that keep info about disk space, file allocations and usage, configuration settings, endpoints, logins, etc.
  2. Model: template database. Gets cloned when a new database is created. Any changes that one would like be applied by default to a new database should be made here
  3. Tempdb: re-created every time SQL Server instance is restarted. Holds intermediate results created internally by SQL Server during query processing and sorting, maintaining row versions, etc. Recreated from the model database. Sizing and configuration of tempdb is critical for SQL Server performance.
  4. Resource [hidden database]: stores executable system objects such as stored system procedures and functions. Allows for very fast and safe upgrades.
  5. MSDB: used by the SQL Server Agent service and other companion services. Used for backups, replication tasks, Service Broker, supports jobs, alerts, log shipping, policies, database mail and recovery of damaged pages.

Database Files

  1. Primary data files: every database must have at least one primary data file that keeps track of all the rest of the files in the database. Has the extension .mdf.
  2. Secondary data files: a database may have zero or more secondary data files. Has the extension .ndf.
  3. Log files: every database has at least one log file that contains information necessary to recover all transactions in a database. Has the extension .ldf.

Creating a Database

  1. New user database files must be at least 3 MB or larger including the transaction log
  2. The default size of the data file is the size of the primary data file of the model database (2 MB) and the default size of the log file is 0.5 MB
  3. If LOG ON is not specified but data files are specified during a create database, the size of the log file is 25% of the sum of the sizes of all the data files.

Expanding or Shrinking a Database

  1. Automatic File Expansion:
  1. The file property FILEGROWTH determines how automatic expansion happens
  2. File property MAXSIZE sets the upper limit on the size
  • Manual File Expansion: use the ALTER DATABASE command with the MODIFY FILE option to change the SIZE property to increase the database file size
  • Fast File Initialization: adds space to the data file without filling the newly added space with zeros. New disk content is overwritten as new data is written to the files. Security is managed through Windows security setting SE_MANAGE_VOLUME_NAME
  • Automatic Shrinkage:
    1. Same as doing DBCC SHRINKDATABASE (dbname, 25). Leave 25 % free space in the database after the shrink
    2. Thread performs autoshrink as often as 30 minutes, very resource intensive
  • Manual Shrinkage: use DBCC SHRINKDATABASE if you want to shrink.
  • I highly recommend not to shrink the database.
  • Filegroups

    1. Can group data files for a database into filegroups for allocation and administration purposes.
    2. Improves performance by controlling the placement of data and indexes into specific filegroups on specific drives or volumes.
    3. Filegroup containing the primary data file is called the primary filegroup, there is only one primary filegroup.
    4. Default filegroup: there is at least one filegroup with the property of DEFAULT, can be changed by DBA.
    5. Use cases when -not- to use filegroups:
    1. DBA might decide to spread out the I/O for a database: easiest way is to create a database file on a RAID device.
    2. DBA might want multiple files, perhaps to create a database that uses more space than is available on a single drive: can be accomplished by doing CREATE DATABASE with a list of files on separate drives
  • Use cases when you want to use filegroups:
    1. DBA might want to have different tables assigned to different drives or to use the table and index partitioning feature in SQL Server.
  • Benefits:
    1. Allows backup of parts of the database.
    2. Table is created on a single filegroup, allows for backup of critical tables by backing up selected filegroups.
    3. Same for restoration. Database can be online as soon as primary filegroup is restored, but only objects on the restored filegroups will be available.

    Given the nature of content, also look at the other topics we have discussed before.

    Concurrency Basics

    Locking Basics

    Transaction Log Basics

    Thanks for reading this far. Feel free to pass your comments too.

    Continue reading...


     

    SQL Server: Locking basics November 15th, 2012

    Vinod Kumar

    The learning journey can never stop. As we learn the basic building blocks of SQL Server there is always a need to do refreshers. This blog is on the same lines. I would urge you to read the Blog around Concurrency over at Pinal’s site and then continue the reading below because the basics of Locking is incomplete if we don’t understand what are the concurrency basics. Just like you have traffic signals that regulates traffic to make sure there are no grid locks or long waits for commuters. The parallel lanes for traffic is synonymous to concurrency. SQL Server uses locks as an mechanism to bring the consistency at the same time build the concurrency for the system. Locks are inevitable in any database world and those are also fundamental building blocks.

    1. Locks are applied in both optimistic and pessimistic concurrency models.
    2. Locking is used for maintaining consistency for concurrent transactions.
    3. Read operations acquire shared locks, exclusive locks by write operations while update locks are got during initial portion of an update operation when SQL Server is searching for the data to update.
    4. SQL Server releases locks automatically and manages compatibility between various locking modes, resolves deadlocks and lock escalations are done to reduce overheads.
    5. SQL Server controls locks on tables, on the pages of the table, on index keys and on individual rows of data based on the operation done.

    Lock Modes

    1. Shared Locks
      1. Automatically acquired while reading data.
      2. This lock can be on a page, table, index key or individual row based on the isolation level.
      3. Multiple processes can hold shared locks on the same data and read from it too.
      4. No other process can get an exclusive lock on data that has a shared lock. Neither can a process acquire a shared lock when there is an exclusive lock already on the table.
      5. Shared locks are not held for the whole duration of read in the default isolation level.
    2. Exclusive Locks
      1. This lock is acquired on data when modifications are done by DML statements like INSERT, UPDATE or DELETE operation.
      2. At any point in time exclusive locks can be held by only one process.
      3. In an exclusive locking mode no other process can take locks in this process.
      4. Exclusive locks are taken for the duration of the transaction length as the process can either commit or rollback.
    3. Update Locks
    1. This is an hybrid of exclusive and shared locks.
    2. This lock is taken when SQL Server searches the table to find the resource that needs to be modified.
    3. This can also be initiated using using query hints. It is desirable not to use the same.
    4. Even in this lock, it is not the sufficient level to change data. SQL Server must take exclusive lock to modify data.
    5. Used as an intermediate lock before escalating to exclusive locks.
  • Intent Locks
    1. As the name suggests is a pre-qualifiers to shared/update/exclusive locks.
    2. Since SQL Server can acquire locks at different levels, before the process completes or the statements completes SQL Server might want to know if locks are already acquired.
    3. This is an intermediate locking state and not to be confused as a separate locking mode.
  • Special Lock Modes
    1. Schema stability locks – at the time of compilations, this lock makes sure that no other process is modifying the schema of the underlying objects.
    2. Schema modification locks – acquired when a table’s structure is being modified.
    3. Bulk update locks – locks taken for BULK INSERT command or bcp utility operation. This lock can also be turned on using the table hints.
  • Conversion Locks
    1. As the name suggests, this lock happens during a conversion from one mode to another. There are three types SIX, SIU, UIX where SIX is the most common and the details are below.
  • Key-Range Locks
    1. Locks taken in serializable isolation level for locking ranges of data.
    2. Can be taken only on keys.
  • Let us look at the common abbreviation and locking mode descriptions:

    1. S – Shared: Allows processes to read concurrently but cannot change the resource locked.
    2. X – Exclusive: Prevents processes from modifying or reading data in the data.
    3. U – Update: Prevents external processes from acquiring an update or exclusive lock.
    4. IS – Intent shared: Acquired when resource is locked with a shared lock.
    5. IU – Intent update: Acquired when the resource is locked with an update lock.
    6. IX – Intent exclusive: Acquired when the resource is locked with an exclusive lock.
    7. SIX – Shared with intent exclusive: Shows that a shared lock pages have either a page or row with exclusive locks.
    8. SIU – Shared with intent update: Shows that a shared lock pages have either a page or row with an update lock.
    9. UIX – Update with intent exclusive: Shows that a update lock pages have either a page or row with exclusive locks.
    10. Sch-S – Schema stability: Used to show a query using the object is being compiled at that moment.
    11. Sch-M – Schema modification: Used to indicate the table’s structure is being updated at this moment.
    12. BU – Bulk update: Lock acquired when bulk copy operation (like bcp) is copying data into a table.

    Lock Granularity

    1. SQL Server can lock resources at the table, page, partition or row level.
    2. If locks are escalated, SQL Server can also lock a single partition of a table or index.
    3. SQL Server can also lock index keys and ranges of index keys if needed.
    4. DMV sys.dm_tran_locks view keeps track of each lock and contains information about the resource which is locked and an identifier for the specific resource

    Key Locks

    1. SQL Server use of key locks depends on the isolation level of the transaction.
    1. If isolation level is Read Committed, Repeatable Read or Snapshot, SQL Server locks the actual index keys accessed while processing the query.
    2. If isolation level is serializable, to counter phantoms reads, key-range locks are acquired for the range of values queried.
    3. Incase of tables with clustered index, leaf node contains the data and hence the locks are acquired at this level.
  • There are 9 types of key-range locks:
    1. RangeS-S
    2. RangeS-U
    3. RangeIn-Null
    4. RangeX-X
    5. RangeIn-S
    6. RangeIn-U
    7. RangeIn-X
    8. RangeX-S
    9. RangeX-U 

    Other Locking Assets

    1. We saw locks on objects, pages, keys, partitions and rows. Three are other SQL Server can lock too.
    2. Extents are units of 64KB disk space that can be locked. This is a special type of lock that is taken when an object needs to expand and a new extent is allocated.
    3. Generally connections hold a lock on at least one database object and will have resource_type = DATABASE at a minimum running in the session.
    4. You occasionally have locks on individual partitions, indicated in the lock metadata as HOBT locks. Occurs when locks are escalated and escalation to that partition level is allowed

    Lock Duration

    1. The length of time that a lock is held depends primarily on the mode of the lock and transaction isolation level in effect.
    2. Shared locks in Read Committed and Snapshot isolation levels are released as soon as SQL Server has read and processed the locked data
    3. Shared locks behave the same as exclusive locks in Repeatable Read and Serializable isolation levels – they are not released until the end of the transaction
    4. Update locks are also held until the end of the transaction unless it has been promoted to an exclusive lock in which case it behaves like the exclusive lock

    Lock Ownership

    1. Lock duration is directly affected by lock ownership
    2. Ownership == scope of the lock
    3. Four types of lock scopes
      1. Transactions – Durations depend on isolation level and lock mode (shared locks and update/exclusive locks)
      2. Cursors – requested explicitly when a cursor is declared. If a cursor is opened using a locking mode of SCROLL_LOCKS, a cursor lock is held on every row fetched until the next row is fetched or the cursor is closed. Even if the transaction commits before the next fetch, the cursor lock is not released
      3. Transaction_Workspaces – acquired every time a database is accessed and the resource associated with these locks is always a database. A workspace holds database locks for sessions – usually there is one workspace per session and all DATABASE locks acquired in the session are kept in the same workspace object. In distributed transactions, multiple sessions are enlisted into the same workspace so they share the database locks
      4. Sessions – must be requested explicitly using the sp_getapplock procedure, and apply only to APPLICATION locks. Its duration is until the session disconnects or the lock is released explicitly

    Thanks for reading this far. I know there is more to learn and write like Lock Timeout, Locking Hints, Version Stores, Snapshot Isolation Level, Row Versioning, Deadlocks, Lock Escalations, Row-level Locking and Page-level Locking, Lock Blocks, internal locking etc !!! I will surely keep you posted similarly in future.

    Continue reading...