SQL Server Database Administartion

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 79

BACKUPS

Full backups

A full backup, as the name implies, backs up everything. It is the foundation of any kind
of backup. This is a complete copy, which stores all the objects of the database: Tables,
procedures, functions, views, indexes etc. Having a full backup, you will be able to easily
restore a database in exactly the same form as it was at the time of the backup.

A full backup creates a complete backup of the database as well as part of the
transaction log, so the database can be recovered. This allows for the simplest form of
database restoration, since all of the contents are contained in one single backup.

A full backup must be done at least once before any of the other types of backups can be
run—this is the foundation for every other kind of backup.

How to create full database backup using T-SQL

BACKUP DATABASE DATABASENAME


To DISK='f:\PowerSQL\SQLShackDemoATC.BAK'
WITH FORMAT,
      MEDIANAME = 'Native_SQLServerBackup',
      NAME = 'Full-SQLShackDemoATC backup';

Full Database Backup to Multiple files

BACKUP DATABASE SQLShackDemoATC TO


DISK = 'f:\PowerSQL\SQLShackDemoATC_1.BAK',
DISK = 'f:\PowerSQL\SQLShackDemoATC_2.BAK',
DISK = 'f:\PowerSQL\SQLShackDemoATC_3.BAK',
DISK = 'f:\PowerSQL\SQLShackDemoATC_4.BAK'
WITH INIT, NAME = 'FULL SQLShackDemoATC backup', STATS = 5

If you’d like to create a mirror copy of the backup file:

BACKUP DATABASE ProdSQLShackDemo


TO DISK = 'F:\PowerSQL\ProdSQLShackDemo_1.BAK'
MIRROR TO DISK =  'F:\PowerSQL\ProdSQLShackDemo_2.BAK'
WITH FORMAT

You can, in fact, have up to three mirror copies

BACKUP DATABASE ProdSQLShackDemo


TO DISK = 'F:\PowerSQL\ProdSQLShackDemo_1.BAK'
MIRROR TO DISK =  'F:\PowerSQL\ProdSQLShackDemo_2.BAK'
MIRROR TO DISK =  'F:\PowerSQL\ProdSQLShackDemo_3.BAK'
MIRROR TO DISK =  'F:\PowerSQL\ProdSQLShackDemo_4.BAK'
WITH FORMAT
Differential Backups
A differential database backup is the superset of the last full backup and contains all
changes that have been made since the last full backup. So, if there are very few
transactions that have happened recently, a differential backup might be small in size,
but if you have made a large number of transactions, the differential backup could be
very large in size. 
As a differential backup doesn’t back up everything, the backup usually runs quicker
than a full backup. A differential database backup captures the state of the changed
extents at the time that backup was created. If you create a series of differential
backups, a frequently-updated database is likely to contain different data in each
differential. As the differential backups increase in size, restoring a differential backup
can significantly increase the time that is required to restore a database. Therefore, it is
recommended to take a new full backup, at set intervals, to establish a new differential
base for the data.

Differential backups save storage space and the time it takes for a backup. However, as
data changes over time, the differential backup size also increases. The longer the age of
a differential backup and larger the size and at some point in time it may reach the size
of the full backup. A large differential backup loses the advantages of a faster and
smaller backup as it requires the full backup to be restored before restoring the recent
differential backup. Typically, we would restore the most recent full backup followed by
the most recent differential backup that is based on that full backup

BACKUP DATABASE [SQLShackDemoATC]


   To DISK='f:\PowerSQL\SQLShackDemoATC_Diff.BAK'
   WITH DIFFERENTIAL,
    MEDIANAME = 'Native_SQLServerDiffBackup',
    NAME = 'Diff-SQLShackDemoATC backup';

Transaction Log Backup

The log backup, as its name implies, backs up the transaction logs. This backup type is
possible only with full or bulk-logged recovery models. A transaction log file stores a
series of the logs that provide the history of every modification of data, in a database. A
transaction log backup contains all log records that have not been included in the last
transaction log backup.

It allows the database to be recovered to a specific point in time. This means that the
transaction log backups are incremental and differential backups are cumulative in
nature. If you want to restore the database to a specific point in time, you need restore a
full, recent differential, and all the corresponding transaction log records which are
necessary to build the database up to that specific point, or to a point very close to the
desired point in time, just before the occurrence of the accident that resulted in the data
loss. This series of modifications is contained and maintained using LSN (Log Sequence
Number) in the log chain. A log backup chain is an unbroken series of logs that contain
all the transaction log records necessary to recover a database to a point in time. A log
chain always starts with a full database backup and continues until for reason it breaks
the chain (for example, changing the recovery model of database to simple, or taking an
extra full backup), thus by preventing log backups from being taken on the database
until another full (or differential) backup is initiated for that database.

How to create Transactional log backup using T-SQL

BACKUP LOG [SQLShackDemoATC]


   To DISK='f:\PowerSQL\SQLShackDemoATC_Log.trn'
   WITH
   MEDIANAME = 'Native_SQLServerLogBackup',
    NAME = 'Log-SQLShackDemoATC backup';

Tail log backups

In the event of a failure, when you need the database to get back up and running, and
the database is operating in FULL or BULK_LOGGED recovery model, it’s always easy to
start the recovery operation and start restoring the backups. But before that, the first
action to be taken after the failure is what is called as a tail log backup of the live
transaction log.

This is an intermediate step that we need to take before we start the restoration. This
process is called tail log backup restoration.

USE master;
GO
-- create a tail-log backup
BACKUP LOG [SQLShackDemoATC]
TO DISK = 'f:\PowerSQL\SQLShackDemoATCTailLog.log'
WITH CONTINUE_AFTER_ERROR;
GO

The WITH CONTINUE_AFTER_ERROR clause will force SQL Server to store the log file,
even though it’s generating an error.

Copy Only backup

A copy-only backup is a special type of full backup, which is independent of the


conventional sequence of backups. The difference between copy-only and a full backup
is that a copy-only backup doesn’t become a base for the next differential backup.

A full backup works on all database recovery models. Copy-only backup, on the other
hand, is applicable only to a full or bulk-logged recovery models. The restoration of a
copy-only backup is no different than a normal restoration process.

BACKUP DATABASE [SQLShackDemoATC]

To DISK='f:\PowerSQL\SQLShackDemoATC_1.BAK'

WITH COPY_ONLY,
      MEDIANAME = 'Native_SQLServerFullBackup',

      NAME = 'Full-SQLShackDemoATC backup';

BACKUP LOG [SQLShackDemoATC]

TO DISK = 'f:\PowerSQL\SQLShackDemoATCCopyOnly.log'

WITH COPY_ONLY;

GO

Partial backups

Partial backups are one of the least-used backup methods available in SQL Server. All
database recovery models support partial backups, but partial backups are mostly used
in the simple recovery model in order to improve flexibility when backing up large
databases that contain read-only filegroups.

The READ_WRITE_FILEGROUPS option is used with the BACKUP DATABASE command.


This command is for partial backup. It processes the backup of read-write file groups.

SQLShackPartialBackup is the database created with primary and secondary file groups.
Let’s use this database for this demo.

CREATE DATABASE SQLShackPartialBackup ON  PRIMARY

( NAME = N'SQLShackPartialBackup_1',

FILENAME = N'f:\PowerSQL\SQLShackPartialBackup_1.mdf' ,

SIZE = 5000KB , FILEGROWTH = 1024KB ),

FILEGROUP [Secondary]

( NAME = N'SQLShackPartialBackup_2',

FILENAME = N'f:\PowerSQL\SQLShackPartialBackup_2.mdf' ,

SIZE = 5000KB , FILEGROWTH = 1024KB )

LOG ON

( NAME = N'SQLShackPartialBackup_Log',

FILENAME = N'f:\PowerSQL\SQLShackPartialBackup_log.ldf' ,

SIZE = 1024KB , FILEGROWTH = 10%)

GO
Let’s change the recovery model of the database to SIMPLE using the following
ALTER statement

ALTER DATABASE SQLShackPartialBackup SET RECOVERY SIMPLE

Now, set the secondary file-group to READONLY mode

ALTER DATABASE SQLShackPartialBackup MODIFY FILEGROUP [Secondary]


READONLY

Initiate a backup using the READ_WRITE_FILEGROUPS option

BACKUP DATABASE SQLShackPartialBackup READ_WRITE_FILEGROUPS

TO DISK = N'f:\PowerSQL\SQLShackPartialBackup_Full.bak'

File and File Group Backups


This topic is relevant for SQL Server databases that contain multiple files or file groups.

File backups of read-only file groups can be combined with partial backups. Partial backups
include all the read/write file groups and, optionally, one or more read-only file groups. 

Let’s create a database with multiple files and filegroups.

CREATE DATABASE SQLShackFileBackup ON  PRIMARY

( NAME = N'SQLShackFileBackup_1',

FILENAME = N'f:\PowerSQL\SQLShackFileBackup_1.mdf' ,

SIZE = 5000KB , FILEGROWTH = 1024KB ),

FILEGROUP [Secondary]

( NAME = N'SQLShackFileBackup_2',

FILENAME = N'f:\PowerSQL\SQLShackFileBackup_2.ndf' ,

SIZE = 5000KB , FILEGROWTH = 1024KB )

LOG ON

( NAME = N'SQLShackFileBackup_Log',

FILENAME = N'f:\PowerSQL\SQLShackFileBackup_Log.ldf' ,

SIZE = 1024KB , FILEGROWTH = 10%)


The following examples demonstrates how to create the file-level backup of the
files:

BACKUP DATABASE SQLShackFileBackup  

   FILE = 'SQLShackFileBackup_1',  

   FILE = 'SQLShackFileBackup_2'  

   TO DISK = 'f:\PowerSQL\SQLShackGroupfiles.bak';  

GO 

The following example illustrates the full file backup of all the files in both of the
primary and secondary file-groups.

BACKUP DATABASE SQLShackFileBackup  

   FILEGROUP = 'PRIMARY',

   FILEGROUP = 'Secondary'

   TO DISK = 'f:\PowerSQL\SQLShackGroupfilegroup.bak';  

GO
Backup Set Options

The following are the few options that operate on the database backup set that would be
created using backup database command

WITH Options

The WITH clause is used with the BACKUP command in case we have additional backup
requirements.

COMPRESSION: This option enables backup compression. NO_COMPRESSION explicitly


disables the backup compression. Compression is turned off during backups by default.

ENCRYPTION: An encryption algorithm can be specified with BACKUP to secure the backup

files stored offsite. You can specify NO_ENCRYPTION when you don’t need backup encryption.

Media set Options

FORMAT: This option used to specify whether to overwrite the media header
information. The FORMAT clause will create a new media backup set, whereas
NOFORMAT will preserve all the information.

INIT: INIT is used to create a new backup set; NOINIT is used for appending the backup
to the existing backup set. The NOINIT parameter is used mostly when you backup the
database to a tape device.

NAME: The NAME parameter is used to identify the backup set.

SKIP: The skip parameter is used to skip the expiration check on the backup set.

NOREWIND: This parameter is used to keep a tape device open and ready for use

NOUNLOAD: This parameter is used to instruct SQL Server to not unload the tape from
the drive upon completion of the backup operation.

STATS: The STATS option is useful to get the status of the backup operation at regular
stages of its progress.
SQL Server Restore Commands

There are several RESTORE commands and options that can be used to restore and view
the contents of your backup files.

In this next section we will look at the following commands that can be used:

 RESTORE HEADERONLY - gives you a list of all the backups in a file

RESTORE HEADERONLY FROM DISK = 'C:\AdventureWorks.BAK'

 RESTORE LABELONLY - gives you the backup media information

RESTORE LABELONLY FROM DISK = 'C:\AdventureWorks.BAK'

RESTORE FILELISTONLY - gives you a list of all of the files that were backed up
for a give backup

RESTORE FILELISTONLY FROM DISK = 'C:\AdventureWorks.BAK' WITH FILE = 1

 RESTORE DATABASE - allows you to restore a full, differential, file or filegroup


backup

RESTORE DATABASE AdventureWorks FROM DISK = 'C:\AdventureWorks.BAK'

 RESTORE LOG - allows you to restore a transaction log backup

RESTORE LOG AdventureWorks FROM DISK = 'C:\AdventureWorks.TRN'

 RESTORE VERIFYONLY - verifies that the backup is readable by the RESTORE


process

RESTORE VERIFYONLY FROM DISK = C:\AdventureWorks.BAK

Check a backup file on disk for a particular backupThis command will check the
second backup in this backup file. To check the contents in a backup you can
use RESTORE HEADERONLY and use the Position column to specify the FILE number.

RESTORE VERIFYONLY FROM DISK = C:\AdventureWorks.BAK WITH FILE = 2

RESTORE REWINDINLY

Rewinds and closes specified tape devices that were left open by BACKUP or RESTORE
statements executed with the NOREWIND option. This command is supported only for
tape devices
Understanding the Different States of SQL Database

There are multiple numbers states of a SQL Database. These states determine the
current status or mode of database in SQL server.

At once, the database is only in one state, which may be any one of the following:

 Online , Offline, Restoring, Recovering, Recovery Pending, Emergency, Suspect

In this blog, we are going to discuss about all these states in detail.

Description Of Several States of SQL Database

Online: 

This server state indicates that the database is accessible for end users. The primary
filegroup is online, even if the recovery process of undo phase has not been finished.

Offline: 

The state illustrates that the database is unavailable. This state of server is caused by
explicit user action and it remains in offline mode until & unless users don’t perform
any action on database.

Note: To determine whether the server is in offline state or in an online state, one can
run the following command:

SELECT * FROM sys.databases


After running this command, you will find a table with ColumnName and Value
attributes. In this table, search for state_desc option in ColumnName and check the
Value attribute that whether it is Online or Offline.

Restoring:

 In this state of SQL database one or more data files are being restored from primary file
