SQL Server Database Administartion
SQL Server Database Administartion
SQL Server Database Administartion
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.
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
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.
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.
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.
To DISK='f:\PowerSQL\SQLShackDemoATC_1.BAK'
WITH COPY_ONLY,
MEDIANAME = 'Native_SQLServerFullBackup',
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.
SQLShackPartialBackup is the database created with primary and secondary file groups.
Let’s use this database for this demo.
( NAME = N'SQLShackPartialBackup_1',
FILENAME = N'f:\PowerSQL\SQLShackPartialBackup_1.mdf' ,
FILEGROUP [Secondary]
( NAME = N'SQLShackPartialBackup_2',
FILENAME = N'f:\PowerSQL\SQLShackPartialBackup_2.mdf' ,
LOG ON
( NAME = N'SQLShackPartialBackup_Log',
FILENAME = N'f:\PowerSQL\SQLShackPartialBackup_log.ldf' ,
GO
Let’s change the recovery model of the database to SIMPLE using the following
ALTER statement
TO DISK = N'f:\PowerSQL\SQLShackPartialBackup_Full.bak'
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.
( NAME = N'SQLShackFileBackup_1',
FILENAME = N'f:\PowerSQL\SQLShackFileBackup_1.mdf' ,
FILEGROUP [Secondary]
( NAME = N'SQLShackFileBackup_2',
FILENAME = N'f:\PowerSQL\SQLShackFileBackup_2.ndf' ,
LOG ON
( NAME = N'SQLShackFileBackup_Log',
FILENAME = N'f:\PowerSQL\SQLShackFileBackup_Log.ldf' ,
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.
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.
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.
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.
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 FROM DISK = 'C:\AdventureWorks.BAK'
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
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 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:
In this blog, we are going to discuss about all these states in detail.
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:
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.
TIP: With help of following command, one can recover a database, which is in restoring
state:
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.
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.
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.
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.
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
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
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
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.
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.
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
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?
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
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.
Data File:
1. Check error log. If error number is 17204(data file was damaged)
2. Take tail log backup using
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
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
Recovery Models:
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?
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.
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.
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.
FROM partial_backup
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.
What are the important points which need to be taken care when we restore the
database from lower version to upper version?
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?
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.
Question- If yes in above question then how is SIMPLE RECOVERY Model different
from FULL 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.
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.
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?
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 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.
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.
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.
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.
No, it’s not possible to take tempdb backup and it’s not required.
model Databse can be restores same as any other user defined database from its backup.
GO
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.
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.
ROLLBACK immediate
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
ALTER DATABASE [SalesOrders]
SET offline WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE [SalesOrders] SET online;
Create Snapshot
CREATE DATABASE SalesOrders_dbss ON( NAME = SalesOrders, FILENAME ='C:\
Program Files\Microsoft SQL Server\SalesOrdersCurrent.ss' )
AS SNAPSHOT OF [SalesOrders];
GO
USE MASTER;
RESTORE DATABASE [SalesOrders]
FROM DATABASE_SNAPSHOT = 'SalesOrders_dbss';
GO
USE [master]
GO
ALTER DATABASE [Demo] SET COMPATIBILITY_LEVEL = 120
GO
USE [Demo]
GO
DBCC SHRINKFILE (N'Demo' , 3)
GO
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
USE master;
GO
ALTER DATABASE [Demo]
Modify Name = Demo1
GO
USE [master]
GO
ALTER DATABASE [Demo] COLLATE SQL_Latin1_General_CP1_CS_AS
GO
--Run this command to check what exactly is the issue for database being
recovery/suspect
DBCC CHECKDB(Demo) WITH NO_INFOMSGS
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
use [SalesOrders]
GO
UPDATE STATISTICS [dbo].[Customers]
WITH FULLSCAN
GO
SECURITY
USE [master]
GO
CREATE LOGIN [TECHBROTHERS\kscott]
FROM WINDOWS
WITH DEFAULT_DATABASE=[master]
GO
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
SELECT denylogin,hasaccess FROM syslogins
WHERE name = 'Techbrothers'
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
USE [SalesOrders]
GO
CREATE USER [TECHBROTHERS\kscott] FOR LOGIN [TECHBROTHERS\kscott]
GO
USE [SalesOrders]
GO
ALTER ROLE [db_datareader] ADD MEMBER [TECHBROTHERS\kscott]
GO
USE [SalesOrders]
GO
CREATE SCHEMA [BKS] AUTHORIZATION [TECHBROTHERS\kscott]
GO
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
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
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
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
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
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 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 “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.
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.
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
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.
DR PLANS
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
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.
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.
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.
Log shipping works with FULL and BULK LOGGED recovery model.
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?
Yes, We can configure Log shipping between servers which are in different domain but
there must be Trust relationship between the domain.
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?
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.
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?
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.
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.
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.
In such case Log Shipping will break, and we have to re-configure the 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.
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.
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.
Mirroring
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
Note: Replace the dbname before using the above script Q: How to disable mirroring by
script? Ans: ALTER DATABASE [AdventureWorks] SET PARTNER OFF
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: How can I increase Heartbeat time between principal and mirror server?? By default
its 10 sec.
Ans: Is mirroring is set to paused from principle then then both principle & mirror in
suspending
Ans: MSDB.SYS.SP_DBMMONITORRESULTS
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: If drive letter is different on both the server. Then what is the steps to add a new
datafile?
Q: Please explain how log transmission and transaction commits work in high
performance mode and in high safety mode?
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?
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.
1. Principal and mirror are running SQL Server 2005 or newer (Standard or Enterprise Edition).
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.
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.
a. Take full and T.Log backup from principle server and restore it in mirror server with
NORECOVERY.
Default port no is
Q: Monitoring Mirroring?
· Transaction Rate
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
Q: What are the major new features introduced in Mirroring 2008 version?
To view total bytes send from principal and total bytes received at mirror we can use (run in
witness server)
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.
· 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?
· Both the servers should have either Enterprise or standard editions.
· 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.
· Service Account should be same for sql and sql agent on Instance
can't configure more than 10 DB's on 32 bit but we can on 64 Bit. But not recommended.
Q: Advantages of Mirroring?
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.
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.
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).
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.
e) Profiler:- Profiler many events are providing the status of the Database mirroring
⦁ 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.
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.
TCP://<computer_name>.<domain_segment>[.<domain_segment>]:<port>
Section 1.01
2) Remove existing all Endpoints from Principal, Mirror and Witness servers :- DROP
ENDPOINT [ENDPOINT_NAME]
a) Right-click My Computer, and then click Properties. The System Properties dialog box will
appear.
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.
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.
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.
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?
RESTORING
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.
Automatic or
High Availability FULL Synchronous Y Y
Manual
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
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