group. Apart from this, the state also occurs when one or more secondary files are being
restored in offline mode (i.e., database is unavailable). After completion of restoration
procedure, the database is modified into an useable state and hence, users can now
access the restored database.
Recovering: 

At the time of restarting the SQL server, all database undergoes “Recovery” process. In
this state, the database comes in its consistent state i.e., during the process its state
changes from recovery state to online state. Moreover, the recovering procedure is
performed in three phases i.e., Discovery, roll forward, and Rollback

 Discovery Phase: The first phase discovers that where will the server proceed
through log file. During its discovery procedure, it built-in the memory structure for
determining the memory required for going to next phases.

 Roll Forward Phase: The second phase determines the transactions that were
committed while shutting down the database but not yet written to MDF file through
checkpoints.

 Rollback Phase: Last phase of this recovering process determines whether there


are any uncommitted transactions in database or not. If yes, then they first roll back
those transactions and than bring database into consistent state.

TIP: With help of following command, one can recover a database, which is in restoring
state:

RESTORE DATABASE ADventureWorks WITH RECOVERY

Recovery Pending: 

While working with the server, users encounter an error that are related to resources
during recovery process. In such cases, database is not corrupted or damaged. This state
occurs when some data files are missing or there is some problem with system
resources. Therefore, some external operations are being required by users to resolve
this error state and continue the recovery process until its end.

Suspect: 

In this state, the recovery gets started but does not reach to its completion. It does not
allow users to connect with database and can be considered as an inconsistent state.
However, the common reason behind occurrence of such state is that the primary
filegroup may be corrupted & hence, in suspect. Therefore, this state also requires some
additional actions that repair the corrupted file & recover data from it.

Emergency: 

This state is enable by users by making some default changes. Such state
implementation can only be performed in single-user mode and could be restored or
repaired. In such state, database is in READ_ONLY state, logging is disabled, and access
is restricted. Suppose a database is find out as a suspect can be set to emergency state,
which will allow admin to perform read-only operation within it. Hence, no one can
perform any updation in such database that is in emergency mode
SQL Server Database Recovery Models

A recovery model is a database configuration option that determines the type of backup
that one could perform, and provides the ability to restore the data or recover it from a
failure.

The recovery model decides how the transaction log of a database should be maintained
and protects the data changes in a specific sequence, which may later be used for a
database restore operation.

Types of recovery models

All SQL Server database backup, restore, and recovery operations are based on one of
three available recovery models:

 SIMPLE
 FULL
 BULK_Logged

SIMPLE

The SIMPLE recovery model is the simplest among the available models. It supports full,
differential, and file level backups. Transaction log backups are not supported. The log
space is reused whenever the SQL Server background process checkpoint operation
occurs. The inactive portion of the log file is removed and is made available for reuse.

Point-in-time and page restore are not supported, only the restoration of the secondary
read-only file is supported.

Reasons to choose the simple database recovery model

1. Most suited for Development and Test databases


2. Simple reporting or application database, where data loss is acceptable
3. The point-of-failure recovery is exclusively for full and differential backups
4. No administrative overhead

It supports:

1. Full backup
2. Differential backup
3. Copy-Only backup
4. File backup
5. Partial backup

FULL

In this recovery model, all the transactions (DDL (Data Definition Language) + DML
(Data Manipulation Language)) are fully recorded in the transaction log file. The log
sequence is unbroken and is preserved for the databases restore operations. Unlike the
Simple recovery model, the transaction log file is not auto-truncated during
CHECKPOINT operations.

All restore operations are supported, including point-in-time restore, page restore and
file restore.

Reasons to choose the full database recovery model:

1. Supporting mission critical applications


2. Design High Availability solutions
3. To facilitate the recovery of all the data with zero or minimal data loss
4. If the database designed to have multiple filegroups, and you want to perform a
piecemeal restore of read/write secondary filegroups and, optionally, read-only
filegroups.
5. Allow arbitrary point-in-time restoration
6. Restore individual pages
7. Incur high administration overhead

It supports all type of following backups

1. Full backup
2. Differential backup
3. Transaction log backup
4. Copy-Only backup
5. File and/or file-group backup
6. Partial backup

BULK_LOGGED

It’s a special purpose database configuration option and it works similar to FULL
recovery model except that certain bulk operations can be minimally logged. The
transaction log file uses a technique known as minimal logging for bulk operations. The
catch is that it’s not possible to restore specific point-in-time data.

Reasons to choose the bulk logged recovery model:

1. Use minimal logging technique to prevent log file growth


2. If the database is subjected to periodic bulk operations

It supports all types of backups:

1. Full backup
2. Differential backup
3. Transaction log backup
4. Copy-Only backup
5. File and/or file-group backup
6. Partial backup
Transaction log internals

It’s worth taking the time to understand the internals of the SQL Server transaction log.

1. Whenever there is a transaction (DDL and DML) the details of every operation is
logged in the transaction log file
2. The transaction log backup ensures transactional durability and data consistency
using a mechanism known as WAL (Write-Ahead-Logging). The transactions that
occur on the database first get registered into the transaction log file and then
the data is written to the disk. This facilitates the SQL Server to rollback or roll-
forward every step of the recovery process
3. Enables point-in-time restore of databases
4. SQL Server always writes to the transaction log file sequentially. It’s cyclic in
nature. The transaction log file is further divided into log blocks which are
logically mapped using VLF’s (Virtual Log Files)
5. The log records in the blocks that are no longer needed are deemed as “inactive,”
and this portion of the log blocks can be truncated, i.e., the inactive segments of
the log blocks are overwritten by new transactions. These segments or portion of
the log file are known as virtual log files (VLFs)
6. Any inactive VLF can be truncated, although the point at which this truncation
can occur depends on the recovery model of the database
7. In the SIMPLE recovery model, truncation can take place immediately upon the
occurrence of a CHECKPOINT operation. Pages in the data cache are flushed to
the disk, having first “hardened” the changes to the log file. The space in any VLFs
that becomes inactive as a result, and is made available for reuse
8. A database may have multiple log files but it’s mandatory to have at least one. It
will only ever write to one log file at a time, and having more than one files will
not boost write-throughput or speed. In fact, having more multiple files could
result in performance degradation, if each file is not correctly sized or differs in
size. Any mismatch leads to longer duration of recovery of the database
9. For business-critical databases, it is recommended to initiate full database
backups, followed by a series of frequent transaction log backups, followed by
another full backup, and so on. As part of the database restore operation, we can
restore the most recent full backup (plus differentials, if taken), followed by the
chain of available log file backups, up to the one covering the point in time to
which we wish to restore the database 

Recovery Model Overview

Simple

 Description
o No transaction log backups.
o In the Simple Recovery Model, the transaction log is automatically purged and
the file size is kept intact. Because of this, you can’t make log backups in this case.
o Supports only full and bulk_logged backup operations.
o The unsupported features of in simple recovery model are: Log shipping,
AlwaysOn or Mirroring and Point-in-time restore
 Data loss
o Yes; we cannot restore the database to an arbitrary point in time. This means, in
the event of a failure, it is only possible to restore database as current as the last
full or differential backup, and data loss is a real possibility
 Point-in-time restore
o No

Full

 Description
o Supports transaction log backups.
o No work is lost due to a lost or damaged data file. The Full database recovery
model completely records every transaction that occurs on the database. 
o One could arbitrarily choose a point in time for database restore. 
o This is possible by first restoring a full backup, most recent differential then
replaying the changes recorded in the transaction log. If a differential backup
doesn’t exist, then the series of t-logs are applied.
o Supports Point-in-time data recovery.
o If the database uses the full recovery model, the transaction log would grow
infinitely, and that will be a problem. So, we need to make sure that we take
transaction log backups on a regular basis. 
 Data loss
o Minimal or zero data loss.
 Point-in-time restore
o This setup enables more options. 
o Point-in-time recovery.

Bulk logged

 Description
o This model is similar to the Full Recovery Model, in that a transaction log is kept,
but certain transactions such as bulk loading operations are minimally logged,
although it logs other transaction. This makes the bulk data imports perform
quicker and keeps the file size of the transaction log down, but does not support
the point in time recovery of the data.
o This can help increase performance bulk load operations.
o Reduces log space usage by using minimal logging for most bulk operations.
 Data loss
o If you run transactions under the bulk-logged recovery model that might require
a transaction log restore, these transactions could be exposed to data loss.
 Point-in-time restore
o Point-in-time recovery is not possible with bulk-logged model
o It is possible only if the following conditions are satisfied: 
Users are currently not allowed in the database. 
If you’re able to re-running the bulk processes.
Switching recovery models

Full and bulk-logged

1. Initiate a log backup


2. Perform bulk operations, immediately switch back the database to full recovery
model
3. Initiate transaction log backup

Simple to FULL or Differential

1. Initiate a full (or differential, if full is already available) database backup


2. Schedule t-log backups

FULL or BULK_Logged to Simple

1. Disable the transaction log backup job


2. Ensure that there is a job to take full backup
INERTVIEW QUESTIONS

How can I verify that backups are occurring on a daily basis?


o Review the SQL Server error log for backup related entries.
o Query the msdb.dbo.backupset table for the backup related entries.
o Review the file system where the backups are issued to validate they
exist.
o Check all backup jobs history

 How do you know if your database backups are restorable?

o Issue the RESTORE VERIFYONLY command to validate the backup. For


validating LiteSpeed backups use XP_restore_verifyonly
o Restore the backups as a portion of a log shipping solution.
o Randomly retrieve tapes from off site and work through the restore
process with your team to validate the database is restored in a successful
manner.

What is the database that has the backup and restore system tables?  What are the
backup and restore system tables?  What do each of the tables do?

 The MSDB database is the database with the backup and restore system tables.
 Here are the backup and restore system tables and their purpose:
o backupfile - contains one row for each data file or log file backed up
o backupmediafamily - contains one row for each media family
o backupmediaset - contains one row for each backup media set
o backupset - contains one row for each backup set
o restorefile - contains one row for each restored file
o restorefilegroup - contains one row for each restored filegroup
o restorehistory - contains one row for each restore operation

 In a situation with full, differential and transaction log backups being issued for a
database, how can an out of sequence full backup be issued without interrupting
the LSN's?
 Issue the BACKUP command with the COPY_ONLY option

How is a point in time recovery performed independent of a server down


situation?

It depends on which backup types are issued.  In this example let's assume that full,
differential and transaction log backups are issued.
o Restore the most recent full backup with the NORECOVERY clause
o Restore the most recent differential backup with the NORECOVERY clause
o Restore all of the subsequent transaction log backups with the
NORECOVERY clause except the last transaction log backup
o Restore the last transaction log backup with the RECOVERY clause and a
STOPAT statement if the entire transaction log does not need to be
applied
What are the permissions required to perform backup and Restore?
Ans:
The user must be a member of either of the below roles

Backup:
 sysadmin – fixed server role
 db_owner –  fixed database role
 db_backupoperator – fixed database role

Restore:
 Sysadmin – fixed server role
 Dbcreator – fixed server role
 db_owner – fixed database role

How can you be notified if a native SQL Server database backup or restore fails via
the native tools?
Ans:
 Setup SQL Server Alerts to be sent to Operators on a failure condition.

Include RAISERROR or TRY\CATCH logic in your backup or restore code to alert on the
failure.

How is a point in time recovery performed?


Ans:
It depends on which backup types are issued.  In this example let’s assume that full,
differential and transaction log backups are issued.

 Restore the most recent full backup with the NORECOVERY clause
 Restore the most recent differential backup with the NORECOVERY clause
 Restore all of the subsequent transaction log backups with the NORECOVERY clause
except the last transaction log backup
 Restore the last transaction log backup with the RECOVERY clause and a STOPAT
statement if the entire transaction log does not need to be applied

Consider a scenario where you issue a full backup.  Then issue some transaction
log backups, next a differential backup, followed by more transaction log
backups, then another differential and finally some transaction log backups.  If
the SQL Server crashes and if all the differential backups are bad, when is the
latest point in time you can successfully restore the database?  Can you recover
the database to the current point in time without using any of the differential
backups?
Ans:
 You can recover to the current point in time, as long as you have all the
transaction log backups available and they are all valid. Differential backups do
not affect the transaction log backup chain
Can you restore master database? If yes how?
Ans:
All server level information stored in master database that includes logins information
etc. Schedule a regular backup for master database and below is the process to restore a
master db.

 Start the sql server in single user mode (-m)


 Issue the restore command with replace from SQLCMD prompt

 RESTORE DATABASE master FROM <backup_device> WITH REPLACE

 Restart the sql server in normal mode


 All databases as available at the time of master db backup must be attached as
everything is tracked in master database.
 If any databases are missing we can manually attach the mdf-ldfs.

How can we rebuild the system databases?


Ans:
We usually rebuild the system databases when they are corrupted.

Rebuild deletes the databases and recreates it hence all the existing information is
vanished.

Before rebuild:
 Locate all recent backup of system databases
 Make a note on mdf and ldf file locations, server configuration, Build /hotfix /sp
applied

Rebuild:
 Locate the Sql Server installation bits and run the command setup.exe fro command
prompt by passing the argument as “/ACTION=REBUILDDATABASE”
 Review the summary.txt once the rebuild completes

Post Rebuild:
 Restore all the system databases from existing backups
 Move the system databases mdf/ldf files to the actual locations

How can we rebuild Resource system database?


Ans:
In Sql Server 2008 from installation wizard from left navigation pane select
“Maintenance” and Click on Repair. It rebuilds the resource database.

Can we rebuild resource database?


Ans:
Yes! To rebuild these database files you would need to run Repair from the Installation
Center.
Can we rebuild msdb?
Ans:
Yes! We can directly restore it from a valid backup. If there is no valid backup available,
restore all system databases as described above.

What is the difference between Hot and Cold Backup?


Ans:
Performing backup while the database is online is called Hot backup. Stopping SQL
server service and copying MDF and LDF files is called cold backup which is not really
happens in production.

What are the restore options available?


Ans:
When you restore a backup, you can choose from 3 restore option.

1. With Recovery – Database is ready to use, and user can connect to database, user can
change data inside database.
2. No Recovery – Database is not ready, there are few more backups that has to be
applied to this database instance. User cannot connect to database because it is in
Restoring Status. (Exception: Not considering Database Snapshots )
3. Standby / Read Only – Database is ready to use but database is in Read Only mode,
user can connect to database but they cannot change data inside database. A running
database con not be changed to standby mode. Only a data in no-recovery state can
be moved to standby mode. This is an option that is specified while restoring a
database or transaction log.

What are the options to restore the database till Point 8 i.e. P8?

 Option 1: F1 > D2 > T5


 Option 2: F1 > D1 > T3 > T4 > T5
 Option 3: F1 > T1 > T2 > T3 > T4 > T5

What are the options to restore the database till Point 10 i.e. P10?

 Option 1: F2 > T6
 Option 2: F1 > D2 > T5 > T6
 Option 3: F1 > D1 > T3 > T4 > T5 > T6
 Option 4: F1 > T1 > T2 > T3 > T4 > T5 > T6

 What are the options to do a point in time recovery P13?

 Option 1: F2 > D3 >T8 with STOPAT Time stamp of P13


 Option 2: F2 > T6 > T7 > T8 with STOPAT Time stamp of P13
 Option 3: F1 > D2 > T5 > T6 > T7 > T8 with STOPAT Time stamp of P13
 Option 4: F1 > D1 > T3 > T4 > T5 > T6 > T7 > T8 with STOPAT Time stamp of
P13
 Option 5: F1 > T1 > T2 > T3 > T4 > T5 > T6 > T7 > T8 with STOPAT Time
stamp of P13

When we cannot take backup of database in which state?


         Suspect (only tail log backup is allowed)
         Restoring
         Standby
         Offline
         If T.Log file was full(Only Log backups are allowed)

How can we imagine or calculate size of backup?


                        Use <dbname>
                        Go                         
                        Sp_spaceused   Check reserved size

My database size is 8gb and daily 600 transactions give me your suggestible
strategy?
  Daily Full Backup
 Every 4hrs differential backups
   Every 2hrs T.Log backups

My database size is 600gb and daily 4000 transactions give me your suggestible
strategy?
 Weekly Full backup
 Daily Differential backups
 Every 1hr T.Log backup

My database size is 600gb and daily 4000 transactions give me your suggestible
strategy?
      Weekly Full backup
  Daily Differential backups
Every 1hr T.Log backup

Note: Whenever the database size is <200gb then follow FAQ: 8 steps. If db size is
<200gb follow FAQ: 9 steps.

How to know the backup path where backups are stored?


                        Use MSDB
                        Go
            Select * from backupmediafamilly

Note: Transaction log backups chain will never break.

How to recovery crashed database (data file & log file)?

Data File:
      1.      Check error log. If error number is 17204(data file was damaged)
      2.      Take tail log backup using

BACKUP LOG <dbname> TO DISK=’----‘ WITH NO_TRUNCATE


   
3.      Restore FULL BACKUP with NORECOVERY
      4.      Restore latest differential backup if any with NORECOVERY
      5.      Restore Tail log backup WITH RECOVERY

LOG File:
   
1.      If log was damaged then make the database into single_user_mode
Alter database <dbname> set single_user
      2.      Set the database in emergency mode
Alter database <dbname> set emergency
      3.      Run the checkdb with required repair level
DBCC Checkdb (‘dbname’, ‘Repair_allow_data_loss’)
      4.      Set the database into multi user mode
Alter database <dbname> set multi_user

Difference between Transaction log and tail log backups?

Transaction log Backup Tail Log Backup

It is scheduled log backup which truncates It is not scheduled it cannot truncate T.log
T.log file. file.
It forces checkpoint Skip checkpoint

Required to truncate T.log file To recovery data when data file was
damaged
My database recovery model was SIMPLE and I have taken full backup. I was
unable to take T.log backup hence I have changed recovery model to full. Can I
take T.log backup now?
            Not allowed, Full backup of SIMPLE recovery model cannot work as base for
T.Log backups we have to take first full backup then T.Log backup.

we have configured every Sunday 11pm FULL backup. Every 11pm differential
backups and every 1h.r T.log backups. Database was failed at 11.30 pm on Friday.
Then what are the db recovery steps?
          1.      Take Tail log backup to get 11-11.30pm transactions on Friday.
          2.      Restore last Sunday full backup with NO_RECOVERY
          3.      Restore Friday 11pm differential backup with NO_RECOVERY
          4.      Restore tail log backup with RECOVERY

My backup was failed what may be the possible scenarios?

            Disk was Full


            Server was busy
            Problem with network
            If domain is not running and SQL Server service is running with domain account
            Problem with MSDB and SQL Agent
            If there is disk I/O error while reading from data or T.log files
            CHECKSUM errors
            Database has entered into Suspect or restoring
            T.log file was full (only log backups are allowed other backups fail)

16: can I take tempdb backup and do the restore?


            We cannot take the tempdb bakup

17: can I take log backup in simple recovery model?


            No we cannot take log backup in simple recovery model.

18: What are the recovery states define it?


    .      
With Recovery
This database becomes operational. We cannot apply further backups.
    With NORecovery
This database becomes non-operational. We can apply further backups.
   With Standby
Database is restored in read only mode. Users can work only with SELECT c
Command. It allows further transaction log backups to be restored.

Recovery Models:

FULL BULK LOGGED SIMPLE


What’s logged All transactions All transactions Minimal for recovery
except Bulk
operations
Log truncated At backup At backup When Checkpoint
Available for restore Yes Yes No
Recommended for Yes Not Always NO
production
Point in time Possible No No
recovery
Supports log Yes Yes No
backups
Use minimal space No No Yes
Log shipping Yes Yes No
Mirroring Yes No No
Replication Yes Yes Yes

Why Database restores from upper version to lower version is not allowed?

Database servers get changed with service packs and new releases. New object types get
added and the lower versions cannot understand these object types.

In order to avoid such conflicts and problems – Higher end database restorations cannot
be performed directly on lower end database servers.

Is there any alternate method of restoring the database from Upper version to
lower version?

There is no proper method of restore the database from upper version to lower version.
However we can use below techniques to perform this task:

 Script out the database Objects and create these on the target database
 Use SQL Server Import Export Wizard to copy data from source server to
destination server (only Data)
 Copy data to destination tables using BCP (only Data)

Is it possible to attach the Data and log files of upper version to lower version SQL
Server instance?

No, It is not possible.

What are Mirrored Backup Media Sets?

Mirrored backup media sets are supported only in the Enterprise edition of SQL Server.

Mirroring a media set increases backup reliability by reducing the impact of backup-
device malfunctions. These malfunctions are very serious because backups are the last
line of defense against data loss. As database grows, the probability increases that a
failure of a backup device or media will make a backup non restorable. Mirroring
backup media increases the reliability of backups by providing redundancy.

22) Is it possible to mark Primary File Group as Read only?

No it’s not possible to make Primary File Group read only.

How to make the File Group read only?

Filegroups can be marked as read-only. Any existing filegroup, except the primary
filegroup, can be marked as read-only. A filegroup marked read-only cannot be modified
in any way. Read-only filegroups can be compressed.

ALTER DATABASE ReadFilegroup MODIFY FILEGROUP Test1FG1 Read_Only;

What are the benefits of Read only file groups?

 Can be compressed (using NTFS compression)


 During recovery you don’t need to apply logs to recover a read-only file group
 Protection of data from accidental modifications
How can you mount a database from MDF file even if you don’t have the
transaction log?

The only time that you can do this is when the DB was shut down cleanly before the log
file was lost. It’s still not a good idea. While attaching a data file without the log file may
be possible in some circumstances, it is not a recommended approach and is only for
cases when the log file has been damaged or lost due to hardware problems and there
are no backups available. Of course, you cannot have a database without a log file, so
SQL Server just recreates a log file when you attach the database.

Attaching a data file without the log file breaks the log chain and may render the
database transactionally or structurally inconsistent depending on the state of the
database before the log file was lost.

What is Piecemeal Restore of Database (Simple Recovery Model)?

A piecemeal restore sequence restores and recovers a database in stages at the


filegroup level, starting with the primary and all read/write, secondary filegroups.

 Partial restore of the primary and filegroups A and C.

RESTORE DATABASE adb FILEGROUP='A',FILEGROUP='C'

FROM partial_backup

WITH PARTIAL, RECOVERY;


At this point, the primary and filegroups A and C are online. All files in filegroup B are
recovery pending, and the filegroup is offline.

 Online restore of filegroup B.

RESTORE DATABASE adb FILEGROUP='B' FROM backup WITH RECOVERY;


Is it possible to perform a point in time recovery with Bulk Logged recovery
model?

Yes, it is possible to perform a point in time recovery with Bulk logged recovery model
till the time we don’t perform any minimal logged operation on the database.

How to recover a database that is in the “restoring” state?

RESTORE DATABASE AdventureWorks WITH RECOVERY

What are the important points which need to be taken care when we restore the
database from lower version to upper version?

 Change the compatibility mode of the database


 Run Update Usage command
 If possible (Time permits) run Index rebuild and Update statistics

How to change the database owner of the database?

EXEC sp_changedbowner 'Myuser';


Suppose I have a Database maintenance plan which runs every 15 minutes to take
the Transaction Logs backup of all user defined databases. One of the members of
DBA team created a new database in the morning at 09:10 AM and the DB
maintenance job started failing. What could be the reason?

This job is failing because the we did not take a full database backup of the newly
created database. We need to a full backup of a database to initiate the log chain.

Assume that the database recovery model is full. The full database backup runs
every week at 9 PM. Sunday, differential backup runs daily at 9 PM. Monday to
Saturday, and hourly transaction log backups. Now, database crashed on Friday
5:10 PM. How to do a point-in-time recovery of the database?

Yes, the point-in-time recovery is possible.

 First, initiate a tail log backup


 Now, restore recent Full database backup with NORECOVERY, i.e.is. Sunday 9 PM
backup
 Apply the Thursday night differential backup with NORECOVERY, i.e.is Thursday
9 PM. Differential backup
 Next, Apply all the T-Log backups since Thursday Differential backup with
NORECOVERY option
 Apply tail-log backup WITH RECOVERY and STOPAT options

How can I retain backup for a specific number of days?

If you want to retain the backup for the only specific number of days then use the WITH
RETAINDAYS clause with the database backup command.

BACKUP DATABASE PowerSQL TO DISK =  N'F:\PowerSQL\PowerSQL.BAK' WITH

RETAINDAYS = 3 , FORMAT, STATS=10

Question- If yes in above question then how is SIMPLE RECOVERY Model different
from FULL Recovery Model?

Answer- All logged transactions will be cleared during checkpoint operation and


transaction log backup is not allowed so point-in-time recovery is not possible in SIMPLE
recovery model. Whereas transaction backup is allowed in full recovery model and
point-in-time recovery is also supported. Logs got cleared only after taking log backup or
switching the recovery model to SIMPLE.

Question- Can we achieve point-in-time recovery in Bulk-logged Recovery Model?

Answer- Yes, if there is no bulk operation performed on your database and you have all
log backups. Point-in-time recovery is not possible if your recovery point falls falls in-
between any bulk operations. .

How differential backup captures only updated data since full backup in its dump
file?

Answer- Differential Changed Map is a page type that stores information about extents
that have changed since the last full backup. Database engine reads just the DCM pages
to determine which extents have been modified and captures those extents in
differential backup file.

Question- Why cannot we serve copy-only backup  as a differential base or


differential backup?

Answer- The differential changed map page is not updated by a copy-only backup.


Therefore, a copy-only backup cannot serve as a differential base or differential backup.
A copy-only backup does not affect subsequent differential backups.
Question- Why a database log file is growing like anything that is running
in SIMPLE Recovery Model?

Answer- It means some transactions are active and running on your database.  As we
know logs are captured in simple recovery model as well so that active transaction is
getting logged there. The inactive portion in log file clears during checkpoint operation.

Question- Can we restore a database till the specific time?

Answer- Yes, if database is running in full recovery model and database has log backups
till that specific time. We can use STOPAT clause to recover till a specific time.

Question- Suppose we are running Daily full backup at 8PM in night and every half
an hour transaction log backup. Now your database is crashed at 3.41PM. How will
you recover your database to the point it was crashed?

Answer- Below steps we will perform in a sequence manner to recover this database to


the point it was crashed.
 First we will run tail log backup to capture all transactions that are not captured in
previous log backups at the point database was crashed.
 Restore last night Full backup with NORECOVERY that was taken at 8PM.
 Apply all transaction log backup since last night full backup with norecovery.
 Apply tail log backup on the database with recovery and with STOPAT parameter.

Question- Take the same scenario as above, now you found that there is one log
file let’s say at 2 PM got corrupted and not restorable. What will be the impact on
your database recovery?

Answer-  We cannot recover this database till that point it was crashed and we would
have last data till 1.30PM considering log backup runs on every half an hour.

Question- Suppose we are running Weekly Sunday full backup at 8PM, daily


differential backup at 10PM and every half an hour transaction log backup. Now
your database is crashed on Saturday 3.11PM. What would be your fastest way to
recover this database in point in time?

Answer-  We will perform below steps to recover this database in point-in-time:


1. Try to run tail log backup at the point database was crashed.
2. Restore latest Weekly Sunday Full backup with NORECOVERY that was taken at
8PM.
3. Restore Friday night differential backup with NORECOVERY that was taken at
10PM.
4. Apply all transaction log backup since Friday differential backup with
norecovery.
5. Apply tail log backup on the database with recovery and with STOPAT parameter.
Question- In addition to above question, suppose you came to know that Friday
night differential backup was corrupted then what would be your strategy to
recovery the database in point-in time?

Answer- We will perform below steps to recover this database in point-in-time:


1. Try to run tail log backup at the point database was crashed.
2. Restore latest Weekly Sunday Full backup with NORECOVERY that was taken at
8PM.
3. Restore Thursday night differential backup with NORECOVERY that was taken at
10PM.
4. Apply all transaction log backup since Thursday night differential backup with
norecovery.
5. Apply tail log backup on the database with recovery and with STOPAT parameter.

Question- Suppose you came to know that differential backups ran on Monday and
Wednesday are corrupted and you have only Tuesday and Thursday differential
backups along with full backup and all log backups. Explain your sequence to
restore the database?

Answer- We will follow same sequence that we follow in previous question. We will
apply weekly full backup then Thursday differential backup along with all transaction
log backups.

Question- How will you restore tempdb?

Answer- We should not restore tempdb as it’s a temporary database and created
everytime we restart SQL Server service.

Question- What is COPY_ONLY full backup and how it is different from regular full
backups?

Answer- Difference between regular full and copy-only full backup is that copy-only full
backup does not break the differential chain. Neither of them breaks the log chain as
neither of them truncates the log file. A copy-only backup cannot serve as a differential
base or differential backup and does not affect the differential base.

SYSTEM DATABASE

 What are the SQL Server system databases and can you outline the general
functionality of each database?

        Master - Database responsible for SQL Server instance related data.  You can also
think of this database corresponding to the Windows SQL Server service account.
       Resource - Database responsible for SQL Server system objects.  This database was
introduced in SQL Server 2005 and is intended to ease the upgrade and rollback of SQL
Server system objects.
       Model - Template database for the creation of new user defined databases.
       MSDB - Database responsible for SQL Server Agent related data such as Jobs, Alerts,
Operators, etc.
       TempDB - Temporary database to store temporary tables (#temptable or
##temptale), table variables, cursors, work tables, row versioning, create or rebuild
indexes sorted in TempDB, etc.  Each time the SQL Server instance is restarted all objects
in this database are destroyed, so permanent objects cannot be created in this database.
        Distribution - Database responsible for managing replicated data.  This database
could reside on the publisher or subscriber.

 True or False - Can you create objects in the Master, Model and MSDB databases?
        True.

 Is it a good idea to create objects in the system databases?

        In general , objects should not be created in the system databases.  In general, it is a
best practice to create a separate database for user defined objects that would be used
instance wide or create the objects in each of the needed databases.  From a DBA
perspective, it is a common practice to create a dedicated DBA database in order to
perform custom administrative tasks.
        If objects are needed for future user defined databases those can be created in the
Model database.

 Does Reporting Services create system databases during the installation process?
        Yes.  The databases are:
            ReportServer - Stores the reports related data.
            ReportServerTempDB - Temporary database storage for Reporting Services.

 Can you move system databases?


        Yes - Here are the key commands:
            Master - Configuration changes with a stop and restart to the SQL Server instance.
            Model - sp_detach_db and sp_attach_db
            MSDB - sp_detach_db and sp_attach_db
            TempDB - ALTER DATABASE command

Do users need explicit rights to the user defined databases?


        No - Rights are granted through the Public Role and Guest user.

What are the typical objects that are created in the TempDB database?
        Temporary tables (#temptable or ##temptale)
        Table variables
        Cursors
        Work tables
        Row versioning
        Create or rebuild indexes sorted in TempDB
 If the model database has the database recovery model set to full, what is the
impact?
        When new user defined databases are created, they will have a full recovery
model.  This means that transaction log backups will be needed to maintain a reasonably
sized transaction log.  If not the transaction logs will continue to grow indefinitely.

 Are all DTS packages stored in MSDB?  Are all SSIS Packages stored in MSDB?
        All DTS packages do not need to be stored in the MSDB database, but that was the
trend in SQL Server 2000.
        All SSIS Packages do not need to be stored in the MSDB database.  Storage on the file
system or in the MSDB database are more a matter of preference as opposed to an
industry trend thus far.

Does the size of the TempDB database really make a difference and how should
TempDB be sized?
        In situations where temporary objects are created in T-SQL code (i.e. temporary
tables (#temptable or ##temptale), table variables, cursors, work tables, row versioning,
create or rebuild indexes sorted in TempDB, etc.) the TempDB database makes a
significant difference in overall performance.  In these situations the database should be
sized appropriately and moved to a separate disk drive in order to support the IO
requests.  If not, the default location and size may be appriopriate.

 Are all SQL Server Agent configurations stored in the MSDB database?
        No - Some of the configurations are stored in the registry.

 Please explain the relationship between logins and users in the system and user
databases.
        Logins - All logins reside in the master database
        Users - All users reside in the master database, other system databases and in the
user defined databases.

  With the upgrade from SQL Server 2000 to SQL Server 2005, the system objects
changed.  Can you name three of the mapped objects between the two versions of
SQL Server?
        Here are three examples, but others do exist:
            System databases
                SQL Server 2000 - master.dbo.sysdatabases
                SQL Server 2005 - master.sys.databases
            Database files
                SQL Server 2000 - master.dbo.sysaltfiles
                SQL Server 2005 - master.sys.master_files
            IO Statistics
                SQL Server 2000 - fn_virtualfilestats
                SQL Server 2005 - sys.dm_io_virtual_file_stats
 Can you explain the differences in restoring the Master database versus a user
defined database?
        In order to restore the Master database the SQL Server instance must be in single
user mode. After the Master database is restored, the SQL Server instance restarts.
        A different set of restore errors may occur as compared to user defined
databases.  One example is if different databases exist from the backup to the current
time period, errors will be recorded related to suspect databases.

  What is the Resource database and in what version of SQL Server was it
introduced?
        The Resource database is responsible for physically storing all of the SQL Server
2005 system objects. This database has been created to improve the upgrade and
rollback of SQL Server system objects with the ability to overwrite only this database.

Is it important to take the system database backups?

Yes, It is very important to take system database backups except tempdb.

Is it possible to take the tempdb database backup?

No, it’s not possible to take tempdb backup and it’s not required.

How to restore model database?

model Databse can be restores same as any other user defined database from its backup.

RESTORE DATABASE [model] FROM  DISK = N'E:\model.bak'

WITH  FILE = 1, NOUNLOAD,  REPLACE,  STATS = 10

GO

How to restore msdb database?

 Stop SQL Server agent service


 Run the below command to restore the msdb database.

RESTORE DATABASE [msdb] FROM  DISK = N'E:\msdb.bak'

WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10


GO

 Start SQL Server agent service

How to restore master database?

 Start the SQL Server Instance in single user mode using –m parameter in the
SQL Server configuration manager for SQL Service.

Issue the below command from command prompt to restore the master

database. 

Is it possible to rename any of system databases?

No, it’s not possible to rename any system database.

What is the default owner of master, model, tempdb and msdb database? Is it possible to
change the owner of system databases?

Default owner of system databases is sa, We can’t change the default owner of master,
model, tempdb and distributor databases.

Restore a SQL Server Database to a Point in Time


Scripts used in video to Point in Time Restore of a SQL Server Database
USE [master] 
BACKUP LOG [SalesOrders] TO  DISK = N'C:\Program Files\Microsoft SQL Server\
MSSQL12.SQLPROD\MSSQL\Backup\SalesOrders_LogBackup_2015-03-03_18-52-
18.bak' WITH NOFORMAT, NOINIT,  
 NAME = N'SalesOrders_LogBackup_2015-03-03_18-52-18', 
 NOSKIP, NOREWIND, NOUNLOAD,
  NORECOVERY ,  STATS = 5
 RESTORE DATABASE [SalesOrders] FROM  DISK = N'C:\Program Files\Microsoft SQL
Server\MSSQL12.SQLPROD\MSSQL\Backup\Fullbackup603.bak'  
WITH  FILE = 1, NORECOVERY,  NOUNLOAD,  STATS = 5 

RESTORE DATABASE [SalesOrders] FROM  DISK = N'C:\Program Files\Microsoft SQL


Server\MSSQL12.SQLPROD\MSSQL\Backup\Diff605.bak' 
WITH  FILE = 1,
  NORECOVERY,  NOUNLOAD,  STATS = 5 

RESTORE LOG [SalesOrders] FROM  DISK = N'C:\Program Files\Microsoft SQL Server\


MSSQL12.SQLPROD\MSSQL\Backup\Tran606.trn' 
WITH  FILE = 1,  NOUNLOAD,  STATS = 5
GO

Cannot Open Backup Device 'BackupLocationPath' Operating system error


5Access is denied?

Resolution include following fixes,


1- check to see if backup folder exists or path is valid in backup location parameter
2- Finding out SQL Server Service Account
3- Check to see if SQL Server Service Account has proper access (read, write, modify) on
specified location
4- If job is running under proxy account, check to see if Proxy account has permission on
backup location same as above permissions.
5- If SQL Server Agent is running the job and it is T-SQL Script, it is more likely that your
SQL Server Service account doesn't have permission on backup location for Access
denied issue.

How to Restore MSDB Database


Script used in Video to Restore MSDB Database in SQL Server
USE [master]

ALTER DATABASE [msdb]

SET single_user WITH

ROLLBACK immediate

RESTORE DATABASE [msdb] FROM DISK = N'C:\SQLSysBackup\msdb.bak' WITH FILE =


1,
nounload, replace, stats = 5

ALTER DATABASE [msdb]


SET multi_user

go

How to Restore Master database


Restore DATABASE master From DISK='C:\SQLSystembackup\master.bak' WITH
REPLACE

How to move Tempdb data and Log Files


-- Current location of Tempdb
SELECT name, physical_name AS CurrentLocation
FROM sys.master_files
WHERE database_id = DB_ID(N'tempdb');
GO

--Move Tempdb Files


USE master
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdev, FILENAME = 'C:\SQLSysBackup\tempdb.mdf') -- New
Location DataFile
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = templog, FILENAME = 'C:\SQLSysBackup\templog.ldf')--New
Location LogFile
GO

SCENARIO BASED QUESTION DATABASES

How to Attach and Detach Databases


--Attach Script
USE [master]
GO
CREATE DATABASE [TestDB] ON ( FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL12.SQLPROD\MSSQL\DATA\TestDB.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.SQLPROD\MSSQL\
DATA\TestDB_log.ldf' )
FOR ATTACH
GO

--Detach Script
USE [master]
GO
ALTER DATABASE [SalesOrders] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

USE [master]
GO
EXEC MASTER.dbo.sp_detach_db @dbname = N'SalesOrders'
GO

How to Shrink Database And Database Files

-Shrink Database Script


USE [SalesOrders]
GO
DBCC SHRINKDATABASE(N'SalesOrders', 10 )
GO

--Shrink DB Files Scripts


USE [SalesOrders]
GO
DBCC SHRINKFILE (N'SalesOrders' , 3)
GO

How to Take Database Offline and Bring it Online

ALTER DATABASE [SalesOrders]
SET offline WITH ROLLBACK IMMEDIATE 
GO
ALTER DATABASE [SalesOrders] SET online;

How to create Database Snapshot

Create Snapshot

CREATE DATABASE SalesOrders_dbss ON( NAME = SalesOrders, FILENAME ='C:\
Program Files\Microsoft SQL Server\SalesOrdersCurrent.ss' )
AS SNAPSHOT OF [SalesOrders];
GO

Restore Snapshot Script

USE MASTER;
RESTORE DATABASE [SalesOrders] 
FROM DATABASE_SNAPSHOT = 'SalesOrders_dbss';
GO

How to Change Compatibility Level of a Database & Why Do We need to Do that in


SQL Server

Change Compatibility Level of a Database by using Script

USE [master]
GO
ALTER DATABASE [Demo] SET COMPATIBILITY_LEVEL = 120
GO

How to get Database out of Single User Mode

Change Database out of Single User Mode Script

--How to put Database in single user mode


USE [master]
GO
ALTER DATABASE [Demo] SET SINGLE_USER WITH rollback Immediate
GO
--How to put Database in multi user mode
USE [master]
GO
ALTER DATABASE [Demo] SET MULTI_USER WITH NO_WAIT
GO

How to Shrink MDF Database Data File of SQL Server

Script used to Shrink Data File in SQL Server

USE [Demo]
GO
DBCC SHRINKFILE (N'Demo' , 3)
GO

How to Rename a Database in SQL Server

If connections are open to Database you can use below script to kill the connections and
then rename.

USE MASTER
GO
DECLARE @DatabaseName AS VARCHAR(500)
-->Provide the DataBaseName for which want to Kill all processes.
SET @DatabaseName='YourDataBaseName'
DECLARE @Spid INT
DECLARE KillProcessCur CURSOR FOR
  SELECT spid
  FROM   sys.sysprocesses
  WHERE  DB_NAME(dbid) = @DatabaseName
OPEN KillProcessCur
FETCH Next FROM KillProcessCur INTO @Spid
WHILE @@FETCH_STATUS = 0
  BEGIN
      DECLARE @SQL VARCHAR(500)=NULL
      SET @SQL='Kill ' + CAST(@Spid AS VARCHAR(5))
      EXEC (@SQL)
      PRINT 'ProcessID =' + CAST(@Spid AS VARCHAR(5))
            + ' killed successfull'
      FETCH Next FROM KillProcessCur INTO @Spid
  END
CLOSE KillProcessCur
DEALLOCATE KillProcessCur

Rename DB by using TSQL Script

USE master;
GO
ALTER DATABASE [Demo]
Modify Name = Demo1
GO

How to Change Database Collation From Case Insensitive to Case Sensitive

Script to Change Collation of Database in SQL Server

USE [master]
GO
ALTER DATABASE [Demo] COLLATE SQL_Latin1_General_CP1_CS_AS
GO

How to Recover Suspect or Recovery Pending Databases in SQL Server.

Select name,state_desc from sys.databases

--Run this command to check what exactly is the issue for database being
recovery/suspect
DBCC CHECKDB(Demo) WITH NO_INFOMSGS

How to Find Out Owner of Any Database in SQL Server


--Finding owner of database using Store Procedure
sp_helpdb
--Finding out Owner of databse using sysdatabses system view
select name as DatabaseName,SUSER_SName(sid) as Database_Owner from
sysdatabases

--Where name = 'Your desired database name'

--Finding owner of database using sys.databases system view


Select name as DatabaseName, SUSER_SNAME(Owner_sid) as Database_Owner from
sys.databases
--Where name = 'Your desired database name'

How to Change the Ownership of a Database in SQL Server


Use Demo

--EXEC sp_changedbowner 'New Owner Login'


EXEC sp_changedbowner 'sa'

-- Changing database owner using Alter Authorization to Login [TECHBROTHERS\


clusteradmin]
ALTER AUTHORIZATION ON Database:: Demo TO [TECHBROTHERS\clusteradmin]

How to Avoid Using C drive for Database Create in SQL Server

USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\
MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\Data'
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\
MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'L:\Data'
GO

How to Reduce TempDB Size without Restarting SQL Server Services


USE [tempdb]
GO
--10 is desired size in MB, keep in mind that this size needs to be more than or equal to
minimum required
--size of tempdb, otherwise tempdb will not shrink
DBCC SHRINKFILE (N'tempdev' , 10)
How to Update Statistics (stats) of All the Databases or Single Database in SQL
Server
Script: Update statistics of All User Databases

use [SalesOrders]
GO
UPDATE STATISTICS [dbo].[Customers]
WITH FULLSCAN
GO

SECURITY

How to Create Windows Authentication Login in SQL Server

USE [master]
GO 
CREATE LOGIN [TECHBROTHERS\kscott] 
FROM WINDOWS  
WITH DEFAULT_DATABASE=[master]
GO

How to Create SQL Server Authenticated Login in SQL Server

 USE [master]
GO 
CREATE LOGIN [Techbrothers]  
WITH PASSWORD=N'Pa$$w0rd', 
 DEFAULT_DATABASE=[master],  
CHECK_EXPIRATION=OFF,  
CHECK_POLICY=OFF
How to Create Windows Group Authentication Login in SQL

USE [master]
GOCREATE LOGIN [TECHBROTHERS\SQLDBReader]  
FROM WINDOWS 
WITH DEFAULT_DATABASE=[master]
GO

How to Check Login Status in SQL Server

SELECT denylogin,hasaccess FROM syslogins 
WHERE name = 'Techbrothers'

How to Enable and Disable Login in SQL Server


--How to enable SQL Server Login
 USE [master]
GO 
GRANT CONNECT SQL TO [Techbrothers]
GO 
ALTER LOGIN [Techbrothers] ENABLE
GO
 -- How to disable SQL Server Login 
USE [master]
GO 
DENY CONNECT SQL TO [Techbrothers]
GO
 ALTER LOGIN [Techbrothers] DISABLE
GO
How to Create a Database User in SQL Server

USE [master]
GO 
CREATE LOGIN [TECHBROTHERS\
kscott] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
GO 
USE [SalesOrders]
GO 
CREATE USER [TECHBROTHERS\kscott] FOR LOGIN [TECHBROTHERS\kscott]
GO 
USE [SalesOrders]
GO
 ALTER ROLE [db_datareader] ADD MEMBER [TECHBROTHERS\kscott]
GO 

How to Map a User to an Existing Login in SQL Server

USE [SalesOrders]
GO 
CREATE USER [TECHBROTHERS\kscott] FOR LOGIN [TECHBROTHERS\kscott]
GO 
USE [SalesOrders]
GO 
ALTER ROLE [db_datareader] ADD MEMBER [TECHBROTHERS\kscott]
GO

How to Create User Define Schema in a Database in SQL Server

USE [SalesOrders]
GO 
CREATE SCHEMA [BKS] AUTHORIZATION [TECHBROTHERS\kscott]
GO  

How to Create Database Role in SQL Server

USE [SalesOrders]
GO 
CREATE ROLE [CustTableReader] AUTHORIZATION [TECHBROTHERS\kscott]
GO 
USE [SalesOrders]
GO 
ALTER AUTHORIZATION ON SCHEMA::[dbo] TO [CustTableReader]
GO 
USE [SalesOrders]
GO 
GRANT SELECT ON [dbo].[Customers] TO [CustTableReader]
GO 
USE [SalesOrders]
GO 
GRANT UPDATE ON [dbo].[Customers] TO [CustTableReader]
GO 
USE [SalesOrders]
GO
GRANT VIEW DEFINITION ON [dbo].[Customers] TO [CustTableReader]
GO

How to Create an Application Role in a Database of SQL Server

USE [SalesOrders]
GO 
CREATE APPLICATION ROLE
[AppReader] WITH DEFAULT_SCHEMA = [dbo], PASSWORD = N'Pa$$w0rd'GO 
USE [SalesOrders]
GO 
ALTER AUTHORIZATION ON SCHEMA::[db_datareader] TO [AppReader]
GO
 USE [SalesOrders]
GO 
GRANT SELECT ON [dbo].[Customers_3] TO [AppReader]
GO 
USE [SalesOrders]
GO
 GRANT UPDATE ON [dbo].[Customers_3] TO [AppReader]
GO 

How to Provide Explicit Permission to Specific Tables to a User in a database of


SQL Server

USE [SalesOrders]
GO
 GRANT SELECT ON [dbo].[Customers] TO [TECHBROTHERS\kscott]
GO
How to Provide Execute Permission to specific Store Procedures to a User in a
Database of SQL Server

USE [SalesOrders]
GO 
GRANT EXECUTE ON [dbo].[Proc_AllCustomer] TO [TECHBROTHERS\kscott]
GO

How to Provide View Definition Permission of Database Objects to a user in SQL


Server
USE [SalesOrders]
GO 
GRANT VIEW DEFINITION ON [dbo].[Customers] TO [TECHBROTHERS\kscott]
GO
 USE [SalesOrders]
GO
 GRANT VIEW DEFINITION ON [dbo].[Proc_AllCustomer] TO [TECHBROTHERS\kscott]
GO 
USE [SalesOrders]
GO 
GRANT VIEW DEFINITION ON [dbo].[Customers_2] TO [TECHBROTHERS\kscott]
GO

How to Assign Default Schema to AD Group in SQL Server


USE [Demo]
GO
CREATE SCHEMA [Myschema]
GO
--Create Login First and then go in Schema to Set Group default schema
USE [master]
GO
CREATE LOGIN [TECHBROTHERS\SQLDBReader] FROM WINDOWS WITH
DEFAULT_DATABASE=[master]
GO
Use [Demo]
ALTER AUTHORIZATION ON SCHEMA::[Myschema] TO [TECHBROTHERS\
SQLDBReader]
CONTAINED DATABASE

How to Create Contained Database User in SQL Server

USE [MYContainedDB]
GO
 CREATE USER [ContainedUser] WITH PASSWORD=N'Pa$$w0rd', 
 DEFAULT_SCHEMA=[dbo]
GO 
USE [MYContainedDB]
GO
 ALTER AUTHORIZATION ON SCHEMA::[db_owner] TO [ContainedUser]
GO 
USE [MYContainedDB]
GO 
ALTER ROLE [db_owner] ADD MEMBER [ContainedUser]
GO

Introduction to Extended Events 

How to Create an Extended Event in SQL Server


In this video you will learn how to create an Extended Event in SQL Server using SQL
Server Management studio as well as using T-SQL Script. It also shows step by step
process of creating a New Session, choosing events that you would like to capture,
filtering the events data (fields) and saving the output to a disk location. It also
demonstrates how to get list of Extended Events in SQL Server, how to watch Live Data
of a session, how to analyze captured data and how to start and stop a session in
extended events in SQL Server.

CREATE EVENT SESSION [DatabaseEvent] ON SERVER

ADD EVENT sqlserver.database_attached(


ACTION(sqlserver.database_name,sqlserver.nt_username,sqlserver.username)),
ADD EVENT sqlserver.database_created(
ACTION(sqlserver.database_name,sqlserver.nt_username,sqlserver.username)),
ADD EVENT sqlserver.database_detached(
ACTION(sqlserver.database_name,sqlserver.nt_username,sqlserver.username)),
ADD EVENT sqlserver.database_started(
ACTION(sqlserver.database_name,sqlserver.nt_username,sqlserver.username))
ADD TARGET package0.event_file(SET filename=N'C:\SQLSysBackup\
DatabaseEvents.xel')
WITH (STARTUP_STATE=OFF)
GO

How to Start or Enable and Stop or Disable Extended Event Session in SQL Server
--Stop event session
ALTER EVENT SESSION [DatabaseEvent] ON SERVER
STATE=STOP

--Start Event Session


ALTER EVENT SESSION [DatabaseEvent] ON SERVER
STATE=START
How can SQL Server instances be hidden?
 To hide a SQL Server instance, we need to make a change in SQL Server
Configuration Manager. To do this launch SQL Server Configuration Manager and
do the following: select the instance of SQL Server, right click and select
Properties. After selecting properties you will just set Hide Instance to "Yes" and
click OK or Apply. After the change is made, you need to restart the instance of
SQL Server to not expose the name of the instance.
What options are available to audit login activity?
 Custom solution with your application to log all logins into a centralized table
 Enable login auditing at the instance level in Management Studio
 Execute Profiler to capture logins into the instance
 Leverage a third party product
 What are some of the pros and cons of not dropping the SQL Server BUILTIN\
Administrators Group?
 Pros:
o Any Windows login in that group is by default a SQL Server system
administrator
o This single group can be used to manage administrators from a Windows
and SQL Server perspective
 Cons:
o Any Windows login is by default a SQL Server system administrator,
which may not be a desired situation
o SQL Server BUILTIN\Administrators Group has system administrator
rights by default
o SQL Server itself does not need to be hacked to gain access to your data, if
the Windows local administrators group is compromised then it is
possible to access SQL Server as a system administrator
 3) What’s the difference between Windows and Mixed mode?
Windows authentication mode requires users to provide a valid Windows
username and password to access the database server. In enterprise
environments, these credentials are normally Active Directory domain
credentials.
 Mixed authentication mode allows the use of Windows credentials but
supplements them with local SQL Server user accounts that the administrator
may create and maintain within SQL Server

Being a DBA which authentication mode you will prefer if you are asked to give an
advice for a new Application?
Windows authentication is definitely more secure as it’s controlled and authenticated
by Active Directory policies.

What are logins and users and its difference?


A login is the principal that is used to connect to the SQL Server instance. A user is the
principal that is used to connect to a database.
The security context on the instance itself is dictated by the login, it’s roles and the
permissions granted/denied. The security context on the database is dictated by the
user, it’s roles and the permissions granted/denied.

What is a Securable?
Securables are the resources to which the SQL Server Database Engine authorization
system regulates access. For example, a table is a securable. Some securables can be
contained within others, creating nested hierarchies called “scopes” that can themselves
be secured. The securable scopes are server, database, and schema.

What are Fixed Server roles and importance?


Bulk Admin: Members of this role can perform Bulk Insert operations on all the
databases.
DBCreator: Members of this role can Create/Alter/Drop/Restore a database.
Disk Admin: Members can manage disk files for the server and all databases. They can
handle backup devices.
Process Admin: Members of this role can manage and terminate the processes on the
SQL Server.
Server Admin: Members of this role can change Server-wide configurations and
shutdown SQL Server instance.
Setup Admin: Members of this role can Add/Remove Linked Servers.
Security Admin: Members of this role can create/manage Logins, including changing
and resetting passwords as needed, and managing GRANT, REVOKE and DENY
permissions at the server and database levels.
SysAdmin: Members of this role have Full Control on the instance and can perform any
task.
Public: Public is another role just like Fixed Server Roles, that is by default granted to
every login (Windows/SQL)

What are “View Server State”,”VIEW DATABASE STATE” permissions meant for?
Dynamic management views and functions return server state information that can be
used to monitor the health of a server instance, diagnose problems, and tune
performance.
There are two types of dynamic management views and functions:
Server-scoped dynamic management views and functions. These require VIEW SERVER
STATE permission on the server.
Database-scoped dynamic management views and functions. These require VIEW
DATABASE STATE permission on the database.

What are “View Definition” permissions?


The VIEW DEFINITION permission lets a user see the metadata of the securable on
which the permission is granted. However, VIEW DEFINITION permission does not
confer access to the securable itself. For example, a user that is granted only VIEW
DEFINITION permission on a table can see metadata related to the table in the
sys.objects catalog view. However, without additional permissions such as SELECT or
CONTROL, the user cannot read data from the table.
The VIEW DEFINITION permission can be granted on the following levels:
• Server scope
• Database scope
• Schema scope
• Individual entities

What is a guest account?


Guest user permits access to a database for any logins that are not mapped to a specific
database user. The guest user cannot be dropped but it can be disabled by revoking the
CONNECT permission. The recommendation is not valid for master, msdb and tempdb
system databases. If Guest user is disabled in msdb system database, it may cause some
issues. Distribution database is also system database and more information about the
Guest User in distribution database can be found below. It is recommended to disable
guest user in every database as a best practice for securing the SQL Server.

Is it possible to create new User Defined Server role in 2012 or not?


Yes, it is possible to create a Server role in SQL Server 2012.
What are the security related catalog views?
Server-Level Views
sys.server_permissions
sys.sql_logins
sys.server_principals
sys.server_role_members
Database-Level Views
sys.database_permissions
sys.database_role_members
sys.database_principals

What are the extra DB roles available in msdb?


SQL Server 2005 introduced the following msdb database fixed database roles, which
give administrators finer control over access to SQL Server Agent. The roles listed from
least to most privileged access are:
• SQLAgentUserRole
• SQLAgentReaderRole
• SQLAgentOperatorRole

Which one is highest privileged role out of SQLAgentUserRole,


SQLAgentReaderRole, SQLAgentOperatorRole?
SQLAgentOperatorRole is the most privileged of the SQL Server Agent fixed database
roles. It includes all the permissions of SQLAgentUserRole andSQLAgentReaderRole.
Members of this role can also view properties for operators and proxies, and enumerate
available proxies and alerts on the serve.

 What are Fixed Database Roles?


db_datareader: The db_datareader role has the ability to run a SELECT statement
against any table or view in the database.
db_datawriter: The db_datawriter role has the ability to modify via INSERT, UPDATE,
or DELETE data in any table or view in the database.
db_denydatareader: The db_denydatareader role is the exact opposite of the
db_datareader role: instead of granting SELECT permissions on any database object, the
db_denydatareader denies SELECT permissions.
db_denydatawriter: db_denydatawriter role serves to restrict permissions on a given
database. With this role, the user is preventing from modifying the data on any data via
an INSERT, UPDATE, or DELETE statement
db_accessadmin: The db_accessadmin fixed database role is akin to the securityadmin
fixed server role: it has the ability to add and remove users to the database.
The db_accessadmin role does not, however, have the ability to create or remove
database roles, nor does it have the ability to manage permissions.
Granted with GRANT option: CONNECT
db_securityadmin: The db_securityadmin role has rights to handle all permissions
within a database. The full list is:
DENY, GRANT, REVOKE, sp_addapprole, sp_addgroup, sp_addrole, sp_addrolemember,
sp_approlepassword, sp_changegroup, sp_changeobjectowner, sp_dropapprole,
sp_dropgroup, sp_droprole, sp_droprolemember

The list includes the DENY, GRANT, and REVOKE commands along with all the store
procedures for managing roles.
db_ddladmin: A user with the db_ddladmin fixed database role has rights to issue Data
Definition Language (DDL) statements in order to CREATE, DROP, or ALTER objects in
the database.
db_backupoperator: db_backupoperator has rights to create backups of a database.
Restore permissions are not granted, but only backups can be performed.
db_owner: Equal to a sysadmin at instance level, DB_OWNER can perform any task at
DB Level.
public: By default all the users in database level are granted Public Role.
What are Orphaned Users?
A database user for which the corresponding SQL Server login is undefined or is
incorrectly defined on a server instance cannot log in to the instance. Such a user is said
to be an orphaned user of the database on that server instance.
• A database user can become orphaned if the corresponding SQL Server login is
dropped.
• A database user can become orphaned after a database is restored or attached to a
different instance of SQL Server.
• Orphaning can happen if the database user is mapped to a SID that is not present in
the new server instance.

How to troubleshoot issues with the Orphaned users?


This will lists the orphaned users:

EXEC sp_change_users_login 'Report'


If you already have a login id and password for this user, fix it by doing:

EXEC sp_change_users_login 'Auto_Fix', 'user'


If you want to create a new login id and password for this user, fix it by doing:

EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'


How can SQL Server instances be hidden?
To hide an instance of the SQL Server Database Engine
1. In SQL Server Configuration Manager, expand SQL Server Network Configuration,
right-click Protocols for , and then select Properties.
2. On the Flags tab, in the HideInstance box, select Yes, and then click OK to close the
dialog box. The change takes effect immediately for new connections.

Being a DBA what all measures you will follow to make SQL SERVER more secure?
• When possible, use Windows Authentication logins instead of SQL Server logins
• Using server, database and application roles to control access to the data
• Using an un guessable SA password
• If possible, disable and rename the sa account
• Restricting physical access to the SQL Server
• Disabling the Guest account
• Minimize the number of sysadmins allowed to access SQL Server.
• Give users the least amount of permissions they need to perform their job.
• Use stored procedures or views to allow users to access data instead of letting them
directly access tables.
• Don’t grant permissions to the public database role.
• Remove user login IDs who no longer need access to SQL Server.
• Avoid creating network shares on any SQL Server.
• Turn on login auditing so you can see who has succeeded, and failed, to login.
• Ensure that your SQL Servers are behind a firewall and are not exposed directly to the
Internet.
• Do not use DBO users as application logins
• Firewall restrictions ensure that only the SQL Server listening port is available on the
database server.
• Apply the latest security updates / patches

What is Transparent Data Encryption?


Transparent Data Encryption (TDE) is a feature introduced in SQL Server 2008 and
available in later versions for bulk encryption at the database file level (data file, log file
and backup file) i.e. the entire database at rest. Once enabled for a database, this feature
encrypts data into pages before it is written to the disk and decrypts when read from
the disk. The best part of this feature is, as its name implies, it’s completely transparent
to your application. This means literally no application code changes (only
administrative change to enable it for a database) are required and hence no impact on
the application code\functionalities when enabling TDE on a database being referenced
by that application.
What is Service master key?
The Service Master Key is the root of the SQL Server encryption hierarchy. It is
generated automatically the first time it is needed to encrypt another key. By default,
the Service Master Key is encrypted using the Windows data protection API and using
the local machine key. The Service Master Key can only be opened by the Windows
service account under which it was created or by a principal with access to both the
service account name and its password.

What are the types of keys used in encryption?

Symmetric Key – In Symmetric cryptography system, the sender and the receiver of a
message share a single, common key that is used to encrypt and decrypt the message.
This is relatively easy to implement, and both the sender and the receiver can encrypt
or decrypt the messages.

Asymmetric Key – Asymmetric cryptography, also known as Public-key cryptography, is


a system in which the sender and the receiver of a message have a pair of cryptographic
keys – a public key and a private key – to encrypt and decrypt the message. This is a
relatively complex system where the sender can use his key to encrypt the message but
he cannot decrypt it. The receiver, on the other hand, can use his key to decrypt the
message but he cannot encrypt it. This intricacy has turned it into a resource-intensive
process.

How to take backup of the Service master key?

BACKUP SERVICE MASTER KEY TO FILE = 'path_to_file'

ENCRYPTION BY PASSWORD = 'password'


Is it possible to disable SA, how?
Disable the SA Login
Disabling the SA account is a good option to prevent its use. When it is disabled no one
can use it in any circumstance until it is enabled. The only disadvantage is that we can’t
use the SA account in an emergency. we can use the below T-SQL to disable SA account.
–Query to disable the SA account.

ALTER LOGIN sa DISABLE;


Is it possible to Rename the SA Login
Yes we can rename the SA account which will prevent hackers/users to some extent.
–Query to check account status

ALTER LOGIN sa WITH NAME = [newname];


Define SQL Server Surface Area Configuration Tool
SQL Server 2005 contains configuration tools such as a system stored procedure
calledsp_configure or SQL Server Surface Area Configuration tool (for services and
features) in order to enable/disable optional features as needed. Those features are
usually installed as disabled by default. Here is the list of the features that can be
enabled using the tool:
• xp_cmdshell
• SQL Server Web Assistant
• CLR Integration
• Ad hoc remote queries (the OPENROWSET and OPENDATASOURCE functions)
• OLE Automation system procedures
• System procedures for Database Mail and SQL Mail
• Remote use of a dedicated administrator connection

DR PLANS

What is SQL Server log shipping?

SQL Server log shipping is a technique which involves two or more SQL Server instances
and copying of a transaction log file from one SQL Server instance to another. The
process of transferring the transaction log files and restoring is automated across the
SQL Servers. As the process result there are two copies of the data on two separate
locations 

A log shipping session involves the following steps:

 Backing up the transaction log file on the primary SQL Server instance


 Copying the transaction log backup file across the network to one or
more secondary SQL Server instances
 Restoring the transaction log backup file on the secondary SQL Server instances

Log Shipping Minimum Requirements

1. SQL Server 2005 or later


2. Standard, Workgroup or Enterprise editions must be installed on all server
instances involved in log shipping.
3. The servers involved in log shipping should have the same case sensitivity
settings.
4. The database must use the full recovery or bulk-logged recovery model
5. A shared folder for copying T-Log backup files
6. SQL Server Agent Service must be configured properly

In addition, you should use the same version of SQL Server on both ends. It is possible to
Log Ship from SQL 2005 to SQL 2008, but you can not do it the opposite way. Also, since
Log Shipping will be primarily used for failover if you have the same versions on each
end and there is a need to failover you at least know you are running the same version
of SQL Server.

Implementation examples

One of the common log shipping scenarios is the environment with two servers
(SQLServer-1 – primaryand SQLServer-2 – secondary), two SQL Server instances
(SQLInstance-1 and SQLInstance-2), and one SQL Server database named SQLDB-1 with
log shipping running on it

Another common configuration is the environment with three (or more) servers
(SQLServer-1 – primary, SQLServer-2 – secondary, and SQLServer-3 – secondary),
three SQL Server instances (SQLInstance-1, SQLInstance-2, and SQLInstance-3), and one
SQL Server database named SQLDB-1 with log shipping running on it

Operating modes

There are two available modes and they are related to the state in which the secondary,
log shipped, SQL Server database will be:

 Standby mode – the database is available for querying and users can access it,
but in read-only mode
o The database is not available only while the restore process is running
 Users can be forced to disconnect when the restore job commence
 The restore job can be delayed until all users disconnect themselves
 Restore mode – the database is not accessible
How It Works
Log shipping implementation is straightforward:

1. Full backup of the database is taken on the primary server and copied to the
standby server.
2. Standby server maintains a copy of the database.
3. The database is not operational; it can stay in either read-only mode or no-recovery
mode.
4. Transaction log for the "log-shipped" database is backed up on the primary server
periodically. Note that only databases that are in FULL recovery mode can be log-
shipped.

Transaction log backups are placed on a shared drive; standby server's SQL Server
Agent account must have access to this shared drive.

5. Transaction log backups are copied to the standby server.


6. Transaction log backups are applied to the database on the standby server in the
order that they were taken on the primary server.
7. Either primary server, standby server, or a separate server can be used to monitor
log shipping. If you use a separate server for monitoring, it does NOT have to have
Enterprise Edition of SQL Server; any edition (other than MSDE) will do.

If the primary server becomes unavailable due to disk failure or some other reason, DBA
can take the following steps to fail the database over to the standby server:

1. Perform one last backup of the transaction log on the primary server (if possible).
2. Copy all transaction log backups to the standby server and apply them in the same
order they were taken on the primary server.

The last transaction log backup should be restored by using the WITH RECOVERY
clause so that the standby database becomes operational.

3. Transfer any logins that exist on the primary server to the standby server. Only the
logins that must have access to the log-shipped database must be transferred.

This step might be further complicated if logins with the same name exist on both
servers. In such cases, the DBA needs to ensure that appropriate mappings exist
between SQL Server logins and database users on the standby server.

During the initial configuration of log shipping, you can allow the standby database to
assume the primary role. That means you can ship transaction logs from the standby
server to the primary server after you have failed the primary database over. So if
primary server (server A) fails over to standby server (server B), servers can switch
roles so that you can fail server B back to server A if needed.

2. What is Log Shipping?

Log shipping is DR (disaster recovery) feature in SQL server where one or more than
one warm standby databases are maintained on separate secondary servers in case
Primary server is crashed,  secondary servers can be used to host the application. T-log
backup of Primary database is automatically shipped from primary server to secondary
servers and applied to secondary databases individually so that Primary and secondary
databases can be in SYNC.

3. How many server are used in Log Shipping?

1. Primary server: Primary database (Original) resides on Primary server


2. Secondary server: Copy of Primary database is maintained on secondary servers
3. Monitor server (Optional): Single Monitor server is used to monitor multiple log
shipping configurations among primary and secondary databases. This server is used to
keep the history and status of backup/restore operations. Monitor server also raise the
alert if Log shipping is out of SYNC and any Log shipping Job fails.

4. What are the Pre-requisite for Log-Shipping?

1. To set-up log shipping we must have SYSADMIN rights on the server


2. SQL server version should be SQL 2005 or later.
3. Database must be in FULL or BULK LOGGED recovery model so T-logs can be applied.
4. SQL Enterprise,Standard,Workgroup,Developer edition must installed on the servers
participating in log shipping.
5. Servers must have the same case sensitivity settings.
6. SQL server services on both Primary and secondary server should use the same
domain account.
7. Shared folder should be created in Primary server to hold the T-log backup. SQL
service account of primary should have Read/Write permission on the shared folder for
backup job to be successful. Agent account of secondary should have Read Permission
on the Shared folder of Primary server for copy job to be successful.
  
5. What recovery models are required to configure the Log Shipping?

Log shipping works with FULL and BULK LOGGED recovery model.

6. What are advantages of Log shipping?

1. Easily Configured. It can be configured using GUI wizard.


2. Log shipping doesn’t require expensive hardware that’s why most of corporate org
use it.
3. Low maintenance and very less troubleshooting is required for log shipping.
4. Secondary server can be used for reporting purpose to offload the primary server.
5. Manually fail-over process is very short, it takes around 10-15 minutes.
6. We can have multiple secondary databases which can be used for different purpose,
one server can be used for HA and another one for SQL server reporting.

7. What are Disadvantage of Log Shipping? 

1. No Automatic Fail-over: DBA needs to manually fail-over the server.


2. Downtime is required when there is fail-over.
3. Possible Data Loss: Some data can lost in case of server crash, it depends on schedule
of Log Shipping jobs.
4. Log shipping set-up cannot be scripted.
5. Each database which needs to be log shipped should be set up through separate Log
shipping Wizard.

8. Is it possible to configure Log Shipping from lower version to upper version and
Vice versa?

Yes, We can configure Log Shipping from lower to upper version. But it is not possible
vice versa.  Primary server can be SQL 2008 and secondary 2012 but opposite is not
possible.

9. What all jobs are created after configuring the Log Shipping?

when Log Shipping is configured, there are 4 jobs created between Primary Server and
Secondary  Server.
1. Backup job: This job is created on Primary Server and it performs the T-log backup
of the Database.
2. Copy Job: This job is created on Secondary Server and it Copies the transaction log
Backup from Primary Server to the Secondary Server.
3. Restore Job: This job is created on Secondary Server and it performs restore
operation on the Secondary Server.
4. Alert Job: If Monitor server is used an Alert Job is also created on Monitor server and
it raises alerts if any operation/Job is not completed successfully.

10. can we configure Log shipping between two database server which having
different collation?

No, We cannot configure Log shipping in this case.

11.Can we configure Log Shipping between different domain?

Yes, We can configure Log shipping between servers which are in different domain but
there must be Trust relationship between the domain.

12 If We create a user on the Primary database, will it automatically be created on


the secondary?

Yes, it will be created on the secondary database automatically as its a logged operation.
13. If we take the FULL backup of Primary database, Will it affect the Log
shipping?

No, Full backup will not disturb the Log shipping.

14. Will Manual T-log Backup break the Log Shipping?

Yes, Manual T-log Backup will break the LSN chain so Log shipping will not work. To
resume the Log shipping , we have to manually copy  and restore the T-log backup on
Secondary database.

15. If we create the Login in Primary server , will it automatically transferred to


Secondary server?

No, Login will not be transferred to secondary server. Log shipping works on Database
Level not on Instance Level.

16.If we add a data file on the Primary database in the same location which exists
on the target, will it automatically be created on the secondary?

Yes, data file will be created on Secondary server if the location is same.

17.If we add a data file in the Primary database in a location which does not exist
on the target, will it automatically be created on the secondary?

No, it will not be created on secondary server if disk layout is not same.Log shipping will
break in this case. we have to manually apply the T-log backup on secondary database
"WITH MOVE" option to resolve the issue.

18. Can We shrink log shipped database log file WITH TRUNCATE option?

No, We should not Shrink Log file WITH TRUNCATE option because it will disturb the
log shipping.We can shrink the log file but without TRUNCATE option.

19. Can we have Multiple secondary databases for a primary database in log
shipping?

 Yes, we can setup Multiple secondary databases for a primary database.

20. What is the best option to backup the Primary database when log shipping is
running?

 Database should be backed up with "COPY-ONLY"option ,it will never affect log
shipping.

21. Can we take the backup of Secondary database in log shipping?


No, we cannot backup secondary database in log shipping.

22. If We create any Job on Primary server, will it be created on secondary server?

No, Job will not be created on secondary server as Job is server Level Object.

23 What is .TUF file in log shipping?

TUF file is known as "Transaction Undo File". TUF file is created when we configure Log
shipping in STAND-BY mode.The transaction undo file contains Transaction that were
not committed on the source database but were in progress when the transaction log
was backed up.while restoring the log backup, uncommitted transactions will be saved
into the undo file and only committed transactions will be written to disk making users
to read the database. When you restore next log backup SQL server will get the
uncommitted transactions from tuf file and check with the new log backup whether the
Transaction is committed or not. If its committed the transactions will be written to disk
else it will be stored in .tuf file until it gets committed or rolled-back.

24. What will happen if .TUF file is corrupted or deleted?

In such case Log Shipping will break, and we have to re-configure the log shipping.

25. What is .WRK file in Log Shipping?

When .trn files are copied from Primary server to Secondary server, an
intermediate .WRK files temporarily generated and when T-log backup file copied
completely at secondary server, they renamed to the .trn extension. The temporary
naming using the .wrk extension ensures that the files will not picked up by the restore
job until .trn file successfully copied.

26. What is STANDBY Mode in log shipping?

We can offload our primary database by using secondary server for read-only query
processing and Reporting.for this purpose secondary database must be in STANDBY
mode.

27. Types of mode in SQL Log shipping?

Two modes are used in log shipping:


1. No-Recovery- No user access is given to the secondary database and the database
will be in Restoring state so the database does not have to care about uncommitted
transactions.
2. STANDBY - secondary database can be used for Read-only purpose and .TUF file is
used to contain the uncommitted transactions.

28. Switch-over the Log shipping Roles?


1. Disable the "BACKUP" Job on Primary server.
2. Go to Secondary server and Run the "COPY" Job so any remaining T-log backup copied
to secondary server from Primary.
3. Run the "Restore" Job to restore those remaining T-LOG Backups.Now Secondary
database is Up to date with Primary.
4. Disable "COPY" and "RESTORE" jobs.
5. Go to Primary database and Take Last T-Log Backup with NORECOVERY clause, it will
left the Primary database in restoring state.
Backup Log DB_Name to disk='\\Seondary_server_UNC_Path\
DB_Name_Norecovery.trn' with Norecovery
6. Go to secondary Server and restore last T-log backup with Recovery clause, it will
bring the secondary database online.
Restore log DB_Name From disk='\\Seondary_server_UNC_Path\
DB_Name_Norecovery.trn' with Recovery.
7. Now set-up the Log Shipping(from Secondary database that has become Primary
now) and we don't need to initialize the Secondary database(Prior it was Primary) as its
already in Restoring state.
8. Once the Log Shipping Set-up is completed, We can delete the Original Log Shipping
disabled Jobs from Primary and secondary servers.
9. we have successfully Switched over the Role, Primary has become secondary and
Secondary become Primary.

29. We configured Log Shipping in standby mode, but restore job failed with
below error:"Could Not apply log backup,Exclusive access could not be obtained
because the database is in use".
How to rectify the issue?

To restore T-log backup on the database, SQL Server needs exclusive access on the
database.
When we configure Log shipping in standby mode, users will be able to access the
database and can execute Read only queries against the secondary database.
Hence If the scheduled restore job runs at particular time interval, the database will
have a lock and it won’t allow SQL Server to restore the T-logs.
To Prevent this error we need to check “Disconnect users in the database when
restoring backups” options in log shipping configuration wizard.

  How to failover secondary server, when the Primary Server fails?


If the Primary Server will become un-available, do the following steps.
a)    Take the Tail of Log from Primary server if possible.
b)    Restore Tail of log into all Secondary Database
c)     Remove Log-shipping configuration from Primary Server
d)    Select any one of Secondary server and bring into online with Alter Database DBName set Online
e)    Right click on Primary Database and Generate script for Users and Logins.
f)     Then move the script to Secondary server to create Users and Logins
g)    Re-configure log shipping from New Server (Secondary server)

What are errors occurred in Log shipping?


There are two errors are occurred during Log shipping
1)    14420:- This error occurs when the Backup job fails
2)    14421:- This error occurs when the Restoring job fails
 Where you monitoring Log shipping and how?
The following methods can use for monitoring Log shipping.
a)  Monitor server (History Tables):- Monitor Server tracks all statistics, status and errors that could be
happen during Log shipping.
1)  Log_shipping_monitor_primary:- Stores primary server status
2)  Log_shipping_monitor_secondary:- Stores secondary servers status
3)  Log_shipping_monitor_history_detail:- Contains history details for logshipping agents.
4)  Log_shipping_monitor_error_detail:- Stores error details for log shipping jobs.
5)  Log_shipping_monitor_alert:- Stores Alert Job ID
b)  System Stored Procedures (MSDB):- System Stored procedures gives the history information about the
specified server that are configured in Log shipping.
1)  sp_help_log_shipping_monitor (Run at Monitor Server)
2)  sp_help_log_shipping_monitor_primary @Primary_Database = ‘DBName’ (Run at MS)
3)  sp_help_log_shipping_monitor_secondary @ Secondary_Database = ‘DBName’ (Run at MS)
4)  sp_help_log_shipping_alert_job (Run at Mon Server)
5)  sp_help_log_shipping_primary_database @ Database = ‘DBName’ (Run at Primary Server)
6)  sp_help_log_shipping_secondary_database @ Database = ‘DBName’ (Run at Sec Server)
c)   Transaction Log shipping Status report (Summary Reports):-  This report shows the status of log
shipping configurations for which this server instance is a primary, secondary or monitor.
d)  SQL Server Agent Job Histor:- Right click on Jobs > View history
e)  Checking the SQL Server Log

Mirroring

What is SQL Server database mirroring?


SQL Server database mirroring is a disaster recovery and high availability technique that involves
two SQL Server instances on the same or different machines. One SQL Server instance acts as a
primary instance called the principal, while the other is a mirrored instance called the mirror. In
special cases, there can be a third SQL Server instance that acts as a witness

Implementation examples
One of the common mirroring configuration is the environment with two SQL Servers (SQLServer-1
and SQLServer-2), two instances (SQLInstance-1 and SQLInstance-2), and one mirrored database
named SQLDB-1
The second common configuration is the environment with one SQL Server machine, two SQL Server
instances, and one mirrored database named SQLDB-1. This solution has a major flaw because if
SQLServer-1 goes down, both instances will be unavailable

Operating modes
SQL Server database mirroring can be set to provide high availability or disaster recovery.
Depending on the needs, a DBA can choose among three available modes

 High safety – Data is written and committed on the principal and mirror databases
synchronously. Only after committing on both databases, the database application can
continue with activity
o Might produce delay and slower operation because transactions must be committed on both
databases
o If the principal database goes down, two options are available:
 Do nothing – wait for the principal to become available again. During that time, the SQL
Server instance is unavailable. Mirroring will continue where it has stopped
 Force the SQL Server instance on the mirror database – the mirror database becomes the
principal. Possible data loss due to committed transactions on the original principal
database which are not yet committed on the mirror currently acting as the principal
 High safety with automatic failover – Three servers are necessary. Data is written and
must be committed synchronously both on the principal and mirror databases. Only after
committing on both databases, the application can continue running
o Might produce delay and slower operation because transactions must be committed on both
databases
o If the principal database goes down, only one option is available:
 Let the automatic failover process complete, the mirrored database becomes the principal
 High performance – the asynchronous communication, data is written and committed on
the principal server, and later sent and committed to the mirror server. Automatic failover
isn’t possible and the witness server can’t be used
o The high performance mode is only available in the Enterprise edition of SQL Server
o If the principal database goes down, three options are available:
 Do nothing – wait for the principal to become available again. The SQL Server is unavailable.
Mirroring will continue where it has stopped
 Force the SQL Server instance on the mirror database – the mirror database becomes the
principal. Greater possibility for data loss, due to asynchronous communication between
databases
 Manual update – to reduce data loss, take the tail of the log backup if the failed server allows,
remove mirroring and restore the tail of the log on the previously mirrored database

Q: Database Mirroring comes with which edition?


Ans: SQL Server 2005 SP1. Or SQL Server 2005 RTM with trace flag 1400

Q: How to enable mirroring by Script ? 

Ans: – Specify the partner from the mirror server

ALTER DATABASE [AdventureWorks] SET PARTNER = N‘TCP://A.corp.mycompany.com:5022';

– Specify the partner from the principal server

ALTER DATABASE [AdventureWorks] SET PARTNER = N‘TCP://B.corp.mycompany.com:5022';

Note: Replace the dbname before using the above script  Q: How to disable mirroring by
script? Ans: ALTER DATABASE [AdventureWorks] SET PARTNER OFF 

Note: Replace the dbname before using the above script

Q: How to do manual failover to Mirror when principle is working fine?


Ans: ALTER DATABASE <DB Name> SET PARTNER FAILOVER

Q: Why I’m getting the below error message while configuring database mirroring?
Msg 1416, Level 16, State 31, Line 3. Database is not configured for database mirroring
Ans : You need to restore the Full backup from principal server using With NoRecovery option
and also one transactional log backup from principal server using With NoRecovery option and
then start configuring mirroring.

Q: Can we configure mirroring between Standard Edition & Enterprise Edition or Vice
Versa? 
Ans: Nope its not possible, both principal and mirror should have same edition

Q: Is it possible to take backup of mirrored database in mirror server?


Ans: No

Q: Is it possible to perform readonly operation at mirrored database in mirror server?


Ans: Yes, You can create database snapshot for the same

Q: How can I increase Heartbeat time between principal and mirror server?? By default
its 10 sec.

Ans: ALTER DATABASE AdventureWorks SET PARTNER TIMEOUT 30

Q: What status of mirroring has if secondary is down?


Ans: If secondary is down principle or Mirror show status disconnected

Q: What status of mirroring has if principle is down?


Ans: If principle is down mirror will be disconnected with in recovery instead of synchronized
with restoring

Q: What status of mirroring has if mirroring is paused?

Ans: Is mirroring is set to paused from principle then then both principle & mirror in
suspending  

Q: System Store Procedure to monitor Mirroring?

Ans: MSDB.SYS.SP_DBMMONITORRESULTS 

Q: What are different possible Mirroring Stats?

SYNCHRONIZING

SYNCHRONIZED

SUSPENDED

PENDING FAILOVER

DISCONNECTED 

Q: Can I create multiple endpoints for configuring different databases for mirroring and
point each database to unique endpoint.

Ans: No 

Q: Can we configure mirroring between 32 and 64 bit machine?

Q: Can Log Shipping and mirroring configure together?


Q: Can we renamed mirrored database?

Q: Is drive letter required to be same on both the server?

Q: If drive letter is different on both the server. Then what is the steps to add a new
datafile?

Q: Can we have different collation setting on both the database

Q: What is different role switching is available?

Q: What is hot standby and warm standby server?

Q: Please explain how log transmission and transaction commits work in high
performance mode and in high safety mode?

Q: What is SQL query to set/change operating mode?

Q: Can we configure mirroring without setting up endpoints?

Q: Suppose your table size is of 300 GB and you have to rebuild it. Tell me Q: what is the
precautionary step you will take so that your mirroring should not be effected?

Q: What is the step to move datafile in mirroring? Please step out every steps?

Q: What will happen if I delete any datafile on principle server? Will it affect mirroring
session?

Q: Quorum types in Mirroring?

A Quorum is the relationship between the Witness,Principal and the Mirror.Depending on the
mode of operation it is divided into 3.

Full Quorum —>This is when all 3 Witness,Principal and the Mirror can communicate with
each other.Since witness is present automatic failover occurs.

Quorum —>This state exist if the Witness and either partner can communicate with it.

Partner-to-Partner —>When only the Principal and Mirror can communicate with each other.

Q: What are the requirements for setting up database mirroring? Additional  

Q: can you mix versions in mirroring (e.g. 2005 and 2000)?


A Requirements for database mirroring:

1.   Principal and mirror are running SQL Server 2005 or newer (Standard or Enterprise Edition).

2.   Principal and mirror have enough space for the database.

3.   For automatic failover, witness must be running.

4.   Principal database must be in FULL recovery model.

5.   Mirror database must be prepared prior to mirroring setup - one full backup and one transaction
log backup need to be taken on principal and restored WITH NORECOVERY on mirror.

A to additional Q: yes, but principal has to be earlier then mirror, for example 2005 -> 2008. SQL
Server 2000 does not support database mirroring at all.

Q: What is the endpoint in Mirroring?

Endpoint: An endpoint is a SQL Server object that enables SQL Server to communicate over the
network. It encapsulates a transport protocol and a port number.

An endpoint is a network protocol which is used to communicate Principal, Mirror and Witness
servers over the network.

Creation of an end point:-

Create endpoint <endpoint name> State=started/stopped/disabled

as tcp (listener port=5022/5023) for database_mirroring (role=partner/witness) 

Q: What are the Operating Modes and explain them? a. High


Availability (principle+mirror+witness) :- High-availability mode, runs synchronously.
Requires a Witness Server instance. The Principal server sends the log buffer to the mirror
server, and then waits for a response from the mirror server.
principle is not available the witness and mirror will decide automatic failover .mirror becomes
online.
b. High Protection (princeiple+mirror):- High-protection mode, runs synchronously. Always
commit changes at both the Principal and Mirror. automatic failover is not possible.
c. High Performance:- High-performance mode, runs asynchronously and the transaction
safety set to off. The Principal server does not wait for a response from the mirror server after
sending the log buffer. The principal server running nice and fast, but could lose data on the
mirror server.

Q: Mirroring configuration steps?

Configuring Mirroring – Steps

1.       Configuring security and communication between instances

a.       Configuring endpoint

b.       Creating logins for other servers service accounts

c.       Grant connect permission to this logins on endpoints

2.       Create mirror database

a.       Take full and T.Log backup from principle server and restore it in mirror server with

          NORECOVERY.

3.       Establish mirroring session using ALTER DATABASE command

Default port no is

5022 is default port number for mirroring in sql server

Q: Monitoring Mirroring?

Using Database Mirroring Monitor

We can monitor the following features

·         Unsent Log     (at principal)

·         Un restored Log (at mirror)

·         Transaction Rate

·         Commit Overhead (Transactions applied rate at mirror)  


Q: How to set Automatic failover timeout?

The default timeout for communication between the principal, mirror, and witness servers is 10
seconds.

Adjusting the automatic failover time for SQL Server Database Mirroring

ALTER DATABASE dbName SET PARTNER TIMEOUT 20 

Q: How to do manual failover?

To perform a manual failover

ALTER DATABASE AdventureWorks SET PARTNER FAILOVER; 

Q: Pausing or Removing Database Mirroring?

To pause the database mirroring session

ALTER DATABASE AdventureWorks SET PARTNER SUSPEND;

To resume the database mirroring session

ALTER DATABASE AdventureWorks SET PARTNER RESUME;

To remove the database mirroring session

ALTER DATABASE AdventureWorks SET PARTNER OFF; 

Q: What are the major new features introduced in Mirroring 2008 version?

1. Auto Page Repair.

Select * from sys.dm_db_mirroring_auto_page_repair


2. Transactions are sending to Mirror by compressing.

To view total bytes send from principal and total bytes received at mirror we can use (run in
witness server)

Select * from sys.dm_db_mirroring_connections   

Q: Counters required to monitor Mirroring performance?

Monitoring database mirroring performance

To monitor the performance of database mirroring, SQL Server provides a System Monitor
performance object (SQLServer:Database Mirroring) on each partner (principal and mirror).
The Databases performance object provides some important information as well, such as
throughput information (Transactions/sec counter). Following are the important counters to
watch.

On the principal:

·  Log Bytes Sent/sec: Number of bytes of the log sent to the mirror per second.

·  Log Send Queue KB: Total kilobytes of the log that have not yet been sent to the mirror
server.

· Transaction Delay: Delay (in milliseconds) in waiting for commit acknowledgement from the
mirror. This counters reports the total delay for all the transactions in process at that time. To
determine the average delay per transaction, divide this counter by
the Transactions/sec counter. When running asynchronous mirroring this counter will always
be 0.

· Transactions/sec: The transaction throughput of the database.This counter is in


the Databases performance object.

·  Log Bytes Flushed/sec: The rate at which log records are written to the disk. This is the log
generation rate of the application. It plays a very important role in determining database
mirroring performance.This counter is in the Databases performance object.

·  Disk Write Bytes/sec: The rate at which the disk is written to. This counter is in the Logical
Disk performance object and represents. Monitor this counter for the data as well as the log
disks.

On the mirror:
· Redo Bytes/sec: Number of bytes of the transaction log applied on the mirror database per
second.

· Redo Queue KB: Total kilobytes of hardened log that remain to be applied to the mirror
database to roll it forward.

· Disk Write Bytes/sec: The rate at which the disk is written to. This counter is in the Logical
Disk performance object and represents. Monitor this counter for the data as well as the log
disks on the mirror. 

Q: Mirroring Requirements?

·         SQL Server 2005 with SP1 or SQL Server 2008

·         Database should be in FULL recovery model.

·         Service Broker should be enabled on the database.

·         Both the servers should have either Enterprise or standard editions.

·         Both the servers should have same edition.

·         Witness server can have any edition.

·         Database name should be same

·         Collation should be same

·         You can’t mirror more than 10 db in 32 bit server, because an instance can only have one end
point which could be a bottle neck if there are lots of db’s in that instances.

·         You cant attach or detach

·         Mirroring Ports should be open and functionable

·         Service Account should be same  for sql and sql agent on Instance

·         Cross DB transactions and distributed transactions not permitted. 

Q: How many Databases can configure Mirroring?

can't configure more than 10 DB's on 32 bit but we can on 64 Bit.  But not recommended. 

Q: Can we configure mirroring on different domain.


Yes. both domain's should be trust each other.

Q: What is cross db transaction and distributed transaction.  

Q: can we configure mirroring on difference SQL Service packs.

Yes(build no should be same. 

Q: Advantages of Mirroring?

 Hardware or software upgrades can be simplified.


 It increases the data protection(disaster recovery).
 Increases the database availability on syn mode.
 Cost of DB mirroring less compare to clustering.
 It is robust and efficient than log shipping and replication.
 It support the full text.
 Failover is fast compare to cluster.
 Mirror server can be used to host databases for other application
Q: Disadvantages

 Does not support filestream.


 potential loss of data in async mode(high performance).
 Mirror server is not available for read-only purpose.
 It works at the database level, not at the server level.
 Multiple database fail-over.
 Q: Enhancements in 2008
 Automatic page repair(823,824,829 page errors).
 compression of mirroring data stream.
 Log send buffers - efficient use
 Write-ahead event enhanced in 2008
 Page read-ahead during the undo phase
Q: What is the page error's in mirroring

Automatic page repair(823,824,829 page errors).

 823 syclic redendancy failure

 824 logical errors

 825 restore pending

Data page read error in principal then entry in suspect pages table in msdb db for the particler
page. page is marked as restore pending making it in accessible to application queries. mirror
state is suspended till recover the page.

Can check suspect pages:


SELECT * FROM msdb..suspect_pages;

Q: What is the default of end points (port numbers) of principal, mirror and witness
servers? How to find the Port numbers?

The default port numbers of principal, mirror and Witness servers are 5022, 5023 and 5024.

To Find Port Number:- SELECT name, port FROM sys.tcp_endpoints.

Q: Trace flags are used to temporarily set specific server characteristics or to switch
off/on a particular behavior. 1400 Trace flag is used in mirroring.
To set trace flag for Database mirroring:- Configuration Manager > Right click on server instance
> Properties > Advanced tab > Startup parameters > -t1400 (add).

Q: How to monitoring Mirroring?

There are six methods are available for monitoring the Database Mirroring

a) Database Mirroring Monitor:- Database Mirroring Monitor is a GUI tool that shows update
status and to configure warning thresholds.

To open DM Monitor:- Right click on Principal Database > Tasks > Select Launch Database
Mirroring Monitor.

b) SQL Server Management Studio:- A green arrow on the mirror server is indicates running
well. A red arrow indicates problems that need to investigate.

c) SQL Server Log:- It provides information of Mirroring establishment and status. If any errors
occurs it will be logged to SQL Server log and Windows event log.

d) Performance Monitor:- It can provides real-time information about Database mirroring. We


can use performance counters to get status of the database mirroring such as Bytes
received/sec, Bytes sent/sec, Transaction delay etc.

e) Profiler:- Profiler many events are providing the status of the Database mirroring

f) System Stored Procedures:-

⦁ sp_dbmmonitoraddmonitoring

⦁ sp_dbmmonitorchangemonitoring

⦁ sp_dbmmonitorhelpmonitoring

⦁ sp_dbmmonitordropmonitoring

Q: What is Hardening?

As quickly as possible, the log buffer is written to the transaction log on disk, a process called
hardening.

Q: What is Log buffer?


A log buffer is a special location in memory (RAM). SQL Server stores the changes in the
database’s log buffer.

Q: How to Setup Fully Qualified Names for Database Mirroring?

I. FQDN Error

One or more of the server network addresses lacks a fully qualified domain name (FQDN).
Specify the FQDN for each server, and click Start Mirroring again.

The syntax for a fully-qualified TCP address is:

TCP://<computer_name>.<domain_segment>[.<domain_segment>]:<port>

Section 1.01

Section 1.02 II. RECTIFYING FULLY QUALIFYED NAMES

1) To View Endpoints:-SELECT * FROM sys.database_mirroring_endpoints;

2) Remove existing all Endpoints from Principal, Mirror and Witness servers :- DROP
ENDPOINT [ENDPOINT_NAME]

3) Adding "local" as the primary DNS suffix as follows:-

a) Right-click My Computer, and then click Properties. The System Properties dialog box will
appear.

b) Click the Computer Name tab.

c) Click Change. The Computer Name Changes dialog box will appear.

d) Click More. The DNS Suffix and NetBIOS Computer Name dialog box will appear.

e) Enter the appropriate DNS suffix for the domain.

f) Select the Change primary DNS suffix when domain membership changes check box.

g) Click OK to save the changes, and then click OK to exit the Computer Name Changes dialog
box.

h) Click OK to close the System Properties dialog box, and then restart the computer for the
change to take effect.

4) Reconfigure the Database mirroring either GUI or T-SQL

Q: Database mirroring is disabled by default. Database mirroring is currently provided


for evaluation purposes only and is not to be used in production environments. To enable
database mirroring for evaluation purposes, use trace flag 1400 during startup. For more
information about trace flags and startup options, see SQL Server Books Online.
(Microsoft SQL Server, Error: 1498)

Answer:
This is a common error & everyone is know to this error. Database mirroring is officially
supported from SQL Server 2005 SP1, hence in the RTM version database mirroring is disabled
by default. You can use TRACE 1400 to enable in RTM version or else update your SQL Server
with latest service pack.

Adding Trace Flag to Startup parameter

 Goto RUN --> Type sqlservermanager.msc


 Right click on SQL Server(instancename) service and click on properties
 Click on Advanced tab
 In the startup parameters enter this ;-T1400 and click on OK
 Restart SQLservices and then try configuring db mirroring
Or

 Update SQL Server to latest service pack.

What are the Mirroring modes

Table 13-11 summarizes the different database mirroring modes and the pros/cons for each of the
modes.

Synchronous Witness
Mode Name Pro/Con
or Async present?

Supports automatic failover and is the most hardened. If


High- mirror disappears but principal and witness are connected,
Synchronous Yes
Availability operations   continue. Mirror catches up when it comes back
online.

High- automatic failover and if mirror unavailable, principal


Synchronous No
Protection database goes offline.

Fast performance but data not guaranteed on the other side


High- and no automatic failover. Useful for low-bandwidth
Asynchronous Yes
Performance connections between mirror and principal since performance
is best.

What are the Mirroring States?


PRINCIPAL MIRROR Discription

RESTORING

IN RECOVERY WHILE CONFIGURING

HIGH SAFETY WITH AUTOMATIC


Principal syncronized Mirror syncronized/restoring
FAILOVER

Principal suspended Mirror suspended/restoring If Paused principal

Mirror syncronized/restoring Principal syncronized Principal Failover

Mirroring States:

SYNCHRONIZING: Indicates that the mirror database is trying to catch up with the principal database.
This is typically seen when you just start database mirroring or in high-performance mode.

SUSPENDED: Indicates that the mirror database is not available. During this time the principal is referred
to as running exposed, as it is processing transactions but not sending any transaction log records to the
mirror.

PENDING_FAILOVER: Indicates the state that the principal goes through before transitioning to the
mirror role.

DISCONNECTED: Indicates that the partners are unable to communicate with each other.

Operating Modes in Mirroring?

Database Mirroring Operating Modes

Transaction Transfer Quorum Witness


Operating Mode Failover Type
safety mechanism required server

Automatic or
High Availability FULL Synchronous Y Y
Manual

High Protection FULL Synchronous Y N Manual only

High OFF Asynchronous N N/A Forced only


Performance
Mirror Monitoring

The following query returns the descriptions for basic database mirroring session information
about either the principal or the mirror.
SELECT
      DB_NAME(database_id) AS 'DatabaseName'

    , mirroring_role_desc

    , mirroring_safety_level_desc

    , mirroring_state_desc

    , mirroring_safety_sequence

    , mirroring_role_sequence

    , mirroring_partner_instance

    , mirroring_witness_name

    , mirroring_witness_state_desc

    , mirroring_failover_lsn

FROM sys.database_mirroring

WHERE mirroring_guid IS NOT NULL;

The following is an analogous query returns relevant descriptive session information about the
witness server that you run on the witness.
SELECT 

      Database_name

    , safety_level_desc

    , safety_sequence_number

    , role_sequence_number

    , is_suspended

    , is_suspended_sequence_number

    , principal_server_name

    , mirror_server_name

FROM sys.database_mirroring_witnesses;
MIRRORING

You might also like