0% found this document useful (0 votes)
437 views

SQL Dba Interview Questions

Uploaded by

Shubham
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
437 views

SQL Dba Interview Questions

Uploaded by

Shubham
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Questions are collected by K.V.

N SUBBA REDDY
Daily Activities
a) VERIFY ALL INSTANCES ARE UP
b) VERIFY DBSNMP IS RUNNING -DB simple n/w mail protocol
c) Check OS Event Logs, SQL Server Logs, and Security Logs for unusual events
d) VERIFY SUCCESS OF DATABASE BACKUP
e) VERIFY SUCCESS OF DATABASE ARCHIVING TO TAPE
f) Verify that all scheduled jobs and alerts have run successfully.
g) Periodically monitor performance using both System Monitor and Profiler.
h) Monitoring and identify blocking issues using Enterprise Manager/Management Studio
i) Monitoring Connectivity Issues and Memory Issues
j) Monitoring Log Shipping & Mirroring
k) Managing Logins, Users and Security

Can you explain the environments you have worked in related to the following items?
a. SQL Server versions: 2005 and 2008.
b. SQL Server technologies: Relational engine/Database Engine.
c. Number of SQL Servers :80 servers(5 Test Servers+10Development servers+Remaining
Production servers)
d. Number of instances: Avg 3 Instances for each server.
e. Number of databases :Avg 5 to 6 databases for each database’s
f. Range of size of databases: 30GB to 500GB.
g. Number of DBAs :6
h. Number of Developers :10
i. Hardware specs (CPU’s=For each server 4CPUs, memory=Intel Quad core processors(32GB
RAM), 64 bit, SANs=2TB)
Note: 1GB Backup will take 6secs with 32GB RAM

Project: Working on the software application called RS-Unify based on SQL Server.
It is an automation package, which is developed to automate the core business activities.
It is a multi-user package through which each and every HLL client can interact with main server to upload the
data needed for business transactions.
Client while interacting with server sends and receives the data, which is present in the database.
Citrix online server is used to connect client system remotely
The main purpose of the project was to Install & Implement RSUnify
system maintenance and Troubleshooting the Software and guidance

What is your experience with third party applications and why would you use them?
Experience Why
Backup tools Need to improve upon the functionality that SQL Server
offers natively
Performance tools Save time, save money, better information or notification.
Code or data synchronization
Disaster recovery\high availability
Third Party Tools to compress database:
Lite speed->Object level recovery----www.quest,.com BMC Remedy
TSM Tivoli www.redgate.com(Backupro)
Semantic Backup www.idera.com

System Requirements
* O/S : Windows 2000 server with sp4
: Windows 2003 server with sp2
: Windows 2008 sever
* RAM : >1GB
* CPU : >1GHz Processors:Pentium3 or higher
* HDD : 2684 MB
: 611 MB for database engine(493+118)
* SQL Native Client
* .Net Framework 3.5 with sp1
* Windows Services: WMI (Windows Management Instrumentation)
*DTC (Distributed Transaction Coordinator) * RPC (Remote Procedure Call)
* IE : 6 SP1 or a later version

I have 30GB Ram, How can we configure for production environment? Ans: Depends SLA
Questions are collected by K.V.N SUBBA REDDY
Upgrade Strategies: In-place upgrade: Using the SQL Server 2012 Setup program to directly upgrade an
instance of
SQL Server 2005, 2008, or 2008 R2. The older instance of SQL Server is replaced.
 we don't have to worry about users and logins
 sqlserver agent jobs will be upgraded during the upgrade process
 The setup program takes the server offline by stopping the existing sqlserver services.
 sqlserver 2005 enterprise,developer,standard,workgroup editions can be upgraded to diff. editions of
sqlserver 2008
 sqlserver 2005 express editions can be upgraded to the express edition of sqlserver 2008
Side-by-side upgrade: Using steps to move all or some data from an instance of SQL Server 2005, 2008, or
2008 R2 to a separate instance of SQL Server 2012. There are two main variations of the side-by-side upgrade
strategy:
One server: The new instance exists on the same server as the target instance.
Two servers: The new instance exists on a different server than the target instance.
Advantages: Ability to run sqlserver side by side for testing and verification
 rollback strategy as original server is still intact
 best for large databases
Dis-advantages: Additional hardware may be required for instance upgrade or additional physical server.
 does not preserver the sqlserver 2005 functionality
 issue of instance name for connecting applications

Upgrade Advisor: To help you identify any possible problems before starting the upgrade process. SQL Server
2005 Upgrade Advisor scans the existing SQL Server 7 and SQL Server 2000 instances provided. The Advisor
checks for any potential compatibility issues, deprecated functionalities, and feature and behaviour changes, and
provides you with a recommended list of tasks that need to be done before and after the upgrade.

Setting Worker thread threshold settings:


1. Open SSMS
2. Right click on the server\instance name
3. Go to properties
4. Select Processors
5. Change the value Maximum worker threads to 512
6. Click OK
7. Restart SQL SERVER Services
8. If Service brokers are not used, then disable the same
9. Find out the list of databases on which service broker is enabled
select * from sys.databases where is_broker_enabled=1
10. Alter database properties to disable service broker.
ALTER DATABASE [Database Name] SET DISABLE_BROKER

One of a user is unable to connect to SQL Server. What may be scenarios and how to troubleshoot it?
Possible Scenarios
1) Error: 26: SQL Browser Firewall No connectivity between client and server
2) Error: 28: Instance TCP/IP was disabled
3) Error: 40: Instance service is not running
4) Error: 18456 Login failed. (invalid login or pwd )
5) Expired Timeout: N/W issue, Server is busy, In server max sessions are open ,No available session
memory
6) Connection Forcibly Closed: Update the client computer to the server version of the Sql Server Native
Client.
7) In single user mode if any other service is connected with the db Engine, it doesn't allow connections.

My SQL Server service is not started. What may be the possible scenarios?
Possible Scenarios
1) Logon Failure: Problem with service account.
2) 3417: Files are not present in the respective path or there are no permissions on target folder where
the files are not present.
3) 17113: Master files are moved to different location, but not mentioned in startup parameters.
4) Service cannot be started in timely fashion: Insufficient resources, try to stop some other instances and
start again.
To find error: Using windows event log ( start --> run --> eventvwr->select System -> check for the errors
Using SQL Server ErrorLog file

Instance: It is a copy of sql-server which runs in a system either with same version or different version.
Questions are collected by K.V.N SUBBA REDDY
Default instance: it is a copy of sql-server which is created with the same name of the system name.A system
can contain only one default instance. The services of the default instance will be displayed as service name
(MSSQLSERVER)
NAMED INSTANCE: It is a copy of sql-server which is created by a user provided name.
A system can contain upto a maximum of 49/50 number of named instances.
The services of the named instance is displayed as service name(instance name)
We can have 49 named instances per machine.
Advantages of instances:
Allows to maintain multiple copies.
Allows to separate the environments(dev/testing/production).
Allows to differentiate the user permissions across the instances.
Directory structure:
For every instance installed a separate folder will be created.<drive>:\programm files \microsoft
sqlserver\mssql.n\mssql

Instance aware services: These services are installed once for each instance.
The following are the instance aware services.
i) Sqlserver service (database engine). (ii) Sqlserver reporting service. (iii) Sqlserver analysis service.
(iv) Sqlserver agent service. (v) Sqlserver full text search service.
The instance aware services are displayed with the format of service name (instance name).
Instance un-aware services: These services are installed only once for all the instances.
Some are sql-server services and some are windows services.
The instance un-aware services are displayed in the format of service name.
The following are the list of instance -unaware services.
(i) Sqlserver integration service. (ii) Sqlserver browser service.
(iii) Sqlserver vss writer (windows service). (iv) Sqlserver active directory helper (windows service).

What are Services available in SQL Server?


There are three services available in SQL Server 2005.
a) SQL server service:- It is responsible for running Databases, System Stored Procedures, System
Indexes, User Login information and Passwords
b) SQL server agent service:- It is responsible for running Jobs, Alerts, Notifying the operators
c) Distributed Transaction Coordinator:- It is responsible for moving data among instances (One DB
to another DB)

How many ways to run services?


Services are run by 5 ways they are
1) At task pane > Right click on server and click start / stop
2) Management Studio > Right click on Server and click start / stop / restart
3) Surface Area Configuration
4) Command Prompt > Net start/stop mssqlserver
5) SQL Server configuration manager > Right click on server and click start / stop / restart.

Editions: 1.ENTERPRISE EDITION (E.E) 2.STANDARD EDITION (SE) 3.WORKGROUP EDITION


(WE)
4. DEVELOPER EDITION (DE) 5.EXPRESS EDITION (EE) 6.MOBILE EDITION (ME) OR
COMPACT EDITION

Enterprise Edition Standard Edition


1. For large scale appls 1. For small and medium scale appls
2. Supports clustering 2. Supports clustering
* 2000 - 4 Nodes * 2000 - No support
* 2005 - 8 Nodes * 2005 - 2 nodes
* 2008 - 16 Nodes * 2008 - 2 nodes
3. Supports all advanced features 3. No advanced feature support
* DB Snapshots
* Peer to peer replication
* Online restores
* Resource Governor And TDE
* Mirroring with Safety FULL and OFF
4. No limit for no of CPUs 4. Max 4 CPUs
5. No limit for size of db(512PB) 5. Same

What is the Versions Available in SQL Server?


SQL Server was developed by Microsoft in 1987 and the versions are 6.0, 6.5, 7.0, 8.0(2000), 9.0(2005-Yukon),
10(2008-Kotmai), 10.5(2008R2-Kilimanjaro), 11.0(2012-Denali)
Questions are collected by K.V.N SUBBA REDDY
What are different variants of SQL Server 2005?
Express – Free and only for one user Enterprise – 5 users apart from server
Workgroup – 10 users apart from server Standard – 25 users apart from server

Explain the difference between DBMS and RDBMS.


DBMS:
A database is a collection of homogenous information that is organized in such a way that it can be easily
accessed, managed, and updated. Ex: FoxPro, IMS
DBMS is not more secure than RDBMS
In DBMS store and retrieve small amount of Data
Data is stored in flat files with metadata.
DBMS does not support client / server architecture.
DBMS does not follow normalization. Only single user can access the data.
DBMS does not impose integrity constraints.
To perform the database operations, the file should be in use.
Relationship can be established between 2 files.

RDBMS:
DBMS is a set of software that is used to manage and maintain Relational data effectively
RDBMS is more secure than DBMS
In RDBMS store and retrieve large amount of Data
RDBMS stores the data in tabular form. (Means table in rows & columns)
RDBMS supports client/server architecture.
RDBMS follows normalization. Allows simultaneous access of users to data tables.
RDBMS imposes integrity constraints. ACID properties of the database are defined in the integrity constraints.
It has additional condition for supporting tabular structure or data that enforces relationships among tables.
Different Types of RDBMS: 1.SQL Server 2.Oracle 3.DB2 4.Sybase 5.Informix

What is normalization?
In relational database design, the process of organizing data to minimize redundancy.
Different normalization forms:
1NF: Eliminate Repeating Groups
2NF: Eliminate Redundant Data
3NF: Eliminate Columns Not Dependent On Key
BCNF: Boyce-Codd Normal Form : If there are non-trivial dependencies between candidate key attributes,
separate them out into distinct tables.
4NF: Isolate Independent Multiple Relationships
5NF: Isolate Semantically Related Multiple Relationships
ONF: Optimal Normal Form: A model limited to only simple (elemental) facts, as expressed in Object Role Model
notation.
DKNF: Domain-Key Normal Form A model free from all modification anomalies.

COLLATION: Collation refers to a set of rules that determine how data is sorted and compared
CS -> CASE SENSITIVE AS -> ACCENT SENSTITIVE KS->Kana Sensitivity
CI -> CASE INSENSITIVE AI -> ACCENT INSENSITIVE WS-> Width sensitivity

What is AWE? How configure Dynamic Memory Allocation?


AWE (Address Windowing Extension) is used to support very large amounts of physical memory. When AWE is
enabled the operating system dynamically allocates memory to SQL Server based on the Min server memory
and max server memory settings. (1) Win. Server 2003 SE supports utpo 4GB (2) EE upto 32GB. (3) DC upto
64GB)
To Configure AWE:- Right click on instance > Properties > Memory > Enable AWE > Set Min and Max memory
etc.
Note:- AWE is not needed and cannot be configured on 64-bit operating systems.

Hot fixes are the solution for the bugs.


Service packs contains hotfixes and additional features
Sql server 2005 contain RTM, SP1, SP2,SP3, SP4. SS 2008 contain RTM, SP1, SP2

What is purpose of LSN numbers?


Every record in the transaction log is uniquely identified by a log sequence number (LSN). LSNs are used
internally during a RESTORE sequence to track the point in time to which data has been restored.

What is Stored Procedure?


Questions are collected by K.V.N SUBBA REDDY
 A stored procedure is a named group of SQL statements that have been previously created and
stored in the server database.
 Stored procedures accept input parameters

 When the procedure is modified, all clients automatically get the new version.

 Stored procedures reduce network traffic and improve performance.

 Stored procedures help promote code reuse.


 Stored procedures can encapsulate logic. You can change stored procedure code without affecting
clients.
 Stored procedures provide better security to your data.
 Stored procedure can’t be inactive but trigger can be Inactive.

 Stored procedures can be used to help ensure the integrity of the database.e.g. sp_helpdb,
sp_renamedb, sp_depends etc.

Types of stored Procedures


User Defined Stored Procedure:- Stored procedures are modules or routines that encapsulate code for reuse.
System Stored Procedure:- are used to perform many administrative and informational activities.
Extended stored procedure:- are used to create own external routines in a programming language such as C.

What is Trigger?
 A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE)
occurs.
 Triggers are stored in and managed by the DBMS.
 Triggers are used to maintain the referential integrity of data by changing the data in a systematic
fashion.
 A trigger cannot be called or executed; the DBMS automatically fires the trigger as a result of a data
modification to the associated table.
 Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is
stored at the database level.
 Stored procedures, however, are not event-drive and are not attached to a specific table as triggers
are.Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are
implicitly executed. In addition, triggers can also execute stored procedures.

Types of triggers: 1.DML Triggers (Instead of Trigger and After trigger) 2. DDL Triggers 3.Logon
Triggers

After Triggers:- After Triggers will fires after the data is inserted into the table. The typical use for an After
trigger is to log the action to an Audit or logging table
Before Triggers:- Before triggers will fire before the data is inserted into the table.
Note:- DML triggers fires before or after issue, DDL triggers fires after the issue

Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the
trigger is fired because of data modification it can also cause another data modification, thereby firing another
trigger. A trigger that contains data modification logic within itself is called a nested trigger.

Where can you view the list of server-scoped DDL triggers?


The server-scoped DDL triggers will appear in Management Studio in the Object Explorer under the "Triggers"
folder..

What is View? A simple view can be thought of as a subset of a table.


 It can be used for retrieving data, as well as updating or deleting rows.
 Rows updated or deleted in the view are updated or deleted in the table the view was created with.
 The results of using a view are not permanently stored in the database.

What is SQL Injection and why is it a problem?


SQL Injection is an exploit where unhandled unexpected SQL commands are passed to SQL Server in a
malicious manner. It is a problem because unknowingly data can be stolen,deleted, updated, inserted or
corrupted.

What is Index?
Questions are collected by K.V.N SUBBA REDDY
 An index is a physical structure containing pointers to the data.
 Indices are created in an existing table to locate rows more quickly and efficiently.
 The users cannot see the indexes; they are just used to speed up queries.
 Effective indexes are one of the best ways to improve performance in a database application.
 Indexes need disk space, the more indexes you have, more disk space is used.

What are the difference between clustered and a non‐clustered index?


A clustered index is a special type of index that It physically sorts the rows in the table.
Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
Create clustered index pid_indx on prods (pid)
A nonclustered index is a special type of index in It cannot sort the rows physically.
The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index
rows.
Always we have to place first clustered index then nonclustered.
We can have up to 249 non clustered index in a table.
You can have up to 999 non clustered index from SQL Server 2008 onwards.
CREATE NONCLUSTERED INDEX IX_Address_PostalCode ON Person.Address (PostalCode)

Difference between P.K and Clustered Index?


Primary key enforce uniqueness and allows to establish relationship. But by default clustered index cannot..

What is page splitting?


SQL Server want to write data at a specific place (because of an index), but if there is not enough room in the
current page it has to split it in two. Page splitting can impair performance and fragment the storage of the data
in a table. When creating an index, you can specify a fill factor to leave extra gaps and reserve a percentage of
free space on each leaf level page of the index to accommodate future expansion in the storage of the table's
data and reduce the potential for page splits.

What is Fill factor? How to assign Fill factor?


A Fill factor is a reserved free space on each leaf level page which is used for future growth of data or index in a
table and reduces the page splits by default it is 100%.
Assign Fill Factor:- Right Click on Server > Properties > Database Settings > Default Index Fill Factor >
Provide the value

What are the different index configurations a table can have?


No indexes
A clustered index
A clustered index and many nonclustered indexes
A nonclustered index
Many nonclustered indexes

Indexes - where you cannot create them? Indexes cannot created in LOB (Large Object data), in the columns
with data types like: text, ntext, varchar (max), nvarchar (max), varbinary (max), xml, image.

What is Heap table? A table without a clustered index is called as heap table.

What is B-Tree? The database server uses a B-tree structure to organize index information. B-Tree generally
has following types of index pages or nodes:
• Root node: A root node contains node pointers to branch nodes which can be only one.
• Branch nodes: A branch node contains pointers to leaf nodes or other branch nodes which can be two
or more.
• Leaf nodes: A leaf node contains index items and horizontal pointers to other leaf nodes which can be
many.

What is the diff between re-building and re-organize? When your use.
Re-building Re-Organize
1. Complete index is dropped and recreated. Here 1. Just index pages are placed in order of index
you can specify FillFactor. key column volume. Here you can not specify Fill
Factor
2.Fragmentaion >30% or if scan density < 75% 2. .Fragmentaion >5% &<30% or if scan density
> 75% &<95%
3.Statistics are updated 3.Not Updated
4.Take Long time 4.Take less time
5.Table is block if the option “online processing of 5.Allows
DML…” is not enabled
Questions are collected by K.V.N SUBBA REDDY
Re-building Re-Organize
6.Use Tempdb space 6.Min.space
7.Alter index indexname/All on <tname> rebuild 7.Alter index indexname/All on <tname>
reorganize
8. It is offline operation 8. It is online operation
9.Option is available in all SQL Server 2005 edition 9.Option is available in SS 2005 EE and DE

What are “Table Scan’s” and “Index Scan’s”?


A table scan is where the table is processed row by row from beginning to end.
An index scan is where the index is processed row by row from beginning to end.
If the index is a clustered index then an index scan is really a table scan.

Which is faster a Table Scan, or a Clustered Index Scan?


Same speed in case a table has a clustered index that it’s always show index scan instead of table scan.

What are data objects?


Tables, Views, clusters, index, cluster and sequences are called data objects for a database

What is cursor?
Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis.
Types of cursors: 1. Static, 2. Dynamic, 3. Forward only, 4. Key set-driven.
In order to work with a cursor we need to perform some steps in the following order:
1. Declare cursor 2.Open cursor 3.Fetch row from the cursor 4.Process fetched row 5.Close cursor
6.Deallocate cursor
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network round-trip, where
as a normal SELECT query makes only one round-trip, however large the result set is.
Cursors are also costly because they require more resources and temporary storage
Further, there are restrictions on the SELECT statements that can be used with some types of cursors.

What techniques are used to retrieve data from more than one table in a single SQL statement?
Joins, unions and nested selects are used to retrieve data.

What is the use of DBCC commands?


DBCC stands for database consistency checker. is used to check logical and physical consistency of database
structure. DBCC statements can fix and detect problems. They are grouped in to four categories:-
Maintenance: Maintenance tasks on a database, index, or file group.
DBCC CLEANTABLE
DBCC DROPCLEANBUFFERS
DBCC SHRINKFILE
DBCC FREEPROCCACHE
DBCC INDEXDEFRAG(Database_Name, Table_Name, Index_Name)
DBCC DBREINDEX([[`db_name.username.table_name'[,ind_name[,fillfactor[,SORTED_DATA|
SORTED_DATA_REORG])
DBCC DBREPAIR (database_name, DROPDB [, NOINIT])
DBCC SHRINKDATABASE(database_name [, new_size[, `MASTEROVERRIDE']])
DBCC UPDATEUSAGE ({0 | database_name}[, table_name [, index_id]]) | USEROPTIONS}[WITH
COUNT_ROWS]
Miscellaneous: Miscellaneous tasks such as enabling trace flags or removing a DLL from memory.
DBCC dllname (FREE)
DBCC HELP
DBCC FREESESSIONCACHE
DBCC FREESYSTEMCACHE
DBCC TRACEOFF (trace#)
DBCC TRACEON (trace#)
Informational: Tasks that gather and display various types of information.
DBCC INPUTBUFFER (spid)
DBCC PROCCACHE
DBCC USEROPTIONS
DBCC SHOWCONTIG (table_id, [index_id])
DBCC OUTPUTBUFFER (spid)
DBCC OPENTRAN ({database_name} | {database_id})[WITH TABLERESULTS]
DBCC SQLPERF ({IOSTATS | LRUSTATS | NETSTATS| RASTATS [, CLEAR]} {THREADS} | {LOGSPACE})
DBCC TRACESTATUS (trace# [, trace#...])
DBCC SHOW_STATISTICS(table_name, index_name)
Questions are collected by K.V.N SUBBA REDDY
Validation: Validation operations on a database, table, index, catalog, file group, or allocation of database
pages.
DBCC CHECKFILEGROUP
DBCC CHECKCATALOG
DBCC CHECKCONSTRAINTS
DBCC CHECKALLOC [(database_name [, NOINDEX])]
DBCC CHECKIDENT[(table_name)]
DBCC CHECKTABLE (table_name [, NOINDEX | index_id]
DBCC CHECKDB [(database_name [, NOINDEX])]

What is Dynamic Management Views?


DMVs return server state information that we can use to monitor the health of a server instance, diagnose
problems, and tune performance. Types of DMVs:
SQL Server related [HW Resources] DMV: Is responsible to manage server level resources specific to a SQL
Server instance.
sys.dm_os_sys_info
sys.dm_os_hosts
sys.dm_os_schedulers
sys.dm_io_pending_io_requests
sys.dm_io_virtual_file_stats
sys.dm_os_memory_clerks
sys.dm_os_ring_buffers
Database related DMV These DMVs will help to identify database space usages, partition usages, session
information usages.. sys.dm_db_file_space_usage
sys.dm_db_session_space_usage
sys.dm_db_partition_stats
sys.dm_os_performance_counters
Index related DMV These DMVs will help to identify database space usages, Partition usages, Session infn
usages, etc. sys.dm_db_index_usage_stats
Execution related DMV: will provide infn regarding sessions, connections, and various requests which are
coming into the SS sys.dm_exec_sessions sys.dm_exec_connections
sys.dm_exec_requests sys.dm_exec_sql_text
.
How to Delete Duplicate Rows in a Table?
Delete from Dept where deptno not in (select min(Deptno) from dept Group by Loc)

What is the query used to display all tables names in SQL Server (Query analyzer)?
select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'

To get the list of User Defined table names: Select * from sysobjects where type = 'u'
To get the list of system Defined table names: Select * from sysobjects where type =‘s’

What is the Syntax used for find the SQL Server version?
1) Select @@version
2) Click on Server > Summary Reports > Server Dashboard > configuration details > See product version.

What is an OLTP system and OLAP system?


OLTP: Online Transaction and Processing helps and manages applications based on transactions
involving high volume of data. Typical example of a transaction is commonly observed in Banks, Air
tickets etc. Because OLTP uses client server architecture, it supports transactions to run cross a
network.

OLAP: Online analytical processing performs analysis of business data and provides the ability to perform
complex calculations on usually low volumes of data. OLAP helps the user gain an insight on the data coming
from different sources (multi dimensional).

What is a Linked Server?


• Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query
both the SQL Server dbs using T-SQL Statements.
• With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data
to be retrieved, joined and combined with local data.
• Stored Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server.
• To know linked servers information: select * from sys.servers
• To access table from different server:Select *
from Linkedservername.Databasename.dbo.Tablename
Questions are collected by K.V.N SUBBA REDDY

What is sub-query?
 Sub-queries are often referred to as sub-selects
 A subquery is a SELECT statement that is nested within another T-SQL statement.
 A subquery SELECT statement can return any number of values.
 It can be found in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or
ORDER BY clauses of a T-SQL statement.
 A Subquery can also be used as a parameter to a function call.
Properties of Sub‐Query
1 A sub‐query must be enclosed in the parenthesis.
2 A sub‐query must be put in the right hand of the comparison operator, and
3 A sub‐query cannot contain an ORDER‐BY clause.
4 A query can contain more than one sub‐query.
Types of Sub‐query
1 Single‐row sub‐query, where the sub‐query returns only one row.
2 Multiple‐row sub‐query, where the sub‐query returns multiple rows,. and
3 Multiple column sub‐query, where the sub‐query returns multiple columns
4
What are different Types of Join?
Joins are used in queries to explain how different tables are related. Joins also let you select data from a table
depending upon data from another table.
1.Inner Join:Contain matched rows only.
2.Outer Join:Contain Matched rows and Unmatched rows.These are 3 types.
Left Outer Join:Which contains all the rows from left table and matched rows from right table.
Right Outer Join:Which contains all the rows from Right table and matched rows from left table.
Full OuterJoin:Which contains all the rows from left table and all rows from right table.
3.Cross Join:A join with out any condition is called Cross Join,Every row in 1st table is joins with every row in
2nd table.
4.Self Join:A join joins with it self is called self join.
5.Equi Joins:Matchs rows from joined table & Display redundant values
6.Natural Joins:Display all matches rows & Restrict to Redundant values.

Constraint: Using Constraint, SQL Server enforces the integrity to the database.
It defines the rules that restrict unwanted data in the column.
Constraints can be table constraints or column constraints.

What is CHECK Constraint? A CHECK constraint is used to limit the values that can be placed in a column.
The check constraints are used to enforce domain integrity.

What is NOT NULL Constraint? A NOT NULL constraint enforces that the column will not accept null values.
The not null constraints are used to enforce domain integrity, as the check constraints.

Could you please describe some properties / Facts about NULL during comparisons.
NULL can not used with any comparing operator, NULL
• NULL will never be true or false
• NULL can not compared as =,<>,<,>, <=,<= etc.
• NILL is always equates will NULL only

What is Identity? Identity (or AutoNumber) is a column that automatically generates numeric values. A start and
increment value can be set, but most DBA leave these at 1.

What are primary keys and foreign keys?


Primary keys are the unique identifiers for each row.
By default primary key creates a clustered index on the column
primary key doesn't allow NULLs
A table can have only one Primary key.
Foreign keys and PK’s are both method of ensuring data integrity.
A foreign key in one table points to a primary key in another table.
This foreign key must have the same structure as the reference table’s primary key.

Explain the types of Data integrity?


Enforcing data integrity ensures the quality of the data in the database.
Entity Integrity: It means that the row is kept as a unique entity. It ensures that the integrity of the identifier is
maintained through PRIMARY KEYS, IDENTITY property etc
Questions are collected by K.V.N SUBBA REDDY
Domain Integrity: It validates the entries for a given column. Restricted data types can be given, FOREIGN
KEY, CHECK and NOT NULL constraints can be specified.
Referential Integrity: it helps in maintaining the relationships between tables when a new row is inserted or
deleted. Usually Foreign leys are used to define relationships between tables.

Types of Transact-SQL
Data Definition Language (DDL): CREATE, ALTER, DROP
Data Control Language (DCL): GRANT, REVOKE, DENY
Data Manipulation Language (DML): SELECT, INSERT, UPDATE, DELETE

What is User Defined Functions?


User-Defined Functions allow defining its own T-SQL functions that can accept 0 or more parameters and return
a single scalar data value or a table data type. Different Kinds of User‐Defined Functions created are:
 Scalar User-Defined Function
 Inline Table-Value User-Defined Function
 Multi-statement Table-Value User-Defined Function

Difference between sql server 2000 and sql server 2005?


1. Sql server 2005 include Enterprise manger and Query analyzer together in same window but in 2000 it is in
different.
2. Sql server 2005 support more data types like xml, Varchar (max) and varbinary (max)
3. We can create max of 2(paw(20))-1 databases in 2005 in compare to 2000 we can create 65,535 databases
4. In store procedure we can write try catch statement in 2005 not in 2000
5 Mirroring is available in 2005 but not in 2000
6.In SQL SERVER 2000 there where maximum 16 instances, but in 2005 you can have up to 50 instances.
7.Encryption and key management build in 2005 but not in 2000
8.SQL SERVER 2005 has reporting services for reports and does not exist for SQL SERVER 2000
9.SQL Server 2005 introduces a dedicated administrator connection (DAC) But not in 2000
10.Schema is separate in 2005.But in 2000, Owner = Schema, hard to remove old users at times

Difference between SQL Server 2005 and SQL Server 2008?


SQL 2005
1. Cannot encrypt
2. Can Compress tables and indexes.(Introduced in 2005 SP2)
3. Datetime is used for both date and time.
4. No table datatype is included.
5. SSIS is started using.
6. Central Management Server(CMS) is not available.
7. Policy based management(PBM) is not available.

sql 2008
1. Can encrypt the entire database introduced in 2008.
2. Can compress tables and indexes
3. Date & time are seperately used for date and time datatype,geospatial & timestamp with internal
timezone is used.
4. Table datatype introduced.
5. SSIS avails in this version.
6. Central Management Server(CMS) is Introduced.
7. Policy based management(PBM) server is Introduced.
 Storing backup file takes 5 minutes without compression in sqlserver 2005,but it takes only 3 minutes in
sql server 2008 for storing backup files with compression.
 The nice thing is that it upgrading should be much easier from 2005 to 2008 than it was from 2000 to
2005.
 when we write select * from --- it ask to for table name (2008) but 2005 does not ask.
 Resource Governor , Transparent Data Encryption are there in 2008
 Enhanced Auditing
 Enhanced Database Mirroring
Automatic page repair. Enhanced supportability Log Stream Compression

Main Difference is over 2000,2005,2008 is


1. XML integration 2. Exception Handling 3. CLR ( common language runtime) integration
4. Varchar (Max) data type 5. DDL Triggers 6. Database Mirroring 7. Row Number function for
paging
Questions are collected by K.V.N SUBBA REDDY
8. Table fragmentation 9. Full Text Search 10. Easy User Interface 11. Versions 12. Bulk
Copy Update
SQL Server 2008 R2
PowerPivot for SharePoint
PowerPivot for Excel
Multi-Server Administration and Data-Tier Application
Master Data Services (MDS)
Supported by the Editions of SQL Features Server 2008 R2
Connecting to the Database Engine Using Extended Protection .

Which are new data types introduced in SQL SERVER 2008?


The GEOMETRY Type: The GEOMETRY data type is a system .NET common language runtime (CLR) data
type in SQL Server. This type represents data in a two-dimensional Euclidean coordinate system.
The GEOGRAPHY Type: The GEOGRAPHY datatype’s functions are the same as with GEOMETRY. The
difference between the two is that when you specify GEOGRAPHY, you are usually specifying points in terms of
latitude and longitude.
New Date and Time Data types: DATE: The new DATE type just stores the date itself. It is based on the
Gregorian calendar and handles years from 1 to 9999.
TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000 through 23:59:59.9999999. The
precision is allowed with this type. TIME supports seconds down to 100 nanoseconds. The n in TIME (n) defines
this level of fractional second precision, from 0 to 7 digits of precision.
DATETIMEOFFSET (n) is the time-zone-aware version of a datetime data type. The name will appear less odd
when you consider what it really is: a date + a time + a time-zone offset.
DATETIME2 : It is an extension of the datetime type in earlier versions of SQL Server. This new data type has a
date range covering dates from January 1 of year 1 through December 31 of year 9999. This is a definite
improve and the same fractional precision that TIME type provides

What is use of EXCEPT Clause?


EXCEPT clause is similar to MINUS operation in Oracle. The EXCEPT query and MINUS query returns all rows
in the first query that are not returned in the second query.

What is XPath? XPath uses a set of expressions to select nodes to be processed.

What is Aggregate Functions? Aggregate functions perform a calculation on a set of values and return a
single value. Aggregate functions ignore NULL values except COUNT function. Aggregate functions are
AVG, MIN, CHECKSUM_AGG, SUM, COUNT, STDEV, COUNT_BIG, STDEVP, GROUPING, VAR, MAX,
VARP

What are defaults? Is there a column to which a default can't be bound?


A default is a value that will be used by a column, if no value is supplied to that column while inserting data.
IDENTITY columns and timestamp columns can't have defaults bound to them.

How to reset SA password? Start the instance in single user mode and connect as a member of
Built-in\Administrators to reset the SA password

How to reset SA password? Start the instance in single user mode and connect as a member of
Built-in\Administrators to reset the SA password

What is Policy Management?


Policy Management in SQL SERVER 2008 allows you to define and enforce policies for configuring and
managing SQL Server across the enterprise. Policy-Based Management is configured in SQL Server
Management Studio (SSMS). Navigate to the Object Explorer and expand the Management node and the Policy
Management node; you will see the Policies, Conditions, and Facets nodes.
Facets: Facets is the property of SQL Server which the policy will consider managing. There are several facets
on which policies could be implemented. For example, we will use the “Database Option” facet to implement a
policy which will ensure that the AutoShrink option should be TRUE for all hosted databases on the server.
Similarly, we will be creating policies on the Stored Procedure facet.

Resource Governor: A technology that enables you to manage SQL Server workload and resources by
specifying limits on resource consumption. The RG Components are
Resource pools. Two resource pools (internal and default) are created when SQL Server 2008 is installed.
Workload groups. Two workload groups (internal and default) are created and mapped to their corresponding
resource pools when SQL Server 2008 is installed.
Classifier. There are internal rules that classify incoming requests and route them to a workload group.
Questions are collected by K.V.N SUBBA REDDY
Scenario There are two DBAs in one organization. One DBA A runs critical queries for business and another
DBA B is doing maintenance of the database. At any point in time the DBA A’s work should not be affected but
at the same time DBA B should be allowed to work as well. The ideal situation is that when DBA B starts working
he get some resources but he can’t get more than defined resources.

Codd's Rules: Any system which claims to be a relation database management system must be able to
manage databases entirely through its relational capabilities
Rule 0: Foundation rule
Rule 1: The information rule
Rule 2: The guaranteed access rule
Rule 3: Systematic treatment of null values
Rule 4: Active online catalog based on the relational model
Rule 5: The comprehensive data sublanguage rule
Rule 6: The view updating rule
Rule 7: High-level insert, update, and delete
Rule 8: Physical data independence
Rule 9: Logical data independence
Rule 10: Integrity independence
Rule 11: Distribution independence
Rule 12: The nonsubversion rule
Tools in sql-server:
(1) Configuration tools: (i) SS Configuration manager (ii) SS Surface area configuration (iii) Management
studio
(2) Monitoring tools: (i) Management studio (ii) activity monitor (iii) DMF’s & DMV's (iv) sqlserver profiler
(3) Command line utilities: SQLCMD, BCP, TABLEDIFF
(4) OTHER TOOLS: Database engine tuning advisor, Upgrade advisor, Third party tool (IDERA tools)

What’s the difference between a primary key and a unique key?


Both primary key and unique key enforces uniqueness of the column on which they are defined. But by default
primary key creates a clustered index on the column, where are unique creates a nonclustered index by default.
Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.

What is difference between DELETE & TRUNCATE commands?


Delete command removes the rows from a table based on the condition that we provide with a WHERE clause.
Truncate will actually remove all the rows from a table and there will be no data in the table after we run the
truncate command.
TRUNCATE
1 TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
2 TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only
the page
3 deallocations are recorded in the transaction log.
4 TRUNCATE removes all rows from a table, but the table structure, its columns, constraints, indexes and
so on,
5 remains. The counter used by an identity for new rows is reset to the seed for the column.
6 You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Because
TRUNCATE TABLE
7 is not logged, it cannot activate a trigger.
8 TRUNCATE cannot be rolled back.
9 TRUNCATE is DDL Command.
10 TRUNCATE Resets identity of the table
DELETE
1 DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.
2 If you want to retain the identity counter, use DELETE instead. If you want to remove table
3 definition and its data, use the DROP TABLE statement.
4 DELETE Can be used with or without a WHERE clause
5 DELETE Activates Triggers.
6 DELETE can be rolled back.
7 DELETE is DML Command.
8 DELETE does not reset identity of the table.

What is the difference between a "where" clause and a "having" clause?


 "Where" is a kind of restiriction statement. You use where clause to restrict all the data from DB. Having
clause is a kind of filtering command.
 Where clause is using before result retrieving. But Having clause is using after retrieving the data.
Questions are collected by K.V.N SUBBA REDDY
 Having Clause is basically used only with the GROUP BY function in a query whereas WHERE Clause
is applied to each row before they are part of the GROUP BY function in a query.
 They specify a search condition for a group or an aggregate. But the difference is that HAVING can
be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When
GROUP BY is not used, HAVING behaves like a WHERE clause.

What is different between int and bint?


bigint can hold values from -2^63 to 2^63-1 and it takes 8 bytes
int can hold values from -2^31 to 2^31 - 1 and it takes 4 bytes

What is difference between Co-related sub query and nested sub query?
Correlated sub query runs once for each row selected by the outer query. It contains a reference to a value
from the row selected by the outer query. Nested sub query runs only once for the entire nesting (outer) query.
It does not contain any reference to the outer query row.

What is the difference between a Local and a Global temporary table?


A local temporary table exists only for the duration of a connection or, if defined inside a compound statement,
for the duration of the compound statement.
A global temporary table remains in the database permanently, but the rows exist only within a given
connection. When connection is closed, the data in the global temporary table disappears. However, the table
definition remains with the database for access when database is opened next time.

Difference between char and nvarchar / char and varchar data-type?


Char [(n)] - Fixed-length non-Unicode character data with length of n bytes. n must be a value from 1 through
8,000. Storage size is n bytes. The SQL-92 synonym for char is character.
nvarchar (n) - Variable-length Unicode character data of n characters. n must be a value from 1 through 4,000.
Storage size, in bytes, is two times the number of characters entered. The data entered can be 0 characters in
length. The SQL-92 synonyms for nvarchar are national char varying and national character varying.
varchar[(n)] - Variable-length non-Unicode character data with length of n bytes. n must be a value from 1
through 8,000. Storage size is the actual length in bytes of the data entered, not n bytes. The data entered can
be 0 characters in length. The SQL-92 synonyms for varchar are char varying or character varying.

Difference between sysusers and syslogins?


Sysusers - Contains one row for each Microsoft® Windows user, Windows group, Microsoft SQL Server™ user,
or SQL Server role in the database. Where are syslogins - Contains one row for each login account.

What is Difference between Function and Stored Procedure?


Sl Stored Procedures User Defined Functions
1 Procedure is to be compiling only one time and Not only one time
vice versa.
2 Stored Procedures can affect the state of the Functions cannot affect the state of the
database by using insert, delete, update and database which means we cannot perform
create operations. insert, delete,
Update and create operations on the database.
3 Sp returns more than one value. Fuction can return a single value only
4 Sp can change server environment and our Function can not change server environment
operating system environment and our operating system environment.
5 SP can’t be used in select Queries statement. Function can be used in select Queries
statement
6 operating system use Execute or Exec to run Functions can run an executable file from SQL
SELECT or an action query.
7. Where as Stored procedures cannot be used UDF can be used in the SQL statements
in in the SQL statements anywhere anywhere in the WHERE/HAVING/SELECT
section

What is the difference between UNION and UNION ALL?


UNION:The UNION command is used to select related information from two tables, much like the JOIN
command. Only distinct values are selected.
UNIONALL: The UNION ALL command is equal to the UNION command, except that UNION ALL selects all
values.
The difference between Union and Union all is that Union all will not eliminate duplicate rows,
Questions are collected by K.V.N SUBBA REDDY
What’s the difference between 32 bit and 64 bit operating systems?
32-Bit: Can support only up to 4GB maximum of RAM. Cannot run programs designed for a 64-bit OS
More commonly found in older home computers where processing power and applications are not mission
critical
32-bit OS Examples: Windows 95,Windows 98,Windows 2000,Windows XP Home, Windows XP Pro
Windows Vista Home, Apple OS 9, Apple OSX Jaguar, Apple OSX Panther
64-Bit: Supports total RAM densities over 4GB. Runs both 32-bit and 64-bit programs
Mission critical setups requiring a great deal of RAM; now equally common for home applications
64-bit OS Examples: Windows XP Pro 64, Windows Vista 64 (Home, Business), Apple OSX Tiger, Apple OSX
Leapord, Linux Distro (All Versions), UNIX
64-bit CPU Examples: AMD Athlon 64, AMD Turion 64,AMD Phenom,Intel Core 2 (Duo and Quad),Intel Dual
Core, Intel Core i7
**It is common for a 32-bit OS to only utilize and display less than 4GB of RAM even if 4GB is installed. This is
not an issue with 64-bit computing.

What is difference between cascade and drop of table?


Cascade option allows the user to delete all the tables which are defined by foreign key relation.
If the tables are involved in foreign key relation, if we try to delete those tables. It will not allow deleting

What is difference between ISQL and OSQL?


Isql: It uses DBLIB as its mechanism for connecting to server.Isql doesn’t support Unicode.
Osql: Uses ODBC as its mechanism for connecting to server and support sql server 2000 fully and its Unicode
complaint.

What is difference between OSQL and Query Analyzer?


Both are the same but there is little difference OSQL is command line tool which is execute query and display
the result same a query analyzer but query analyzer is graphical and OSQL is a command line tool.OSQL have
not ability like query analyzer to analyze queries and show static on speed of execution and other useful thing
about OSQL is that its helps in scheduling.

What is different in Rules and Constraints?


One the most exclusive difference is that we can bind rules to a data types whereas constraints are bound only
to columns.

Diff. b/w getdate () and sysdatetime () in 2008?


With getdate () function, precision is in milliseconds
With sysdatetime () function, precision is down to 100 nanoseconds

What is diff between Push and Pull?


Pull As the name implies, a pull subscription requests changes from the Publisher. This allows the subscriber to
pull data as needed. This is useful for disconnected machines such as notebook computers that are not always
connected and when they connect they can pull the data.
Agent will run in the distributor and Pull subscriptions are created at the subscriber server Subscriber initiates
the replication instead of the publisher
Push As the name implies, a push subscription pushes data from publisher to the subscriber. Changes can be
pushed to subscribers on demand, continuously, or on a scheduled basis.
Agent will run in the subscriber and Push subscriptions are created at the publisher server
The publisher is responsible for updating all the changes to the subscriber with out the subscriber asking those
changes.
What is MARS?
Using Multiple Active Result Sets (MARS), you can maintain multiple pending requests on a single SQL Server
connection. This allows you to issue multiple SQL statements or batch statements against a single connection, which
eliminates the overhead of opening and closing the connection for each.

what is the difference between sys.Databases and sys.sysDatabases.


Well, both of them return some metadata related to databases hosted on the instance. However, sys.Databases returns 56
columns and sys.sysDatabases returns 12 columns.

What are the difference between DDL, DML and DCL commands?
DML commands can't be rollback when a DDL command is executed immediately after a DML. DDL after DML means
"auto commit". The changes will return on disk not on the buffer. If the changes return on the buffer it is possible to
rollback not from the disk.

DDL is Data definition language statements which are used to develop a structure to the table. where as DML(data
manipulation language statements) are used to perform the
Questions are collected by K.V.N SUBBA REDDY
updations to the data.

Difference between DML Triggers and DDL Triggers


DML Triggers will be fired automatically whenever Data Manipulation statements like INSERT,UPDATE and DELETE
are executed where as DDL triggers will fire with the Data definition statements like CREATE, ALTER and DROP.
DML Triggers DDL Triggers
1. Operate on INSERT, UPDATE 1. Operate on CREATE, DROP
and DELETE and ALTER
2. Applied on Tables and views 2. Applied on Databases and
servers
3. Can be used as INSTEAD OF 3. Cannot be used as INSTEAD
TRIGGERS OF TRIGGERS
4. Creates INSERTED and 4. Cannot Create INSERTED and
DELETED tables DELETED tables
5. DML triggers run either Before 5. DDL triggers run only after a
or After a T-SQL statement is T-SQL statement is completed
completed

What is the difference between group by and order by?


Group by controls the presentation of the rows, order by controls the presentation of the columns for the results
of the SELECT statement.

What is the STUFF function and how does it differ from the REPLACE function?
STUFF function is used to overwrite existing characters.
REPLACE function to replace existing characters of all occurrences.
STUFF (string_expression, start, length, replacement_characters),
REPLACE (string_expression, search_string, replacement_string)

What is PIVOT and UNPIVOT?


A Pivot Table can automatically sort, count, and total the data stored in one table or spreadsheet and create a
second table displaying the summarized data. UNPIVOT table is reverse of PIVOT Table.

When is the use of UPDATE_STATISTICS command?


This command is basically used when a large processing of data has occurred.

What is Statistics in SQL Server ?


Statistics helps Query Optimizer to makes a decision to choose the fast good (best) way to execute a given
query. Statistics decides, whether to choose a particular index or not and build the execution plan.
So if your stats are not updated then Optimizer might not choose the best plan and may cause overheads in
query execution. So this becomes very important that SQL Server should always have the updated Statistics.
Create and Update Statistics option either by running following statement
ALTER DATABASE [TEST] SET AUTO_CREATE_STATISTICS ON WITH NO_WAIT
ALTER DATABASE [TEST] SET AUTO_UPDATE_STATISTICS ON WITH NO_WAIT

Which command using Query Analyzer will give you the version of SQL server and operating system?
SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY
('edition').

What is BCP? When does it used?


BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy the structures
same as source to destination. It is used to import and export data from a table into file and vice versa.
Bcp <dbname>.<schemaname>.<tname> in/out <filename> -T –c -S <servername> “In” is to take order from
file into table.
Bcp master.dbo.syslogins out d:\syslogins.txt -T –c -S <servername> “Out” is to take order
from table to file

What command do we use to rename server, a db, a table and a column?


To rename sever sp_dropserver/sp_dropremotelogin old_name sp_addserver , local
To rename db sp_renamedb 'oldname' , 'newname'
To rename Table sp_rename ‘oldTableName’ ‘newTableName’
To rename Column sp_rename ‘TableName. [OldcolumnName]’, ‘NewColumnName’, ‘Column’
Questions are collected by K.V.N SUBBA REDDY
Database Engine: SQL Server Database Engine includes the Database Engine, the core service for storing,
processing, and securing data, Replication, full-text search, and tools for managing relational and XML
data.
Types of databases: systems Dbs, sample dbs (Adventureworks, AdeventureworksDW), User defined dbs.
What are the basic functions for master, msdb, model, tempdb and resource databases?
Master database holds information for all databases located on the SQL Server instance. It consists of server
level settings, system defined error messages (syssmessages), Linked server’s infn (sys.servers), other dbs
details (sysdatabases), Endpoints, Logins (syslogin).SQL Server cannot start without a functioning master
database.
MSDB database consists of total automation information and stores information regarding database backups,
Restores,
Maintain plans, SQL Agent information, and Db mail details, SQL Server jobs, Alerts, operators and log shipping
details.
Tempdb holds temporary tables, temp SPs, Hash tables, Cursors. The process of grouping and ordering is done
here.No need backup. It is cleared once we restart sql server.
Model: It acts as a template for new databases. It consists of system defined objects which are copied into every
new db, User defined tables, User defined data types, SPs can be created here.
Resoure Database is a read‐only database and Hidden database, that contains all the system defined objects t.
SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they
logically appear in the sys schema of every database. It Maintain service packs changes.The Resource
database does not contain user data or user metadata.

Major components of tempdb:


Temporary user objects (cursors, temp tables, temp SPs)
Internal objects (sorting, grouping, and joining)
Row versions (snap shot, isolation levels) To check above objects in sys.dm_db_file_space_usage

How to rebuild Master Databse?


Master database is system database and it contains information about running server’s configuration. To rebuild
the Master database, Run Setup.exe, verify, and repair a SQL Server instance, and rebuild the system
databases. This procedure is most often used to rebuild the master database for a corrupted installation of SQL
Server.
Start /wait <CD or DVD Drive>\setup.exe /qn INSTANCENAME=<InstanceName> REINSTALL=SQL_Engine
REBUILDDATABASE=1 SAPWD=<NewStrongPassword> collation=latin1_general_ci_as

If Model and MSDB Database will crash what you will do? How to rebuild Master Database?
We can re-create Model and MSDB databases by rebuild the Master Database.
SQL Server 2000 (Rebuild MasterDB):- Start > Run > rebuildm.exe
SQL Server 2005 (Rebuild MasterDB):- Start > Run > setup.exe

How to move Model, MSDB?


a. Check the Path of TempDB through sp_helpdb msdb
b. Start sql service in single user mode net start mssqlserver /m /t3608
c. Detach the db sp_detach_db msdb
d. Attach db sp_attach_db @dbname=’msdb’,@filename1=’path1’,@filemane2=’path2’
e. Check the current location and restart server in multi user mode
How to move tempdb?
a) No need to start server in single user mode
b) ALTER DATABASE tempdb MODIFY FILE (NAME = ‘tempdev’, FILENAME = 'E:\tempdb.mdf'),
c) ALTER DATABASE tempdb MODIFY FILE (NAME = ‘templog’, FILENAME = 'E:\tempdb.ldf')
d) Check the current location and restart server.
How to move Master Database?
a. Check the Path of Master DB through sp_HelpDB Master
b. Stop the Services
c. Change the path at Startup parameters SQL Server Configuration manager > Services > Right click on
Service > Properties > Advanced > Add new_path at Startup parameters
d. Move the files to desired location
e. Restart the Services
f. Check the Path of Master DB through sp_HelpDB Master

How many ways you can move the data or databases between servers and databases?
SSIS, DTS, Attach & Detach, Backup/Restore, BCP, Replication, Log shipping, INSERT...SELECT,
SELECT...INTO

Explain the architecture of SQL Server?


Questions are collected by K.V.N SUBBA REDDY
Sql Server is having Physical database and logical database
In physical database-Filegroups, transcation log
Filegroups contains – datafiles, datafiels contains – tables ,tables contains – Extents.Extents contains –
pages,Pages - Rows
Trancastion log is user defined file group by default it is primary file group,
Logical database objects like storedprocedre, views, indexes, triggers

Explain about Data files (.mdf, .ndf, .ldf) (File structure)?


Primary Data file (.mdf):- Primary data files holds user data and objects. Every database has one primary data
file.
Secondary Data file (.ndf):- Secondary Data file (.ndf) is optional and hold user data and objects that do not fit
in the Primary data file. We can add N no. of Secondary data files (Max 32,567) for a DB. Max size for data file:
16TB
Log Data file (.ldf):- T.Log records all the transactions and database modifications made by each transaction
and it is used to recover the database. At least one transaction log file required for each DB. Max size for log file:
2TB
.
File Group: To group similar data files logically,By default every db consists of PRIMARY file group.We can add
our own file groups,File group are provided unique id starts from ” 1”..Log files are never part of file group.
Primary FG: Contains primary data file, all pages for the system tables are allocated in primary FG.
User Defined: User-defined filegroups are any filegroups that are specified by using the FILEGROUP keyword
in a CREATE DATABASE or ALTER DATABASE statement.

What is page/ How store the data in SQL Server?


The fundamental unit of data storage in SQL Server is the page. The page size is 8 KB
Types: BDDGIIPT
1. Data: Consists of actual data.
2. Index: Consists Index entries
3. Text/Image: Consists of data whose data type is Text, Varbinary (max), and Image...
4. Global Allocation Map (GAM): Consists of information of extents.Howmany are free, How many are used.
Shared Global Allocation Map (SGAM): Maintain mixed extents.
5. Page Free Space: Consists of page nos and free space available
6. Index Allocation Map (IAM): Consists of pages nos which are allocated to table or index.
7. Bulk Changed Map (BCM): consists of extents information which is modified after bulk operation.
8. Differential Changed Map (DCM): Consists of info. of extents modified after BACKUP DATABASE cmd

What are the types of Extents?


Extents are the basic unit in which space is allocated to tables and indexes. An extent is 8 contiguous pages, or
64 KB.
Two types: Uniform extents are owned by a single object; all eight pages in the extent can only be used by the
owning object.
Mixed extents are shared by up to eight objects. A new table or index is usually allocated pages from mixed
extents. When the table or index grows to the point that it has eight pages, it is switched to uniform extents.

How to know server was started?


1. Using tempdb creation date R.C on temp->properties->check the property “Date created”
2. Server dash board report R.C on servername->reports->std.reports->server dash board->check “server
startup time”

How to copy the tables, schema and views from one SQL Server to another?
There are multiple ways to do this.
1. “Detach Database” from one server and “Attach Database” to another server.
2. Manually script all the objects using SSMS and run the script on new server.
3. Use Wizard of SSMS.

How to copy data from one table to another table?


There are multiple ways to do this.
1) INSERT INTO SELECT: This method is used when table is already created in the database earlier and data
is to be inserted into this table from another table
2) SELECT INTO: This method is used when table is not created earlier and needs to be created when data
from one table is to be inserted into newly created table from another table. New table is created with same data
types as selected columns.

Security Features:
Principles: Windows (Gropus, Domain Account, Local Account)
Questions are collected by K.V.N SUBBA REDDY
SQL Sever (SQL Account, Server Role)
Database (user, Database role, Application role, Group)
Permissions:
GRANT/REVOKE/DENY(Create,Alter,Drop,Control,Connect,Select,Execute,Update,Delete,Insert)
Securable: Server Scope (Logins, End points, Databases)
Database scope (Users, Assembles, Schemas)
Schema scope (Table, Procedures, Views)

Setting Authentication modes:From SSMS(R.C on server name->properties->security)


From windows registry(Strat->run->regedit……->mssqlserver->double click on login mode->set value 1 or 2.
1.Windows Authentication mode 2.Mixed mode Authenication
To check authentication through sp_readerrorlog.

Windows Authentication mode works: User connects to active directory server with domain credentials.
DC verifies the credentials and it sends unique no to client called TGT(Ticket Granting Ticket)
Client Machine produces TGT to Sql server and connects to sql server if there is mapping login
Syntax: Create login [domain/username] from windows [with default_database=<dbname>] For Windows
AM
Create login <loginname> with password=’....’ [default_database=’...’,
check_policy=on/off,check_expiration=on/off]
Create user <username> for login <loginname>

What is SQL Server Authentication?


When SQL Server authentication is used, SQL Server authenticates the client by comparing user name and
password with user names and passwords maintained within SQL Server.

What is the difference between Windows Authentication and SQL Server authentication?
1) Windows authentication is highly secure than SQL Server authentication why because we need not provide
any login details. So the chance of tracing login details from code by the unauthorized persons will be less.
Windows authentication uses the default windows login credentials.
2) Windows authentication will uses the credentials of the currently logged user to login in to the SQL Server
database. Your application need not to supply the user name and password.
3) For SQL Server authentication we have to supply the SQL database user name and password. That will be
used to get the privileges and right of the user.

Orphaned Users? How to find Orphaned Users and Resolve them?


When a DB is move, attach & detach, restoring to different instance or corresponding login is dropped, the users
of the Database becomes Orphaned users and they can’t access the database because the database users are
not mapped to SID (Security Identifier) in the new instance.
To detect Orphaned users:- sp_change_users_login 'Report'
To Resolve Orphaned Users:- sp_change_users_login 'Update_One', 'db_user', 'login_name'

Orphan Login: The windows login for which there is no mapping user in active directory is called orphan
login.
To find Orphan login:sp_validatelogins

Role:Collectins of priveileges
server roles Fixed database roles
1. sysadmin 1. db_owner
2. serveradmin 2. db_accessadmin
3. setupadmin 3. db_securityadmin
4. dbcreater 4. db_ddladmin
5. processadmin 5. db_datareader
6. securityadmin 6. db_denydatareader
7. diskadmin 7. db_datawriter
8. bulkadmin 8. db_denydatawriter
9. db_bacupoperator
10. public

Fixed server role:sp_addsrvrolemember [@loginame =] 'login', [@rolename =] 'role'


sp_dropsrvrolemember [@loginame =] 'login', [@rolename =] 'role'
sp_helpsrvrole [[@srvrolename =] 'role'] --To return a list of
FixedServerRoles

There are three kinds of the database roles:


Questions are collected by K.V.N SUBBA REDDY
1. Fixed Database Roles
2. Customs Database Roles.
3. Application Roles

Fixed Database Roles:


sp_addrolemember [@rolename =] 'role',[@membername =] 'security_account'
sp_droprolemember [@rolename =] 'role', [@membername =] 'security_account'
sp_helprolemember [[@rolename =] 'role'] -----To return a list of FixedDatabaseRoles
Customs Database roles:Create role <rolename>
Grant select,insert on emp to <rolename>
Adding users to role sp_addrolemember @rolename=’…’,@membername=’…’
Application Roles: Create application role And Grant permissions to the role
sp_addapprole [@rolename =] 'role', [@password =] 'password'
sp_dropapprole [@rolename =] 'role'
To change the pwd : sp_approlepassword [@rolename =] 'role', [@newpwd =] 'password'

Permissions(Grant/Revoke/Deny)
1.Databaselevel:privileges like backup database,create table, show plan, alter table, select insert, update
Grant ……to <username>/<rolename>[WITH GRANT OPTION]
2.schema level:To group similar tables in database we can create schemas.
By default every table is stored in ‘dbo’ schema
Adv: to group similar tables,to grant permissions on more than one table at once.
No need to change the owner of table(s) if the user is deleted.
Syn: create schema <schemaname>
Create table <schemaname>.<tablename>(….)
To transfer dbo.emp into library schema ---> alter schema library transfer dbo.emp
To grant schema level permissions---->GRANT….on schema::[schemaname] to <username>/<rolename>
3.object level:GRANT….ON <objectname> to <username>/<rolename>

Where SQL server user names and passwords are stored in SQL server?
They get stored in System Catalog Views sys.server_principals and sys.sql_logins.

What are the Database States?


The main database states are online, offline, restoring, recovering, resource pending, suspect and emergency.

Where SQL server user names and passwords are stored in SQL server?
They get stored in System Catalog Views sys.server_principals and sys.sql_logins.

What is an alias and how does it differ from a synonym?


An alias is an alternative to a synonym, designed for a distributed environment to avoid having to use the
location qualifier of a table or view. The alias is not dropped when the table is dropped.

What are table qualifiers? When should table qualifiers be used? Syntax:[@table_qualifier =] qualifier
Is the name of the table or view qualifier. qualifier is sysname, with a default of NULL. Various DBMS products
support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database
name. In some products, it represents the server name of the table’s database environment.

What are synonyms?


Synonyms give you the ability to provide alternate names for database objects. You can alias object names; for
example, using the Employee table as Emp. You can also shorten names. This is especially useful when dealing
with three and four part names; for example, shortening server.database.owner.object to object.
SYNONYM is a single-part name that can replace a two, three or four-part name in many SQL statements.
Using SYNONYMS in RDBMS cuts down on typing.
Syntax CREATE SYNONYM [ schema_name_1. ] synonym_name FOR < object >
< object > :: = { [ server_name.[ database_name ] . [ schema_name_2 ].| database_name .
[ schema_name_2 ].| schema_name_2. ] object_name }
Ex: create synonym cust_syn for Library.customers

Encryption/Decryption:Create master key-create master key encryption by password=’pwd@1’


Create certificate
Create symmetric key
Encryption data by using encryptbykey() function
Questions are collected by K.V.N SUBBA REDDY
Public Key Cryptography (PKI) is a form of message secrecy in which a user creates a public key and a
private key. The private key is kept secret, whereas the public key can be distributed to others.
A certificate is a digitally signed security object that contains a public (and optionally a private) key for SQL
Server. You can use externally generated certificates or SQL Server can generate certificates
Create certificate <certificate name> with subject =’….’

Asymmetric keys are used for securing symmetric keys. They can also be used for limited data encryption and
to digitally sign database objects. An asymmetric key consists of a private key and a corresponding public key.

Symmetric Keys A symmetric key is one key that is used for both encryption and decryption. Encryption and
decryption by using a symmetric key is fast, and suitable for routine use with sensitive data in the
database.
Create symmetric key <keyname> with ALGORITHAM=DES/SHA1/MD5
encryption by certificate <certificatename>

Transparent data encryption (TDE) performs real-time I/O encryption and decryption of the data and log files.
The encryption uses a database encryption key (DEK).It can’t encrypt or decrypt individual pieces of data, it
can’t be used to restrict access to data. Steps: Create master key
Create or obtain a certificate a protected by master key.
Create a database key and protect it by the certificate
Set the database you want to protect to use encryption

What is SQL Server Agent? SQL Server agent plays an important role in the day-to-day tasks of a database
administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is
to ease the implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to
schedule your own jobs and scripts.
Whenever user wants to get sql sever agent what permissions you to give?
Three roles are there in MSDB database
1)sql agent user role 2)sql agent reader role 3)sql agent operator role
Path:Security->Login->Usermapping->select MSDB->select permissions

SQL Server Auditing: Auditing an instance of sql server or a sql server db involves tracking and logging events
that occurs on the system. Steps: 1.Server audit specifications (events to capture on the server instance
level).
Database audit specification(events to capture on specific database)
Target (wherewould be the events be logged)
To find: sys.dm_server_audit_status
sys_database_audit_specifications

What is Service Broker?


To establish communications between sql server engine and database mail engine we need service broker
Service Broker is feature which provides facility to SQL Server to send an asynchronous, transactional message.
It allows a database to send a message to another database without waiting for the response, so the application
will continue to function if the remote database is temporarily unavailable.

What are Sparse Columns?


A sparse column is another tool used to reduce the amount of physical storage used in a database. They are the
ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements
for null values at the cost of more overhead to retrieve nonnull values

What does TOP Operator Do?


The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new
addition in SQL SERVER 2008 that it accepts variables as well as literal values and can be used with INSERT,
UPDATE, and DELETES statements.

What is Catalog Views?


Catalog views return information that is used by the SQL Server Database Engine.
All user-available catalog metadata is exposed through catalog views.

What is Filestream?
Filestream allows you to store large objects in the file system and have these files integrated within the
database. It enables SQL Server based applications to store unstructured data such as documents, images,
audios, videos etc. in the file system. FILESTREAM basically integrates the SQL Server Database Engine with
Questions are collected by K.V.N SUBBA REDDY
New Technology File System (NTFS); it basically stores the data in varbinary (max) data type. Using this data
type, the unstructured data is stored in the NTFS file system and the SQL Server Using Transact SQL
statements users can insert, update, delete and select the data stored in FILESTREAM enabled tables.

What is Dirty Read?


A dirty read occurs when two operations say, read and write occurs together giving the incorrect or unedited
data. Suppose, A has changed a row, but has not committed the changes. B reads the uncommitted data but his
view of the data may be wrong so that is Dirty Read.
Dirty Page: Data that has been modified and Stored in the buffer cache and has not yet been Written in to the
hard disk

What are “Unrepeatable reads”? Inconsistent Analysis (Nonrepeatable Read) occurs when a second
transaction accesses the same row several times and reads different data each time. Inconsistent analysis is
similar to uncommitted dependency in that another transaction is changing the data that a second transaction is
reading..

What is “Phantom rows”? Phantom reads occur when an insert or delete action is performed against a row
that belongs to a range of rows being read by a transaction. The transaction’s first read of the range of rows
shows a row that no longer exists in the second or succeeding read, as a result of a deletion by a different
transaction. Similarly, as the result of an insert by a different transaction, the transactions second or succeeding
read shows a row that did not exist in the original read.

What are the New Data types introduced in SQL Server 2005?
SQL Server 2005 has added some new data types to its existing data types.
XML Data type
1. VARCHAR (MAX)
2 .NVARCHAR (MAX)
3. VARBINARY (MAX)

What is CTE?
CTE is an abbreviation Common Table Expression. A Common Table Expression (CTE) is an expression that
can be thought of as a temporary result set which is defined within the execution of a single SQL statement . A
CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.
What are the Advantages of using CTE?
• Using CTE improves the readability and makes maintenance of complex queries easy.
• The query can be divided into separate, simple, logical building blocks which can be then used to build
more complex CTEs until final result set is generated.
• CTE can be defined in functions, stored procedures, triggers or even views.
• After a CTE is defined, it can be used as a Table or a View and can SELECT, INSERT, UPDATE or
DELETE Data.

What is MERGE Stamemt?


MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions
of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain
conditions, but now, using MERGE statement we can include the logic of such data modifications in one
statement that even checks when the data is matched then just update it and when unmatched then insert it.
One of the most important advantages of MERGE statement is all the data is read and processed only once.

What is XML Data type?


The xml data type lets you store XML documents and fragments in a SQL Server database. An XML fragment is
an XML instance that is missing a single top-level element. You can create columns and variables of the xml
type and store XML instances in them. The xml data type and associated methods help integrate XML into the
relational framework of SQL Server.

What is bit data type?


Bit data type is used to store Boolean information like 1 or 0 (true or false).

What is Query Optimizer?


Query Optimizer will correctly evaluate a query and run it as optimally as possible. But on occasion the Query
Optimizer will fail, producing a less than optimal execution plan, and query performance will suffer because of it.
When you identify such a query, You can override the Query Optimizer using what is called an Optimizer Hint.
Optimizer hints can be divided into five different categories:
1. Table Hints: Used to force index selection. 2. Join Hints: Used to specify the type of JOIN strategy
used.
Questions are collected by K.V.N SUBBA REDDY
3. Query Hints: Hints used to affect GROUP BY and UNION functionality. 4. Lock Hints : Used to help avoid
undesirable locking.
5. View Hints: Used to specify indexes in indexed views. 6. Other Hints:Misc.Hints

What are the Protocols used in Networking? What is the Default Port number of TCP/IP?
The protocols used in networking are TCP/IP, NAMED PIPPES, VIA, SHARED MEMORY. The default port no of
TCP/IP is 1433. Named pipes communicates across TCP port 445 UDP: 1434
VIA The Virtual Interface Adapter (VIA) can be used only by VIA hardware.
Shared Memory Shared Memory can only be used on the local computer and cannot be used as a network
protocol.

How many bits IP Address consist of? An IP Address is a 32-bit number

How many layers of TCP/IP protocol combined of? ATIDP


Five. (Application, Transport, Internet, Data link, Physical).

What’s a “SAND BOX” in SQL SERVER 2005?


“Sand box is a safe place for running semi-trusted programs or scripts, often originating from the a third party”

What is Row size of a Database? Row size of a database is 8060 bytes.


Max.no.of columns a table can have? 1024 in Sql Server R2

Explain Full, Bulk-Logged & Simple Recovery Models?


a) Full:- With Full Recovery Model we can recover the data up to the minute of crash, because it records
every operation in the transaction log. Log file grow fastly.To control log file growth we have to configure
regular log backups. When a check point is issued it doesn’t clears the log of the previous transactions
we can configure all types backups. We can configure log shipping and mirroring. Recommended for
real time production databases.Dis.Adv: Can take up a lot of disk space
b) Bulk-Logged:- With Bulk-Logged recovery model we can recover most of the data, but we will lost bulk-
operations because those are not recorded in to the log. We can set this option just before performing a
bulk insert operation to speed up the bulk insert. Recommended for data ware housing databases where
bulk operations take place. In this type of recovery model the log file maintains the complete log of
simple transactions (insert, update, delete) and the bulk transactions are maintained minimally. When a
check point is issued the existing transactions will not be cleared, due to this the log file size continuous
to increase Log file is truncated at the times of log backup. Only log shipping possible. Dis.Adv: Not for
production systems, Point in time recovery not possible
c) Simple:- With Simple Recovery Model we can recover the data only up to the last backup, because
nothing is recorded in the transactional log. Any changes made to database after the last backup was
performed will be lost because they are not recorded in the transaction log. In this recovery model, when
a check point is issued it clears the log of existing transactions. Due to this the log file always contains
the free space. Log file size does not increase. It is not possible to perform the transaction log backup.
Generally it is useful for test and development databases or Data warehouses, but it is not appropriate
choice for Production Database. .
Dis.Adv: Not for production systems, Point in time recovery not possible

Database backup: It is the process of taking data, meta data and services present in the database into O/S file.
Backup can generate in two types of files. The files are .BAK and .TRN.We can provide more security for data.
We copy/move database from one server to another, We can implement standby solutions with log shipping. To
recover data up to point of failure .i.e. to avoid data loss.Sys admin, db_owner and db_backupoperator can take
backup.

What is Full, Diff, T.Log Bakups? Explain Each?


a) Full Backup:- Full backup, backs up the entire Database including Transaction Log. With full
Backup Point-in-time recovery is possible because it contains .mdf and .ldf. It offers complete
protection against media failures. It takes more time & requires more space to store the backup file
b) Differential Backup:- Differential backup records only the data that has change or modified extents
since the last full backup. Takes less time and requires less space. To perform the differential
backup we require at least one full backup.
c) T.Log Backup: - Transaction Log that records all transactions since last transaction log backup or
differential backup. It can be used for recover the data to the point of failure (or) specific point-in-
time. These are the incremental backups, it is possible only in Full and Bulk logged recovery,
models only. It is used to truncate the T.log periodically. To implement log shipping
d) File/File Group backup:- File and File group backups are a specialized form of DB backup. In
which only certain individual file (or) file groups from a DB are backup.
e) Copy only backups :If we want backup without effecting existing plan we can use copy only
backups. sql server supports copy-only full backup and copy only t.log backup.
Questions are collected by K.V.N SUBBA REDDY
f) Striped backups:If the size of backup is large where there is no required disk space in any drive
we can split backup into mulitiple files into different disks..
g) Mirrored Backups: In order to reduce restoration problems we can take backup of same db in
multiple locations so that if any meadi set is get damaged we can restore from othe.Max we can
write 4 mirros for same media set.

What are the Syntaxes for Backups?


a) Full Backup: - Backup database dbname to disk = “path”
b) Diff. Backup: - Backup database dbname to disk = “path” with differential
c) T.Log Backup:- Backup log dbname to disk = “path”
d) File/File Group backup:-backup batabase <dbname> filegroup=’FG name’ to disk=’path’.
e) Copy only backups : Backup database/Log dbname to disk = “path” with copy only
f) Striped backups:Backup database dbname to disk = “path1,to disk=’path2’ WITH
NOFORMAT,STATS=10
g) Mirrored Backups: Backup database dbname to disk = “path’, MIRROR TO disk=’path2’ WITH
FORMAT
*INIT mean overwrite noinit mean append, format mean independent ,noformat:both files are
required

What is Mean Cold backup (Offline Backup) and hot backup (Online Backup)
Cold backup: while taking the cold backup the database will not be accessible by other users (single user mode
or emergency mode (any administrator)), Hot backup: while taking the backup the database will be accessible
to all the users (online)

To disp backup header: restore headeronly from disk=’..Path... .’


To disp files taken into backup: restore filelistonly from disk=’..Path..’
To verify backups: restore verifyonly from disk=’..Path..’

Non Logged operations: BCP, Bulk Insert, Select Into, Index, Text, Next data types

My Backup is fails, what may be the possible reasons?


 No disk space (error: 3271)
 Server was busy
 MSDB was offline
 Agent service was stopped
 N/W problem
 If the server is running on domain account and if the domain is not online.
 T.Log file was full

How to take backup of 400GB DB with in less time?


Generally 1 GB takes 1 min, If we use stripped backups we can reduce time, If we have 4 processors and 4
drives
Who taken backup? sys_admin,db_owner,db_backupoperator

To clear backup history from MSDB database: Sp_delete_backuphistory ‘2012-08-30 11:11:11’

Tables related to backup: In MSDB, we have 5 tables related to backups.


Backupset: Complete backup details. Types D-Full I-Differential F-File/File Group L-T.log Backup FG-File
Group.
BackupMedia Family: Consists of file path.
BackupMediaset: Compression and mirror details.
Backupfile: File names which are taken into backup.
Backup file group: File group names which are taken into backup

Explain about Tail of Log? Give the syntax?


The tail-log backup is the last backup that have not been backed up earlier, to recover the database to the point
of a failure.
Syntax :- 1) BACKUP LOG database_name TO <backup_device> WITH NORECOVERY
2)BACKUP LOG database_name TO <backup_device> [WITH {CONTINUE_AFTER_ ERROR|NO_TRUNCATE
}

Check Point: It is a program executed by SS to take all committed transactions ftom T.Log into datafile.
It takes all committed transactions details (LSN<Pageid) from T.Log file and submits to Lazy writer.
Lazy writer is one of background process which takes the pages from data cahe and writes to data file
Check point truncates t.log file if the recovery model is SIMPLE
Questions are collected by K.V.N SUBBA REDDY
Check point occurs In the following scenarios
Periodically (Depends on recovery interval of SS) R.C on server->properties->Database settings-
>Recovery interval=1.
When the database backup is about to start And If server is started
If the T.log is 70% full and it is in log truncate mode.
When the data or log file is added or removed from a database.
When recovery model is changed.
CHECKPOINT ---> To Manually perform check point command (or) sp_configure 'recovery interval', 32767)
To verify Check point: Sp_who2 or DBCC log (‘dbname’, 3) Ex: dbcc log(test).
To start sql service without raising checkpoint SHUTDOWN WITH NOWAIT

What is RMAN? Recovery Manager (RMAN) is a utility that can manage your entire Oracle backup and
recovery activities.
Which Files must be backed up?
Database Files (with RMAN) Control Files (with RMAN) Offline Redolog Files (with RMAN)
INIT.ORA (manually) Password Files (manually)
Benefits: 1. Incremental backups that only copy data blocks that have changed since the last backup.
2. Tablespaces are not put in backup mode, thus there is no extra redo log generation during online backups.
3. Detection of corrupt blocks during backups.
4. Parallelization of I/O operations.
5. Automatic logging of all backup and recovery operations.
6. Built-in reporting and listing commands.

Can we change recovery model for System Database? YES, we can change recovery model
Database Default Can be changed or not
Name Recovery
Model
master Simple Not Applicable, technically, YES you can set to FULL or BULK logged but the database
continues to operate as simple recovery model only. you can not perform BACKUP
LOG even you change that to full / bulk logged
model FULL can be changed and set to FULL or BULK Logged
msdb SIMPLE can be changed and set to FULL or BULK Logged
tempdb SIMPLE Can not be changed
distribution SIMPLE YES, but distribution db just stores metadata and history data for replication, but a FULL
recovery model is recommended.
resource N/A recovery model is not relevant to resource database
Database Backup Requirements
Database Backup Requirements Full Backup Differential Transaction Log
Database Name
Critical Daily 6 Hourly 5 to 15 minutes
High Daily 6 Hourly Hourly
Medium Weekly Daily Hourly
Low* Weekly Daily N/A
*Database in simple recovery mode
System Database Database Full Backup Differential Transaction Log
master Daily N/A N/A
msdb Daily 6 Hourly N/A
model Weekly N/A N/A
distribution* Daily 6 Hourly Hourly
*if replication is enabled
SQL Server Database Restore
Single Database All Databases Full Failover
Database
Critical Databases Weekly 􀂉􀂉 Monthly 􀂉􀂉 Quarterly 􀂉􀂉
High Databases Monthly 􀂉􀂉 Quarterly 􀂉􀂉 Yearly 􀂉􀂉
Medium Databases Monthly 􀂉􀂉 Quarterly 􀂉􀂉 Yearly 􀂉􀂉
Low Databases Monthly 􀂉􀂉 Quarterly 􀂉􀂉 Yearly 􀂉􀂉

What is Restore? What are the recovery states? Explain Each?


Restore means recover the data from backups. There are three recovery states for Restore.
Questions are collected by K.V.N SUBBA REDDY
a) With Recovery:- With Recovery, Database will comes to Online and get ready to using Database.
Generally while restoring recent (last) T.Log we can choose with recovery option. We cannot apply
further backups.
b) With No-Recovery:- With No-Recovery Databases will come to Offline and we can’t access DB.
Generally except recent log we can choose With No-Recovery option. We can apply further backups.
In Mirroring we have to restore database in mirror server WITH NORECOVERY
c) Standby:- With Standby, Databases will come to Offline and users can have read only access.
Generally except recent log we can choose Standby option for Read only access. It allows further
backups to be restored. In Log shipping in stand by server we will maintain database in read only
mode.
We can get complete restoration details in the following MSDB tables
Restore History, Restore File, Restore File Group
To restore database the user must have either sysadmin or dbcreater role.

How to backup Resource database?


In order to take the backup of restore database we need to perform file based or disk based backup of the
Mssqlsystemresources.mdf and Mssqlsystemresources.ldf files, by copy paste method. There is no Full backup
or online backup for this database. Sql server will allow Resource database related MDF and LDF files to copied
even when sql server is running.
How to restore resource database?
Use copy paste method only, overwrite the existing file from the backup location

Why in Simple Recovery model we can’t take T.Log backups?


In Simple Recovery Model the Transaction Logs are truncated.

What are the Syntaxes for Restore?


a) With Recovery:-Restore database dbname from disk = “Path” with recovery
b) With No-Recovery:- Restore database dbname from disk = “Path” with no recovery
c) Standby:- Restore database dbname from disk = “Path” with standby

What is Point-in-time restore and use of that?


Point-in-time restore is used to restore the Database to a particular time just before a failure has occurred or
before corrupt data.STOPAT clause is used to restore a data base at point of time.
Restore log <dbname> from disk =’path’ with stop at=’date and time’

What are the common scenarios to Restoring the Data?


 To restore the lost and corrupted data after a system failure
 To restore a database onto a development system for user by application developers while developing
and testing new code.
 To restore a database onto a test system to load test applications and database features.
 To restore a database on separate server as a read-only database to perform queries for reports.

In which edition On-line restoration is possible? On-line restoration is possible only in Enterprise edition.

What is default recovery model for a new database ?


By default SQL Server sets FULL recovery model for all newly created database as it copies values from
model database.

What is the best recovery model, which should be used?


Where Data is critical and data loss can not be afforded a FULL recovery model is suggested
But for development servers where database can be refreshed by production, and space is concern, then
SIMPLE recovery mode can be turned on.

Does Recovery Model affects database transaction log ? YES,The full recovery model might consume all
available disk space, if appropriate database maintenance is not performed as log keep growing.

Does SQL Server recovery model affects SQL Server Performance ?


Technically, small transaction didn’t shown any performance affect but yes, recovery model affect database
performance for large transactions.Full logged provide slow response time for large / bulk operations where bulk
logged / simple gears up large transaction.

Does the recovery model effect the database size / disk ? YES,The full recovery model might consume all
available disk space, if appropriate database maintenance is not performed as log keep growing.
Questions are collected by K.V.N SUBBA REDDY
Is SQL Server recovery mode and Recovery model is same thing ? YES, is one of the same thing.

Does SQL Server recovery model affects your database recovery?


YES, your data safety/recovery depends on recovery model in case of disaster.
• Simple Recovery Model – suits for databases in which data changes infrequently.
• Full Recovery Model – best suits for production OLTP systems where full recovery from damaged
media is the highest priority.
• Bulk-logged Recovery Model - Similar to the full recovery model, the bulk logged recovery model uses
both database and log backups to re-create a database.

What is the best recovery model for recovery point of view ?


Where Data is critical and data loss can not be afforded a FULL recovery model is the only option as this
supports point in time recovery.

Which recovery model gives a best sql server database performance ?


Simple Recovery Model – It allows for the fastest bulk operations and the simplest backup-and-restore
strategy.
Bulk_Logged Recovery Model – allows recovery in case of media failure and gives best performance using
least log space for certain bulk operations like BULK INSERT, bcp, CREATE INDEX etc.

What is Database Recovery Advisor ?(Introduced in Sql server2012)


Database Recovery Advisor is Graphical tool for performing POINT in TIME Recovery for any SQL Server
Database.

Restore Strategy?
 First restore recent last full backup
 Then restore last Diff. backup
 Then restore all Transaction Log backups.

Backup Compression:we can compress upto 75%


Sp_configure ‘backup compression default’,1
Backup database <dbname> to disk=’path’ with compression/no_compression

What is Data Compression?


In SQL SERVE 2008 Data Compression comes in two flavors: 1.Row Compression 2.Page Compression
Row Compression: Row compression changes the format of physical storage of data. It minimize the metadata
(column information, length, offsets etc) associated with each record. Numeric data types and fixed length
strings are stored in variable-length storage format, just like Varchar.
Page Compression: Page compression allows common data to be shared between rows for a given page. Its
uses the following techniques to compress data:
1. Row compression. 2. Prefix Compression. 3. Dictionary Compression.
The main difference between prefix and dictionary compression is that prefix is only restricted to one column
while dictionary is applicable to the complete page.

Data Transformation Services (DTS) is a set of tools available in SQL server that helps to extract (Import or
Export), transform and consolidate data.

Logshipping
What is Log shipping and purpose of Log shipping?
To achieve high availability and high protection, Log shipping copies transactions from a ‘primary server’ to one
or more ‘secondary servers’. In Log shipping, T.Log backups are sent to one or more secondary servers and
then restored to the destination servers individually. If the Primary database becomes unavailable, any of the
secondary database can brought into online manually. The Secondary server acts as a Backup server and
provides read-only query processing to reduce the load on the Primary server. (For query processing, secondary
servers should be configure in stand-by mode).

What is Primary Server, Secondary Server & Monitor Server?


Primary Server: - Primary Server is a Production server which holds the original copy of the database. Log
shipping configuration and administrating will be done from Primary Server.
Secondary Server: - Secondary servers hold the standby copy of the database. We must initialize the DB on a
secondary server by restoring a backup from the Primary server using either NORECOVERY option or the
STANDBY option. By using STANDBY option Users can have read-only access to it.
Questions are collected by K.V.N SUBBA REDDY
Monitor Server: - An optional Server is called as Monitor Server that records history and status of backup, copy
and restore operations and raises alerts if any operations fail. The Monitor Sever should be on separate server
to avoid losing critical information. Single Monitor Server monitors multiple Log shipping configurations.

Standby Servers and Types of Standby Servers


Standby servers - Standby Server is a type of server that can be brought online in a situation when Primary
Server goes offline and application needs continuous (high) availability of the server.
Hot Standby – Hot Standby can be achieved using SQL Server 2005 Enterprise Edition and the later enterprise
versions. SQL Server 2005 has introduced Mirroring of database that can be configured for automatic failover in
a disaster situation.
Warm Standby – In Warm Standby automatic failover is not configured. This is usually set up using Log
Shipping or asynchronous mirroring.
Cold Standby – Code Standby servers need to be switched manually and sometimes all the backups as well as
the required OS need to be applied. Cold Standby just physically replaces the previous server.

What are the Jobs running for Log shipping and explain them?
Log shipping having four operations which are handled by SQL Server Agent Job.
Backup Job: - Backup job is created on Primary Server instance and it performs backup operation. It logs history
on the local server and monitor severs and deletes old backup files and history information.
Copy Job: - Copy Job is created on Secondary server instance and it performs copies the backup files from
primary sever to secondary server. It logs history on the secondary server and monitor server.
Restore Job: - Restore Job is created on the Secondary server instance and it performs restore operation. It logs
history on the local server and monitor sever and deletes old files and history information.
Alert Job: - If a Monitor Server is used, the Alert Jobs is created on the Monitor server instance and it raises
Alerts if any operations have not completed successfully.

Requirements for Log shipping?


 Minimum 2 servers are required
 SQL Server 2005 Standard Edition, Workgroup Edition, or Enterprise Edition must be installed on all
server instances involved in log shipping.
 All servers should have the same case sensitivity settings.
 The databases must use the full recovery model or bulk-logged recovery model.
 We should have sysadmin privileges on both servers.
 Enable remote connections to the server in sql surface area configuration (menu->all programs-
>Microsoft sql 2008 -> configuration tools ->surface area configuration for services and connection
options -> select remote connections -> select local and remote connections by using tcp and named
pipes option
 The sql services in both the primary and secondary server should be the same with same password
 Share folder should be created in primary server to hold the tran log backups

Prerequisites and Limitations


It is important to note the following caveats with log shipping:
• You can ship all databases, except read-only, tempdb, model and any databases not in full recovery model or
simple recovery model.
• During defragging/indexing/re-indexing operations, the transaction log's backup files can become very large.
To keep the size of the transaction logs to a minimum, you can switch between full and bulk logged recovery
models (bulk logged operations minimally log indexing operations).
• Certain operations will "break" log shipping, like changing the recovery from full or bulk logged recovery model
to simple recovery model.
• Log shipping operations will have to be suspended during a backup operation.
• The latency period (how out of sync the primary will be from the secondary) can vary; one example would be a
log shipping scenario where you back up the transaction logs every 10 minutes. A transaction log backup
starting at 1:00 a.m. may take 10 minutes to complete. It may take another five minutes to copy the backup to
the destination server. This means your exposure to data loss will be 15 minutes. Consider what would happen if
your server crashed at 1:09 a.m. Your backup would not be generated or copied to the secondary/standby
server, and the data on your secondary server would be as of 12:50 a.m.
• Log shipping is not considered to be a highly scalable operation for topologies
that involve a large number of databases.
• All dependencies must be in place on the secondary server (for example, logins, DTS or SSIS packages, SQL
Server jobs and any external dependencies).
• Clients will have to be manually redirected to the standby server.
• The application must be log-shipping aware – if the primary server goes offline, the data is queued on the client
until the standby server comes back online. Best practices dictate that this is a manual redirection; otherwise,
the application might redirect to the standby server prematurely or in error
Questions are collected by K.V.N SUBBA REDDY
How to configure Log shipping?
a. Choose Primary Server, Secondary Servers, and optional Monitor server.
b. Create a File share to keep Transaction log backups (Best to place on a separate computer)
c. Create a folder for each Secondary server into which transaction log backup copies.
d. Choose Backup Schedule for Primary Database
e. Choose Copy and Restore Schedules for Secondary Database
f. Choose Alert Job schedule for Monitor Server if configured

What are permissions required for Log shipping?


We must have sysadmin on each server instance to configure Log shipping.

In Logshipping which Recovery Models can we used?


We can use either full or bulk logged recovery model for log shipping.

Where you monitoring Log shipping and how?


We can monitoring the Log shipping in the following ways.
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
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).

sp_refresh_log_shipping_monitor: Refreshes the monitor with the latest information for the specified log
shipping agent.

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.
SQL Server Agent Job History
Checking the SQL Server Log

To display log shipping jobs select * from db.sysjobs where category_id=6

Log Shipping Options


• Interval – Default is 15 minutes. Consider the impact before using a smaller number
• Delayed log restore – option that allows you to have an older copy, for an “oops” situation
• If secondary is far behind. Consider backup/copy to media/restore, consider partitioning the data.
• Careful – Backup typically goes to a file server share. Agent account needs access to share.
• Careful – Weekend maintenance jobs (like indexing) can make you run out of disk space
• No option to synchronize logins – Consider sp_resolve_logins to import.
• Monitoring – MSDB tables, agent history

How Secondary Server will brought into Online, if the Primary Server becomes Unavailable?
If the Primary Server will become un-available, do the following steps.
1. Take the Tail of Log from Primary server with no recovery
2. Restore Tail of log into all Secondary Database with recovery
3. Remove Log-shipping configuration from Primary Server
4. Select any one of Secondary server and bring into online with Alter Database DBName set Online
5. Right click on Primary Database and Generate script for Users and Logins.
6. Then move the script to Secondary server to create Users and Logins
7. Re-configure log shipping from New Server (Secondary server)

.TUF File:Is transaction undo file.It is created when the configuare log shipping and if the secondary db is
STANDBY mode. This file is created in copy/restore folder in secondary server. It contains the information
regarding any modifications that were made as part of incomplete transactions at the time the backup was
performed.
Questions are collected by K.V.N SUBBA REDDY
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

Log Shipping Errors The following are the common log shipping errors and their solution I found. Hope this will
be helpful to everyone.
Error: 14262 :If SQL Server name is not the same as Windows Server name. You can check this by running
Select@@Version. The output of this query should be the name of your windows server name else you need to
perform the below steps, sp_dropserver ‘old server name’sp_addserver ‘new server name’, local
Error: 14420, The error indicates that the difference between the last T-log backed up file and current time on
the monitor server is greater than the time that is set for the Backup Alert threshold.
Error: 14421 indicates that the difference between the last T-log backed up file and last restored T-log file is
greater than the time selected for the Out of Sync Alert threshold.
Error 4323: The database is marked suspect. Transaction logs cannot be restored.
We had the same issue some time ago, this was related to a new file being created in a file group on the source.
Don't know if this applies to your case, but restoring a backup of this new file on the secondary server solved the
problem.
I've configured Log shipping successfully on standby mode, but in the restoration job I'm getting Error:
Could not apply log backup file 'C: \...trn' (Or) Error: Exclusive access could not be obtained because the
database is in use. RESTORE LOG is terminating abnormally
To restore transaction logs to the secondary db, SQL Server needs exclusive access on the database. When
you configure it in standby mode, users will be able to access the database and runs query against the
secondary db. Hence if the scheduled restore jobs runs at that time, the db will have a lock and it won't allow
SQL Server to restore the tlogs. To avoid this you need to check "Disconnect users in the database when
restoring backups" options in log shipping configuration wizard.

IS it possible to log ship database between SQL 2000 & SQL 2005?
No, that’s impossible, In SQL 2005 transaction log architecture is changed compared to SQL 2000 and hence
you won't be able to restore tlog backups from SQL 2000 to SQL 2005 or vice versa.

I'm getting the below error message in restoration job on secondary server, WHY? ( which is too late to
apply to the database) Was your sql server or agent restarted Y'day in either source or destination? Because
the error states there is a mismatch in LSN. A particular tran log was not applied in the destination server hence
the subsequent tran logs cannot be applied as a result !

What is SQL Server Disaster?


Disaster is an event that makes continuation of normal functions impossible. In business terms, any incident
which result affects business or stops business transactions is a disaster Disaster Scenarios are Human error
,System Failure / Malfunction , Hardware Failure Virus Attack Operational Errors Accidents ,Natural Disaster
and tsunami

What is Disaster Recovery ?


Disaster recovery is the process to continue business work after any disaster scenario

Is it possible load balance in log shipping?


Yes of course its possible in log shipping, while configuring log shipping you have the option to choose standby
or no recovery mode, there you select STANDBY option to make the secondary database readonly.

Can I take full backup of the log shipped database in primary server??
In SQL Server 2000 you won't be able to take full backup of log shipped database, because this will break the
LSN chain and it directly affects the log shipping. In SQL Server 2005, yes its possible. You can take full backup
of log shipped database and this won't affect the log shipping.

Can I shrink log shipped database log file??


Answer: Yes of course you can shrink the log file, but you shouldn't use WITH TRUNCATE option. If you use
this option obviously log shipping will be disturbed.

Can I take full backup of the log shipped database in secondary server?
No chance, you won't be able to execute BACKUP command against a log shipped database in secondary
server.

Is it possible to log ship database from SQL server 2005 to SQL server 2008 and vice versa?
Questions are collected by K.V.N SUBBA REDDY
Yes you can log ship database from SQL server 2005 to SQL Server 2008 this will work. However log shipping
from SQL Server 2008 to SQL Server 2005 is not possible because you wont be able to restore SQL server
2008 backup to SQL Server 2005 (downgrading version).

Mannualy restoring log backup with required file location


Restore log dbname from disk=’path’ with file=1 MOVE ‘database1’ to ‘path’, standby =’path…bak’

What are the endpoints in log shipping?what r the port numbers for log shipping?
We don't need to create endpoints or assign port in log shipping, which is required for database mirroring

What are the log shipping frequent issues you have faced?
It depends. I have seen some issues like transaction log cannot restored on the secondary database which is
due to that the transaction log sequence is broken.

Copy and restore jobs are not running?


Check secondary server date and time.i.e secondary server date and time is less than primary server.
Change the date of start for the above jobs equal to secondary server date.

Out Of sync (14421): if there is no disk space in secondary server for restoring
If there is no respective path to create the file in SS.
If there is ad-hoc t.log backup was taken.(To solve restore ad-hoc log backup)
If the agent service or msdb is not working in SS.
If any t.log backups are missing/corrupted before restoring (To solve disable log shipping jobs, Take DIFF/FULL
backup and apply in SS, Enable Jobs)

Advantages
1. Using immediate restore option, we can setup almost an exact copy of the production system at the
Secondary Server.
2. Delayed Restore; using this option you setup a secondary Server with the transaction Logs shipped but are
not restored immediately, this option would be highly helpful, if incase of Data Corruption / Loss because of a
User accidentally deleting / dropping / modifying important Data. If acted immediately, you should be able to
recover the Data from the Database on the secondary Server.
3. Multiple Secondary Databases can be setup for a single Primary Database, providing the option to use one
copy for DR and another for a reporting kind of use (The Users need to be disconnected when the Logs are
restored and that can be done Automatically by SQL Server), so restoring Job can be scheduled for every 6
Hours so as not to interrupt reporting users frequently.
4,One of the biggest benefits of log shipping is that it is a much cheaper high availability solution than clustering.
This is because the hardware requirements that are necessary for clustering are not required for log shipping.
5. Does not require expensive H/W and S/W.
6. It is reliable, easy to maintain,implemenet log shipping is not technically difficult.
7. Stand by server can be used to reporting purpose.

Dis-advantages
1. Automatic Redirection / Failover of the application is not possible.
2. When compared to Database Mirroring or Transactional Replication there is a slight delay in synchronizing the
Database at the secondary server.
3. Can be implemented only with Databases having FULL/Bulk-Logged Recovery model.
4. Sometimes Entire Database is not required for the application when coming back immediately from a
Disaster. Let me explain, a Database has multiple years (let’s say 7) of transactional Data and you may not need
the entire 7 years of Data when disaster strikes, the most recent few years (may be 2 or 3) is good enough to
start immediately. OR a subset of the Database is required for a Marketing application; you cannot provide it
using Log Shipping.
5. There will be some data loss because you can't configure the backup job to run less than 2 minutes

Mirroring
What is Database Mirroring? What are the benefits of that?
“Database mirroring is a method of increasing database availability”, which supports automatic failover with no
loss of data.
Benefits:-Increases data protection
Increases availability of a database
Improves the availability of the production database during upgrades

What are the prerequisites for Database Mirroring?


SQL Server 2005 with SP1 or SQL Server 2008
Database should be in FULL recovery model((Simple and bulk-logged not supported)
Questions are collected by K.V.N SUBBA REDDY
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.
All Servers should use the same master code page and collation
Mirror Server has same database name and use only With NoRecovery option.
All logins for connecting Principal Database should be reside on Mirror database

What are the Restrictions for Database Mirroring?


Maximum 10 databases per instance can support on a 32-bit system.
Database mirroring is not supported with either cross-database transactions or distributed transactions.

Explain about Principal, Mirror and Witness Servers?


1) Principal Server:- One Server serves the database to client is called Principal server and it having
original data. Can have only one Principal Server and it has to be on a separate server.
2) Mirror Server:- Other server instance acts as a hot or warm standby server is called Mirror server
and it having copy of database.
3) Witness Server:- The witness server is an optional server and it controls automatic failover to the
mirror if the principal becomes unavailable. To support automatic failover, a database mirroring
session must be configured in high-availability.

In which Operations are running the Operating Modes?


Asynchronous:- Under asynchronous operation, the Principal server does not wait for a response from the mirror
server after sending the log buffer.
Synchronous:- Under synchronous operation, the Principal server sends the log buffer to the mirror server, and
then waits for a response from the mirror server.

What are the Operating Modes and explain them?(Performing fail over)
a. High Availability:- High-availability mode, runs synchronously. Requires a Witness Server instance.
It makes mirror db online automatically with in configured timeout. Incase of other operating modes,
we have to perform fail over manually. The Principal server sends the log buffer to the mirror server,
and then waits for a response from the mirror server.
b. High Protection:- High-protection mode, runs synchronously. Always commit changes at both the
Principal and Mirror. We have to run ALTER DATABASE <dbname> SET PARTNER OFF(To break
mirroring).Database comes into restoring state run the following cmd to take it online
RESTORE DATABASE <dbname> with recovery
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. We have
to run ALTER DATABASE <dbname> SET PARTNER FORCE_SERVICE_ALLOW_DATA_LOSS in
mirror server. Transfer the logins. Make database available to the users and applications.

What is the default of Port numbers of Principal and Mirror servers? How to find the Port numbers?
The default port numbers of principal and mirror servers are 5022 and 5023.
To Find Port Number:- SELECT name, port FROM sys.tcp_endpoints

What is End Point? How u create end point?


An endpoint is a network protocol which is used to communicate over the network. End points will come with in-
built security
End point runs on a port number, Sql-server supports different types of end points
(i) Db mirroring end points (ii) service broker end points (iii) SOAP end points (iv) TCP end points
By default the dbmirroring end points will run on the default port number 5022. 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)

Which Trace flag is used in Mirroring?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)

In which Recovery model we can use in Mirroring?


In mirroring the principal and mirror databases are used only full recovery model

What is Role-switching? Inter changing of roles like principal and mirror are called role switching.

What is the Syntax to stop the Database Mirroring? Alter database <database name> set partner off
Questions are collected by K.V.N SUBBA REDDY
How to configure Mirroring?
 Choose Principal Server, Mirror Server, and optional Witness server.
 Configuring security and communication between instances
 Configuring endpoint
 Creating logins for other servers service accounts
 Grant connect permission to this logins on endpoints
 Create mirror database
 Take full backup from principle server and restore it in mirror server with NORECOVERY.
 Establish mirroring session using ALTER DATABASE command

How to monitoring Mirroring?


There are six methods are available for monitoring the Database Mirroring
SQL Server Management Studio:- A green arrow on the mirror server is indicates running well. A red arrow
indicates problems that need to investigate.
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.
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.
Profiler:- Profiler many events are providing the status of the Database mirroring.
Database Mirroring Monitor:- Database Mirroring Monitor is a GUI tool that shows update status and to
configure warning thresholds. We can monitor Unsent Log (at principal), Unrestored Log (at mirror), Transaction
Rate, Commit Overhead (Transactions applied rate at mirror)
To open DM Monitor:- Right click on Principal Database > Tasks > Select Launch Database Mirroring Monitor.

System Stored Procedures:-


1) sp_dbmmonitoraddmonitoring
2) sp_dbmmonitorchangemonitoring
3) sp_dbmmonitorhelpmonitoring
4) sp_dbmmonitordropmonitoring
To view complete details of mirroring select*from sys.database_mirroring
To view mirroring endpoint details Select * from sys.database_mirroring_endpoints
To view about Principal, mirror server details and mirroring state run the following query in witness server
Select * from sys.database_mirroring_witnesses

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

In SQL Server 2008, if you want to use a stored procedure to monitor the status of your database
mirroring session, which one would you use? sp_dbmmonitorresults

Threads created for database mirroring


The principal server 3 threads and mirror server 4 threads are created. We can check by using
sp_who/sp_who2

If mirror sever is failed then what is the effect on principle database t.log file?
Principal server transaction log file grows very fast. the transaction log cannot be truncated.

What are the major new features introduced in Mirroring 2008 version?
Auto Page Repair Select * from sys.dm_db_mirroring_auto_page_repair
Log Stream Compression Transactions are sending to Mirror by compressing.

Influences performance of Mirroring: Log generation rate & Transaction safety level.
N/W latency and bandwidth
No. of concurrent user connections & transaction size and volume.

Database Mirroring Errors


Error: When you configure mirroring you might receive the below errror,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
Solution: Assume that your principal server is A and mirror server is B and you have configured mirroring for
Adventure Works database. The fully qualified computer name of each server can be found running the the
command prompt: IPCONFIG /ALL
Questions are collected by K.V.N SUBBA REDDY
Concatenate the "Host Name" and "Primary DNS Suffix". If you see something like:
Host Name . . . : A Primary Dns Suffix . . . . . : corp.mycompany.com
Then the computer name is just A.corp.mycompany.com. Prefix 'TCP://' and append ':' and you then have the
partner name. -- Specify the partner from the mirror server
ALTER DATABASE [AdventureWorks] SET PARTNER = 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';
Error:1412: Occures if we have not restored T.Log backup along with FULL backup in mirror server before
configuring mirroring.
Error: 1416, Database is not configured for database mirroring
You need to restore the Full backup from principal server using With NoRecovery option and also one
T.log backup from principal server using With NoRecovery option and then start configuring mirroring.
Error:1418(Can’t be reached) :Occurs due to the communication problems b/w the end points.Possible
reasons are TCP/IP for the instance was not enabled,Duplicate end points exists,Login was not created in their
instance to mirroring.
Error:1475: Occures if any bulk opearations are made in production server before enabling mirroring.To resolve
this take T.Log backup from prinicipal and restore in mirror then enable mirroing.
Error:1478: If all T.Log Backups are not restored before starting mirroring
Error:1498 This is a common error & everyone is known 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.

Error:In My principal server while i start MirrorThe server network address


"TCP://NABONIDUS.infrasoftcorp.com:5022" can not be reached or does not exist. Check the network
address name and that the ports for the local and remote endpoints are operational. SQL Server 2008 -
1418. The solution to the above problem is very simple and as follows.
Fix/WorkAround/Solution: Try all the suggestions one by one.
Suggestion 1: Make sure that on Mirror Server the database is restored with NO RECOVERY option (This is
the most common problem).
Suggestion 2: Make sure that from Principal the latest LOG backup is restored to mirror server. (Attempt this
one more time even though the full backup has been restored recently).
Suggestion 3: Check if you can telnet to your ports using command TELNET ServerName Ports like “telnet
SQLServerName 5023″.
Suggestion 4: Make sure your firewall is turned off.
Suggestion 5: Verify that the endpoints are started on the partners by using the state or state_desc column the
of the sys.database_mirroring_endpoints catalog view. You can start end point by executing an ALTER
ENDPOINT statement.
Suggestion 6: Try the following command as one of the last options.
GRANT CONNECT ON ENDPOINT::Mirroring TO ALL
Suggestion 7: Delete the end points and recreate them.

Can I create multiple endpoints for configuring different databases for mirroring and point each
database to unique endpoint? No, that’s not possible. You can create only one endpoint in a server for
database mirroring you need to use this endpoint to configuring db mirroring for all the databases.

Can I configure a single database to be mirrored to more than one server. i.e) One source & many
destination like logshipping? No, thats not possible in Database mirroring, its one to one configuration.

Is High performance mode supported in Standard Edition of SQL 2005?


Sql Server 2005 Standard edition supports only Full transaction safety level i.e it does not support High
performance mode (Asynchronous).

What is the Default Partner Timeout? 10Sec.

Database Mirroring Operating Modes

Transaction Transfer Quorum Witness


Operating Mode Failover Type
safety mechanism required server

High Availability FULL Synchronous Y Y Automatic or Manual

High Protection FULL Synchronous Y N Manual only

High Performance OFF Asynchronous N N/A Forced only


Questions are collected by K.V.N SUBBA REDDY

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

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.

In SQL Server 2005 Database mirroring, which form is used to specify the network address of the
servers?
Tcp ://< server address> :< port>

How to Set a Witness Server to Database Mirroring?


SSMS: - Right Click on Principal Database > Tasks > Mirror > Click on Configure Security > Provide the End
point for Witness server > Click oK
T-SQL: - ALTER DATABASE AdventureWorks SET WITNESS = 'TCP://prasad.local:5024' (Do this from the
Principal Server)

How to Remove a Witness Server from Database Mirroring?


SSMS:- Right Click on Principal Database > Tasks > Mirror > Remove TCP address from the Witness > Click oK
T-SQL: - ALTER DATABASE AdventureWorks SET WITNESS OFF

Is it possible to setup database mirroring between standard and enterprise edition? No, it is not possible

Configuring Mirror in High Performance Mode Step by Step:


1. Copy the existing backup to Primary and to Mirror servers
2. Restore the database on Primary as you do normally with the backup available.
3. Restore the database on Mirror with NO Recovery option with the backup you copied
4. Take differential backup of the database on Primary, copy it to Mirror and restore it with NO Recovery
option on Mirror
5. Take transactional log backup of the database on Primary, copy it to Mirror and restore it with NO
Recovery option on SQL02
6. Setup db mirroring and start synchronization.

. In which editions does automatic page repair work with Database Mirroring?
Automatic page repair is an Enterprise only feature. Database mirroring works in both standard and enterprise
editions.

Can you mirror a SQL Server 2008 database in compatibility mode 90?
Yes. Database Mirroring doesn't concern itself with checking if the compatibility mode. You can mirror a
database in any mode if you are on the SQL Server 2008 platform.

IHow can we setup mirroring for MSDB database? No, it is not possible to setup mirroring for system
databases (master, model, msdb, tempdb), it is possible only for user databases

Is it possible to rename Mirroring Database? No, not possible to rename when mirroring is enabled on it.
Can we enable mirroring and log shipping on same database? Yes, we can setup mirroring and log shipping
on primary database with one difference, incase of log shipping we can map one primary with multiple
secondary servers, it is not possible in mirroring. It is one to one.

Is it possible to query mirroring database ? Yes it is possible only using database snapshots, otherwise it is
not possible
Quorum
Quorum is a relationship that exists when two or more server instances in a database mirroring session are
connected to each other. Three types of quorum are possible:
 A full quorum includes both partners and the witness.
 A witness-to-partner quorum consists of the witness and either partner.
 A partner-to-partner quorum consists of the two partners.
Is it possible to start service when quorum is gone? No quorum

Possible Failures during Database Mirroring


As part of mirroring generally we have two types of errors Soft errors And Hard Errors
Soft Errors: Errors identified by SQL Server service i.e. sqlservr.exe is called soft error.
 Network errors such as TCP link time-outs, dropped or corrupted packets, or packets that are in an
incorrect order.
Questions are collected by K.V.N SUBBA REDDY
 A hanging operating system, server, or database state.
 A Windows server timing out.
Hard Errors
Errors identified by windows and notified to sqlservr.exe file are called hard errors.
1 .A broken connection or wire 2. A bad network card 3. A router change 4. Changes in the
firewall
5. Endpoint reconfiguration 6. Loss of the drive where the transaction log resides 7. Operating system or
process failure
Manual Fail Over Error Could not write a checkpoint record in database ID 8 because the log is out of space.
Contact the database administrator to truncate the log or allocate more space to the database log files.

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>
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

What are the Database Mirroring states?


SYNCHRONIZING:- The principal server is sending log records to the mirror server, which is applying the
changes to the mirror database to roll it forward. At the start of a database mirroring session, the database is in
the SYNCHRONIZING state. The principal server is serving the database, and the mirror is trying to catch up.
SYNCHRONIZED:-When the mirror server becomes sufficiently caught up to the principal server, the mirroring
state changes to SYNCHRONIZED. The database remains in this state as long as the principal server continues
to send changes to the mirror server and the mirror server continues to apply changes to the mirror database. If
transaction safety is set to FULL, automatic failover and manual failover are both supported in the
SYNCHRONIZED state, there is no data loss after a failover.
If transaction safety is off, some data loss is always possible, even in the SYNCHRONIZED state.
SUSPENDED:-The mirror copy of the database is not available. The principal database is running without
sending any logs to the mirror server, a condition known as running exposed. This is the state after a failover. A
session can also become SUSPENDED as a result of redo errors or if the administrator pauses the session
SUSPENDED is a persistent state that survives partner shutdowns and startups.
PENDING_FAILOVER:-This state is found only on the principal server after a failover has begun, but the server
has not transitioned into the mirror role. If the unsent log is >0.When the failover is initiated, the principal
database goes into the PENDING_FAILOVER state, quickly terminates any user connections, and takes over
the mirror role soon thereafter.
DISCONNECTED:- The partner has lost communication with the other partner

To change mirroring timeout (Run in principal server)


Alter database OptimizeSQL SET PARTNER TIMEOUT 30

Advantages
1. Supports immediate and automatic failover of applications using ADO.Net and SQL Native Client, using
Client-side Redirect.
2. Supports multiple modes of configuration namely, High Availability Mode, High Protection and High
Performance Mode. Each mode has its advantages, providing an option to choose accordingly based on
requirement in hand.
3. Protection against database failures.
4. Support of easy manual failover and no special H/W requirements.
5. Minimized chance of data loss and relatively easy of setup and configuration.
Questions are collected by K.V.N SUBBA REDDY
Dis-advantages
1. Database redundancy is not provided for Read-Only purpose, but a workaround way using Database
Snapshots on the Mirrored Database is suggested in BOL. It has to be remembered that Database Snapshots
are limited to Enterprise Edition of SQL Server 2005 (Not sure of Database Snapshots on the Mirrored Database
in SQL Server 2008)
2. Can be implemented only with Databases having FULL Recovery model, hence databases with other
recovery models cannot be used in Database Mirroring.
3. Database mirroring does not support FILESTREAM. A FILESTREAM filegroup cannot be created on the
principal server.

Database Mirroring Log-shipping


Database mirroring is functionality in the SQL Log shipping is based on SQL Server Agent jobs
Server engine that reads from the transaction log that periodically take log backups of the primary
and copies transactions from the principal server database, copy the backup files to one or more
instance to the mirror server instance. Database secondary server instances, and restore the
mirroring can operate synchronously or backups into the secondary database(s). Log
asynchronously. shipping supports an unlimited number of
secondary’s for each primary database.
Database mirroring can operate synchronously or Log shipping is always asynchrony. Log shipping
asynchronously totally depends on the log backup and restore
schedule
Database mirroring supports only one mirror for Log-shipping can work on database and server
each principal database. That means DB level. You can configure multiple databases in log
mirroring is at database level shipping
Data Transfer: Individual T-Log records are Data Transfer: T-Logs are backed up and
transferred using TCP endpoints transferred to secondary server
Transactional Consistency: Only committed Transactional Consistency: All committed and
transactions are transferred un-committed are transferred
Server Limitation: Can be applied to only one Server Limitation: Can be applied to multiple
mirror server stand-by servers
Failover: Automatic Failover: Manual
Failover Duration: Failover is fast, sometimes < Failover Duration: Can take more than 30 mins
3 seconds but not more than 10 seconds
Role Change: Role change is fully automatic Role Change: Role change is manual
Client Re-direction: Fully automatic as it uses Client Re-direction: Manual changes required
.NET 2.0/.Net 3.0

Support only full recovery model Supports full and bulk-logged recovery model
Mirror database is always in recovery mode. To You can use the stand-by option to read the
read it you have use database snapshot. database on standby server
Auto Page Recovery introduced with SQL Not supported
SERVER 2008 so it will recover the damaged
pages.

Replication
What is Replication? “Replication is the process of copying and distributing data between databases to
different servers throughout the enterprise”.
Replication is a set of technologies for copying and distributing data and database objects from one database to
another and then synchronizing between databases to maintain consistency.

What are the uses of Replication?


Server to Server Replication:-
Improving scalability and availability
Data warehousing and reporting
Integrating data from multiple sites
Integrating heterogeneous data
Offloading batch processing
Server to Client Replication:-
Exchanging data with mobile users
Retail point of sale (POS) applications
Integrating data from multiple sites
What are the type of replication available in SQL Server?
SQL Server supports
Questions are collected by K.V.N SUBBA REDDY
1. Snapshot replication sends the entire data set to the subscriber.
2. Transactional replication only sends modifications to the data.
3. Merge replication items are modified at both the publisher and subscribers.
4. Heterogeneous replication allows access to other database products.
5. Peer to Peer Transactional Replication

Types of Replication and explain each?


Snapshot replication:- Snapshot replication takes a picture or a snapshot of the database and propagated to
the subscribers. It reduces the overhead on the Publishers and Subscribers because it does not monitor data
updates. Snapshot replication is very useful, when the source data is changes occasionally (Reporting). A
subscriber does not always need to be connected, so data marked for replication can be applied the next time
the subscriber is connected.
Transactional replication:- Transactional Replication starts with a snapshot of the publisher database. With
Transactional Replication, any changes made to the articles are captured from the transactional log and
propagated to the distributors continuously and automatically. Using Transactional Replication we can keep the
publisher and subscriber in almost exactly the same state. T.R is typically used in server to server
environments.Only committed transactions are replicated to ensure data consistency. Transactional replication is
widely applied where high latency is not allowed, such as an OLTP system for a bank or a stock trading firm,
because you always need real-time updates of cash or stocks.
Merge replication:- It provides the advantages of both S.R and T.R.Both publisher and subscriber can make
changes. Both publisher and subscriber can work without any active connection. When they are connected, the
merge replication agent checks for changes on both sets of data and modifies each database accordingly. Site
autonomy is very critical. M.R is typically used in server to client environments. Merge Replication This allows
both publisher and subscriber to work independently, online or offline and merges the changes later. Here
changes are track on both publisher and subscriber and then merged.

Explain about Publisher, Subscriber and Distributer (or) What are the Server Roles Involved in
Replication?
Publisher:- The Publisher is a database that makes data available for replication. The Publisher can have one or
more publications.
Distributor:- The distributor is the intermediary between the publisher and subscriber. It receives published
transactions or snapshots and then stores and forwards these publications to the subscribers.
Subscribers:- Subscribers are database servers that store the replicated data and receive updates. A subscriber
can receive data from multiple publishers. Based on the replication type, the Subscriber can also pass data
changes back to the Publisher or republish the data to other Subscribers.
Note:MSDTC(MS distributed transactions coordinator) should be running in subscriber

Explain about Article, Publication, Subscription?


Article:- An Article is the data, transactions, or stored procedures that are stored within a publication. This is the
actual information that is going to be replicated. An article can be filtered when send to the subscriber
To view the properties of an article belonging to a snapshot or transactional publication: sp_helparticle
To modify the properties of an article belonging to a snapshot or transactional publication: sp_changearticle
To view the properties of an article belonging to a merge publication: sp_helpmergearticle
To modify the properties of an article belonging to a merge publication: sp_changemergearticle
Publication:- The publication is the storage container for different articles. A subscriber can subscribe to an
individual article or an entire publication. An article can’t be distributed individuals, Hence publication is required
Subscription:-Subscription is a request by the subscriber to receive the publication(Types:Pull and Push)

Which recovery models are used for Replication? Full and Bulk-logged Recovery models

How to monitor the Replication?


a) Replication Monitor:- Replication Monitor is a GUI tool provides detailed information on the status and
performance of publications and subscriptions. By using replication monitor we can find out (1) which
subscriptions are slow (2) Why is an agent not running (3) Time taken to transaction commit (4) Why
merge replication is slow (5) How far behind subscription etc.
To launch Replication Monitor :- Connect Instance > Right Click on Replication folder > Select launch
Replication monitor
b) Management Studio:- By using management Studio we can see View Snapshot Agent Status, View Log
Reader Agent Status, View Synchronization Status etc.
Through SSMS:- Connect Instance > Right Click on Publication > Select the option
c) System Monitor:- Provides information on the performance of various processes of Replication.
Agent Performance object Counter
All agents Replication Agents Running
Snapshot Agent Replication Snapshot Snapshot: Delivered Cmds/sec
Snapshot Agent Replication Snapshot Snapshot: Delivered Trans/sec
Questions are collected by K.V.N SUBBA REDDY
Log Reader Agent Replication Logreader Logreader: Delivered Cmds/sec
Log Reader Agent Replication Logreader Logreader: Delivered Trans/sec
Log Reader Agent Replication Logreader Logreader: Delivery Latency
Distribution Agent Replication Dist. Dist: Delivered Cmds/sec
Distribution Agent Replication Dist. Dist: Delivered Trans/sec
Distribution Agent Replication Dist. Dist: Delivery Latency
Merge Agent Replication Merge Conflicts/sec
Merge Agent Replication Merge Downloaded Changes/sec
Merge Agent Replication Merge Uploaded Changes/sec

What are the Agents available for Replication and explain each?
SQL Server Agent hosts and schedules the agents used in replication and also controls and monitors operations
outside of replication.
Snapshot Agent (snapshot.exe):-The Snapshot Agent is typically used for all types of replication. It is
responsible for copying the schema and data from the publisher to the subscribers, stores the snapshot files,
and records information about synchronization in the distribution database. The Snapshot Agent runs at the
Distributor. The snapshot is created by using the following files
(i) .sch -> schema files which contains the articles structure. (ii).bcp -> contains the articles data.
(iii).idx -> contains the indexes infn (iv) .trg -> contains the triggers infn (v) .pre -> referential integrity
constraints.
Name pattern :< publisher>-<publicationdb>-<publication>-<int>
Log reader agent (logread.exe) The Log Reader Agent is used for transactional replication. It moves information
from the transaction log on the publisher to the distribution database.. Each database published using
transactional replication has its own Log Reader Agent that runs on the Distributor and connects to the Publisher
Distribution Agent :( distrib.exe): The Distribution Agent is used for snapshot replication and transactional
replication. It is responsible for moving the stored transactions from the distributor to the subscribers. The
Distribution Agent runs at either the Distributor for push subscriptions or at the Subscriber for pull subscriptions.
Name pattern(push):<publisher>-<publication>-<publication>-<subscriber>-<int>
Name pattern(pull):<publisher>-<publicationdb>-<publication>-<subscriber>-<subscriptiondb>-
<GUID>
Merge agent :( replmerg.exe):- The Merge Agent is used for merge replication. It is responsible for converging
records from multiple sites and then redistributing the converged records back to the subscribers. The Merge
Agent runs at either the Distributor for push subscriptions or the Subscriber for pull subscriptions.
Queue Reader Agent: (qrdrsvc.exe) - The Queue Reader Agent is used for transactional replication with the
queued updating option. It runs on the Distributor and is responsible for reading messages from the queue on
the subscribers and applying them to the appropriate publication. Unlike the Distribution Agent and the Merge
Agent, only one instance of the Queue Reader Agent exists to service all Publishers and publications for a given
distribution database.

What type of locking occurs during the Snapshot generation?


Locking depends on the type of replication used:
• In snapshot replication, the snapshot agent locks the object during the entire snapshot generation
process.
• In transactional replication, locks are acquired initially for a very brief time and then released. Normal
operations on a database can continue after that.
• In merge replication, no locks are acquired during the snapshot generation process.

What options are there to delete rows on the publisher and not on the subscriber?
• One option is to replicate stored procedure execution instead of the actual DELETE command. You can
create two different versions of the stored procedures one on the publisher that does the delete and the
other on the subscriber that does not do the delete.
• Another option is to not replicate DELETE commands.

Describe in brief working of Replication.


At first data and object is synchronized between publisher and subscribers.
The snapshot is created on the publisher and transmitted to subscribers.
All the subsequent changes on the publisher are stored in distribution database.
Subscriber receives the data either using push or pull mechanism as configured from distribution database

What is the difference between Snap Shot and Transaction Replication?


In snapshot replication we can take the copy of the database from publisher and put it into the subscriber, here
it is in read-only mode it will not allow us to make any modifications. It doesn’t involve continuesly.
Transcation replication: This can be used to replication changes to the database with this any changes made
to the replication data immediately captured from transcation log and propagated to the distributor
Questions are collected by K.V.N SUBBA REDDY
How merge replication works
Merge replication is a database technology that combines changes occurring on two or more nodes in a
publisher/subscriber topology. It is important to note that each node in a merge replication topology isn't
completely autonomous; it's not true multi-master replication. You must have a node designated as the
Publisher, which acts as a clearing house. It's where all changes on the nodes are collected, reconciled and
distributed to all other nodes, the Subscribers.

Data is not being delivered to Subscribers, what can be the possible reasons?
There are a number of possible causes for data not being delivered to Subscribers:
o The table is filtered, and there are no changes to deliver to a given Subscriber.
o One or more agents are not running or are failing with an error.
o Data is deleted by a trigger, or a trigger includes a ROLLBACK statement.
o A transactional subscription was initialized without a snapshot, and changes have occurred on
the Publisher since the publication was created.
o Replication of stored procedure execution for a transactional publication produces different
results at the Subscriber.
o The INSERT stored procedure used by a transactional article includes a condition that is not
met.
o Data is deleted by a user, a replication script, or another application.

Explain what stored procedure sp_replcounters is used for?


Sp_replcounters is a system stored procedure that returns information about the transaction rate, latency, and
first and last log sequence number (LSN) for each publication on a server. This is run on the publishing server.
Running this stored procedure on a server that is acting as the distributor or subscribing to publications from
another server will not return any data

If I create a publication with one table as an article, and then change the schema of the published table
(for example, by adding a column to the table), will the new schema ever be applied at the Subscribers?
Yes. Schema changes to tables must be made by using Transact-SQL or SQL Server Management Objects
(SMO). When schema changes are made in SQL Server Management Studio, Management Studio attempts to
drop and re-create the table and since you cannot drop a published objects, the schema change will fail.

Is it possible to replicate data from SQL Server to Oracle?


Yes this can be done using heterogeneous replication. In SQL Server 2000, publishing data to other databases
such as DB2 or Oracle was supported; however, publishing data from other databases was not supported
without custom programming. In SQL Server 2005 and later versions, Oracle databases can be directly
replicated to SQL Server in much the same way as standard SQL Server replication.
To monitor replication, a user must be a member of the sysadmin fixed server role at the Distributor or a
member of the replmonitor fixed database role in the distribution database. A system administrator can add any
user to the replmonitor role, which allows that user to view replication activity in Replication Monitor; however,
the user cannot administer replication

Can you tell me some of the common replication DMV’s and their use?
sys.dm_repl_articles - Contains information about each article being published. It returns data from the
database being published and returns a row for each object being published in each article.
sys.dm_repl_schemas – Contains information about each table and column being published. It returns data
from the database being published and returns one row for each column in each object being published
sys.dm_repl_traninfo - Contains information about each transaction in a transactional replication

What are the advantages and disadvantages of merge replication?


Advantages: It provides built-in and custom conflict resolution capabilities.
It allows for the synchronization of data from multiple tables at one time.
It provides rich data replication options like selection of article types and filtering and identity range
management.
Disadvantages: Merge replication requires more configuration and maintenance at the server

Can I setup replication on a single computer?


Yes, you can setup replication on a single computer. You can setup Publication, Distribution and Subscriber
databases on a single computer. It can be used for the test purposes.

How can I replicate objects permissions?


The information about permissions granted and denied to users, groups, and roles is stored in the
syspermissions system table. The syspermissions system table is stored in each database.
To replicate objects permissions you should replicate the syspermissions table, or with the snapshot replication
you can generate the script of object level permissions and then apply this script before applying the snapshot or
Questions are collected by K.V.N SUBBA REDDY
after applying the snapshot.

To replicate permissions in the snapshot replication topology, select appropriate object, right mouse click and
choose Generate Script, then uncheck all formatting options and on the Options tab check 'Script object level
permissions'. Then select appropriate article and click Publication properties. On the Snapshot tab specify
'Additional script' ('Before applying the snapshot, execute this script' or 'After applying the snapshot execute this
script') and specify script which was created before (this script will contain the GRANT statements).

How can I start replication agents via Transact-SQL?


There are several ways to start replication agents via Transact-SQL.
1. You can use the sp_start_job system stored procedure.
In the Enterprise Manager select the name of the job that start the replication agent and specify this name as the
job_name: EXEC msdb..sp_start_job <job_name>
2. You can use the xp_cmdshell extended stored procedure.
For example: EXEC master..xp_cmdshell "snapshot.exe <parameters>"
3. You can use SQL DMO.

How do we handle duplicate primary keys for transaction/merge replication?


If you use transaction replication then Log Reader Agent read transaction log and all transactions for replication
will be transferred into distribution database as Insert, Update and Delete commands. So, if you try to insert the
record with existing primary key you will receive duplicate primary key error and new record will not be inserted.
How can you handle this? For transaction replication there is no way to handle this error. You should resync
your databases or correct records manually, in this case. This error can be handled only in merge replication.
Some of my text/image values were not replicated. What is the problem?
There is max text repl size server option. This option is used to specify the maximum size (in bytes) of text and
image data that can be replicated. The default value for this parameter is 65536 bytes.
So, if the size of the text/image data is more than 65536 bytes, this data will not be replicated (if 'max text repl
size' option = 65536 bytes). You can change this option by using the sp_configure system stored procedure.
This is the example to set the max text repl size to 128Kb:
sp_configure 'max text repl size', 131072

What are the Agents used for Transactional Replication?


1.Snapshot Agent 2. Log Reader Agent 3. Distribution Agent

What are the Agents used for Merge Replication?


1.Snapshot Agent 2. Merge Agent

What is the major difference between Merge replication and Transactional replication?
In Merge replication the both publisher and subscriber can work independently

How Snapshot Replication(Static Replication) works?


Snapshot Agent: Appends rows to the Msrepl_commands and Msrepl_transactions.
Release any locks on published tables.
Distribution Agent: Establishes a connection to distributor.
Examines the Msrepl_commands and Msrepl_transactions tables.
Applies the schema and commands to the subscription database.

How Transactional Replication(Dynamic Replication) works?


The snapshot agent prepares files containing schema and data of published tables and database objects,
stores the files in the snapshot folder, and records synchronization jobs in the distribution database on the
distributor.
The log reader agent monitors the transaction log of each database configured for T.R and copies the
transactions marked for replication from T.L into Msrepl_transactions of distribution db.
Distribution agent moves the initial snapshot and the transactions held in the distribution databases to
subscribers

Snapshot Replication SPs:


To Configure Publications:sp_replicationdboption,
Sp_addpublication,sp_addpublication_snapshot,sp_addarticle
To Configuare Subscriptions:sp_addsubscriptions,sp_addpullsubscription.

How many articles may be there in a publication? 32767


Max columns in a table?1000
Which editions support snapshot Replications? EE,SE,EE,WE(Limited Publication)
Questions are collected by K.V.N SUBBA REDDY
What is the Process of Transactional Replication? Three Agents are doing the Process for Transactional
Replication.

Types of publications for T.R


Standard publication(SA,LRA,DA)
T.publication with updatable subscriptions.(SA,LRA,DA,QRA)
T.publication in a peer-to-peer topology (Immediate updates or Queue updates)

Peer-Peer Replication? Peer-Peer Replication decreases / nullifies the dependency on Distributor. In this
Replication topology each node is Publisher, Distributor and Subscriber. This increases availability of the
database system and Failure of any node does not impact the health of Replication process. This topology also
offers automatic conflict detection and correction. Hence, recommended in Realtime
Peer to Peer Replication configuration:
1. Take 2 or 3 instances.
2. Make both the instances as publisher as well as distributor.
3. Go to first instance create one transactional publication from required database.
4. Right click on publication take properties ->Select “Subscription Options” and Allow Peer to peer
subscriptions= True and click ok
5. Go to Node1 i.e. first server take full backup and restore backup in Node2
6. Right click on publication select configure peer to peer topology ->Click Next >Select publication
->click Next
7. Right on the surface and select Add New peer node
8. Select second instance 􀂉 Connect
9. Select Database and Peer Originator ID. OK
10. Right click on first node 􀂉 Select Connect to all displayed node->Click Next
11. Configure Log Reader Agent Security 􀂉 Next
12. Configure Distribution Agent security 􀂉 Next
13. Select first option “I created the peer database manually”􀂉 Next ->Next 􀂉 Finish->Close.

Publication types: (i) snapshot publications (ii) transactional publications (iii) merge publications
(iv) Transactional publication with updatable subscriptions

TRANSACTIONAL PUBLICATION WITH UPDATABLE SUBSCRIPTIONS: It is a 2 way replication


Functionality is same as the transactional publication but the transactions at the subscriber will be updated to the
publisher not immediately. The transactions at the subscriber will be queued and the replicated whenever it is
possible. Recommended when the publisher need not to maintain the data with synchronization with the
subscriber immediately. These publications uses linked servers for synchronization to implement this
publications the article should constraint a primary key constraint (same as transactional publication) and the
wizard adds a ROWGUID column (2 way replication)

Replication topologies
Central publisher/Central distributor. Remote distributor
Central subscriber/multiple publishers. Multiple publisher/multiple subscribers.

How to display database names which consists of publication?


Go to publisher->take new query select * from sys.databases where is_published=1 is_subscribed=1

How to trouble shoot if Primary key violation is happened in Transactional replication?


sp_browsereplcommands.

How to resolve latency issues in transactional replication.


We can track latency by using tracer token in replication monitor.
If latency between pub to dist and dist to sub is too high we need to take fresh snapshot and apply at
subscriber.

What are the causes need to take snapshot.


If subscriber data is out of date with compared to publisher.
If data sending from publisher to subscriber is greater than to take snapshot and apply at subscriber

If u configures merge replication what column is newly added into that published table? Will it be
removed if u dropped from publication.
one column is added i.e. "rowguid" column and data type is uniqueidentifier.if u drop table form publication and
the column will so dropped. in case of transactional with updatabale one column is added into that table i.e
"repl_tran_version" column. It can't drop even if u drop table from publication and u need to do manually.
Questions are collected by K.V.N SUBBA REDDY
Failover in replication:
When the publisher or subscriber database fails, replication does not take place
Restore the database by using the available backup sets
On restore the database the replication continues.
Should I script my replication configuration? Yes. Scripting the replication configuration is a key part of any
disaster recovery plan for a replication topology

What recovery model is required on a replicated database?


Replication functions properly using any of the recovery models: simple, bulk-logged, or full.

How do I manage constraints on published tables?


There are a number of issues to consider regarding constraints on published tables
 Transactional replication requires a primary key constraint on each published table. Merge replication
does not require a primary key, but if one is present, it must be replicated. Snapshot replication does not
require a primary key.
 By default, primary key constraints, indexes, and check constraints are replicated to Subscribers.

Can the same objects be published in different publications? Yes, but with some restrictions.

Can multiple publications use the same distribution database?


Yes. There are no restrictions on the number or types of publications that can use the same distribution
database. All publications from a given Publisher must use the same Distributor and distribution database.
Does replication encrypt data?
No. Replication does not encrypt data that is stored in the database or transferred over the network.

Replication issues
"There is insufficient system memory to run this query" - Log reader agent error for subscriber database
:

During working with replication this is one of the error which i encountered and get resolved it. This is coming
with log reader agent and it stopped working. It's due to the issue memory. i have flushed the unused memory
consumed by Adhoc queries and system cache.
To flush the memory use the below commands,
DBCC FREESESSIONCACHE
DBCC FREEPROCCACHE
DBCC FREESYSTEMCACHE('ALL')
"Could not find stored procedure 'sp_MSins_TableName' in replication in sql server" - Log reader agent
error:
It came after reinitialize all subscription for one publication and it stopped working with error,
"Could not find stored procedure 'sp_MSins_TableName' in replication in sql server"

This is due to replication object was not created for insert and named like 'sp_MSins_TableName'. The solution
for this issue, we need to create these missing replication objects using 'sp_scriptpublicationcustomprocs' which
generates scripts the custom INSERT, UPDATE, and DELETE procedures for all table articles in a publication.
Workaround for the solution is,
EXEC sp_scriptpublicationcustomprocs 'PublicationName'
After running generated scripts in subscriber database, log reader agent started to work.
"The row was not found at the Subscriber when applying the replicated command”:
It encountered it with log reader agent and it was stopped due to error as,
"Command attempted: if @@trancount > 0 rollback tran (Transaction sequence number:
0x000CAB2A00038CB6003B00000000, Command ID: 2) Error messages: The row was not found at the
Subscriber when applying the replicated command. (Source: MSSQLServer, Error number: 20598)"

Row conflict issue was occurred due to some of the tables which we can get the details with following query to
reach towards solution.
SELECT * FROM dbo.MSarticles m WHERE EXISTS ( SELECT mc.Article_id from MSrepl_commands mc
WHERE mc.xact_seqno = 0x000CAB2A00038CB6003B00000000
and mc.Article_id = m.article_id )

How do I replicate data over the Internet?


A Virtual Private Network (VPN).
The Web synchronization option for merge replication

Does replication resume if a connection is dropped?


Yes. Replication processing resumes at the point at which it left off if a connection is dropped.
Questions are collected by K.V.N SUBBA REDDY
Are logins and passwords replicated? No. You could create a DTS package to transfer logins and passwords
from a Publisher to one or more Subscribers.

Why can't I run TRUNCATE TABLE on a published table?


TRUNCATE TABLE is a non-logged operation that does not fire triggers. It is not permitted because replication
cannot track the changes caused by the operation: transactional replication tracks changes through the
transaction log; merge replication tracks changes through triggers on published tables.

What is the effect of running a bulk insert command on a replicated database?


For transactional replication, bulk inserts are tracked and replicated like other inserts. For merge replication, you
must ensure that change tracking metadata is updated properly.

Are there any replication considerations for backup and restore?


Yes. There are a number of special considerations for databases that are involved in replication.

Does replication affect the size of the transaction log? Merge replication and snapshot replication do not
affect transaction log size, but transactional replication can

How do I rebuild indexes or tables in replicated databases?


There are a variety of mechanisms for rebuilding indexes. They can all be used with no special considerations
for replication, with the following exception: primary keys are required on tables in transactional publications, so
you cannot drop and recreate primary keys on these tables.

How do I add or change indexes on publication and subscription databases?


Indexes can be added at the Publisher or Subscribers with no special considerations for replication (be aware
that indexes can affect performance). CREATE INDEX and ALTER INDEX are not replicated, so if you add or
change an index at, for example, the Publisher, you must make the same addition or change at the Subscriber if
you want it reflected there.

How do I move or rename files for databases involved in replication?


In versions of SQL Server prior to SQL Server 2005, moving or renaming database files required detaching and
reattaching the database. Because a replicated database cannot be detached, replication had to be removed
from these databases first. Beginning with SQL Server 2005, you can move or rename files without detaching
and re-attaching the database, with no effect on replication.

How do I drop a table that is being replicated?


First drop the article from the publication using sp_droparticle, sp_dropmergearticle, or the Publication
Properties - <Publication> dialog box, and then drop it from the database using DROP <Object>. You cannot
drop articles from snapshot or transactional publications after subscriptions have been added; you must drop the
subscriptions first.

How do I add or drop columns on a published table?


SQL Server supports a wide variety of schema changes on published objects, including adding and dropping
columns. For example, execute ALTER TABLE … DROP COLUMN at the Publisher, and the statement is
replicated to Subscribers and then executed to drop the column. Subscribers running versions of SQL
Server prior to SQL Server 2005 support adding and dropping columns through the stored procedures
sp_repladdcolumn and sp_repldropcolumn.

How do I add a table to an existing publication?


It is not necessary to stop activity on the publication or subscription databases in order to add a table (or another
object). Add a table to a publication through the Publication Properties - <Publication> dialog box or the
stored procedures sp_addarticle and sp_addmergearticle
Does replication work in conjunction with log shipping and database mirroring? Yes.

Does replication work in conjunction with clustering?


Yes. No special considerations are required because all data is stored on one set of disks on the cluster.

How to Delete a Publication (SQL Server Management Studio)?


Delete publications from the Local Publications folder in Microsoft SQL Server Management Studio.
To delete a publication
1. Connect to the Publisher in Management Studio, and then expand the server node.
2. Expand the Replication folder, and then expand the Local Publications folder.
3. Right-click the publication you want to delete, and then click Delete.
Questions are collected by K.V.N SUBBA REDDY
Delete a push subscription at the Publisher (from the Local Publications folder in Microsoft SQL Server
Management Studio) or the Subscriber (from the Local Subscriptions folder). Deleting a subscription does not
remove objects or data from the subscription; they must be removed manually.
To delete a push subscription at the Publisher
1. Connect to the Publisher in SQL Server Management Studio, and then expand the server node.
2. Expand the Replication folder, and then expand the Local Publications folder.
3. Expand the publication associated with the subscription you want to delete.
4. Right-click the subscription, and then click Delete.
5. In the confirmation dialog box, select whether to connect to the Subscriber to delete subscription
information. If you clear the Connect to Subscriber checkbox, you should connect to the Subscriber
later to delete the information.
To delete a push subscription at the Subscriber
1. Connect to the Subscriber in SQL Server Management Studio, and then expand the server node.
2. Expand the Replication folder, and then expand the Local Subscriptions folder.
3. Right-click the subscription you want to delete, and then click Delete.
4. In the confirmation dialog box, select whether to connect to the Publisher to delete subscription
information. If you clear the Connect to Publisher check box, you should connect to the Publisher later
to delete the information.

How to: Disable Publishing and Distribution (SQL Server Management Studio)
Disable publishing and distribution with the Disable Publishing and Distribution Wizard.
To disable publishing and distribution
1. Connect to the Publisher or Distributor you want to disable in Microsoft SQL Server Management Studio,
and then expand the server node.
2. Right-click the Replication folder, and then click Disable Publishing and Distribution.
3. Complete the steps in the Disable Publishing and Distribution Wizard.

Advantages
1. Provides redundancy of Database, giving a choice to use one system for reporting and another for DR or Hot
standby etc.
2. Can be used to build Scale-Out Implementation by using Peer-to-Peer Transactional Replication.
3. Can be used to setup a Reporting / Data Warehousing System which needs only some part of the Source
Database, this can be achieved using Horizontal and Vertical filtering of Data.
4. Oracle Database can be used as a Publisher.
5. Independent of the Recovery Model of the Database, hence any database can be published.
Dis-advantages
1. Automatic Failover of the application is not possible, the application has to be coded / changed to use the
standby system.
2. Many Table related properties, such as Index Partition Schemes, Check Constraints and Non Clustered
Indexes etc are not propagated to the subscribers by default; they need to be configured when publishing.
3. Data Conflict can occur when Merge Replication is configured and sometimes may turn out to be very
complex to solve the conflicts.

MANAGEMENT
What is Maintenance Plan?
A SQL Server maintenance plan allows the creation and scheduling of maintenance tasks through either a
wizard-driven interface or using the Maintenance Plan design surface. The purpose of wizard is to create and
schedule tasks covering the major administration items such as backups, DBCC checks, and index
maintenance.

What the tasks in Maintenance Plans?


1. Backup database task
2. Check database integrity task.
3. Execute Sql server agent job task
4. Execute T-Sql statement task.
5. History cleanup task.
6. Maintenance cleanup task.
7. Notify operator task.
8. Rebuild index task.
9. Shrink database task.
10. Reorganize index task
11. Update statistics task.
Questions are collected by K.V.N SUBBA REDDY
SQL Server Logs/Error logs:Error logs maintain events raised by sql server database engine or agent.By
default supports 1.current log and 6-Archive logs.Error logs are present in log folder of respective instance.we
can read error logs using SP_READERRORLOG. By default when server was restarted the error logs are
recycled automatically.we can recycle using SP_CYCLE_ERRORLOG.We can configuare upto 99 error logs.

Database Mail: Database Mail is an enterprise solution for sending e-mail messages from the Microsoft SQL
Server 2005 Database Engine. Using Database Mail, your database applications can send e-mail messages to
users. The messages can contain query results, and can also include files from any resource on your network.
Database Mail is designed for reliability, scalability, security, and supportability.

How can SQL Server Agent Mail send messages in SQL Server 2005?
SQL Mail through Extended MAPI or Database mail.
SQL Server Agent Mail can be configured to use Database Mail or Extended MAPI.

AUTOMATION: It decreases the user’s workload.


Avoids the overlooking of the important database maintenance tasks
Using automation 80% of database operations can be automated.
The automation task can be performed by using the sql-server agent service.
We can implement log shipping, Mirroring, Replication, Taking backups on scheduled times
Components (SS Agent, MSDB, service broker) are required to implement automation
Automation we can work with 3 options (i) jobs (ii) operators (iii) alerts

JOBS: The job is a collection of steps which can be runned sequentially.


The jobs can be runned either manually or they can be scheduled.
The steps can be any t-sql command, operating system command, activex scripts, replication, log shipping etc.
Viewing the Job history: select the job, right click and click on view history and by using the job activity
monitor.

Operators: These are the alias to the people to whom we can send the electronic notifications using email,
pager, and net send.
1. Standard operators 2. Fail-safe operator: When the notifications to the operators failed, then the notification
will be sent to the fail-safe operator. We can have only one fail-safe operator and it cannot be deleted.

Alerts: These are the pre-defined indications which will be raised automatically by the alert engine.
When an alert is raised we can notify to an operator or we can run a job.
The alerts are 3 types:(i) sqlserver event alerts (ii) sqlserver performance condition alerts (iii) sqlserver WMI
alerts

Sqlserver performance condition alerts: These alerts are raised when the performance counters reaches a
threshold value.
These performance counters can be monitored by using system performace monitor.

Sqlserver event alerts: These alerts are raised when a database event is raised.
These alerts will be raised based on the error numbers or based on the error severity
Eg: create an event alert when a record is deleted from the customers table.

Creating user defined error no: sp_addmessage 50120,16,’cannot delete rows’,’us_english’,’true,’replace’

PERFORMANCE TUNING
Which Tools are used for Performance Tuning?
There are many tools are used for Performance tuning
a) Windows tools for monitoring applications :- Performance monitor, Performance Counters and Logs,
Task manager, Network manager
b) SQL Server tools for monitoring components :- SQL trace, SQL Profiler, DMVs, System Stored
procedures, Graphical show plan, Activity Monitor, DBCC, Built-in Functions, Trace flags

How to identify longest running queries?


There are two ways to identify slow running queries
1) Profiler (By using duration of the query)
2) sys.dm_exec_query_stats and sys.dm_exec_requests DMVs
3) DBCC OPENTRAN

Reasons for Slow Running Query?


There are a number of common reasons for slow-running queries
a) Missing indexes, Index fragmentation
Questions are collected by K.V.N SUBBA REDDY
b) Blockings, Dead lock s,Table scans
c) Missing or out of date statistics (update statistics)
d) Slow network communication.
e) Insufficient memory available for SQL Server.
f) Insufficient disk space.
g) Excess recompilations of Stored Procedures
h) Procedures and Triggers without SET NOCOUNT On

How to analyze query performance?


We can analyze query performance in three ways
1) T-SQL:- SET SHOWPLAN_ALL ON/OFF, SET SHOWPLAN_TEXT ON/OFF
2) SSMS:- Estimated Execution Plan & Actual Execution plan
3) Profiler: - To display text and XML execution plans.

What is the advantage of recompile statement in procedure?


I have noticed that after inserting many rows in one table many times the stored procedure on that table
executes
Slower or degrades. This happens quite often after BCP or DTS. I prefer to recompile all the stored procedure
on the table,
Which has faced mass insert or update. sp_recompiles marks stored procedures to recompile when they
execute next time

Once I run any SQL command, internal how SQL Server executes this command?
Once a query is submitted to SQL Server, It performs the following steps for first time.
1. Parsing (Compiling)
2. Resolving (Verifying table names, col names)
3. Optimizing (Generating execution plan)
4. Executing
Note: Execution plans are
* Case sensitive and
* Space sensitive

What are the steps to take to improve performance of a poor performing query?
Steps to take to improve performance of queries:
• Use indexes efficiently
• Create all primary and foreign keys and relationships among tables.
• Avoid using cursors
• Triggers are with Set NOCOUNT On
• Avoid using Select*, rather mention the needed columns and narrow the resultset as needed.
• Reduce the too much normalization
• Use partitioned views
• Use temporary tables and table variables
• Reduce joins and heavy clauses like GROUP BY if not needed
• Implement queries as stored procedures.
• Have a WHERE Clause in all SELECT queries.
• Use data types wisely
• Instead of NULLS use string values such as N/A
• Use locking and isolation level hints to minimize locking.
• Avoid expensive operators such as NOT LIKE.
• Fully qualify database objects.
• Add space to DB files or TempDB, if that are not having enough space

How do you re-architect a process?


a. Review the current process to understand what is occurring
b. Backup the current code for rollback purposes
c. Determine what the business and technical problems are with the process
d. Document the requirements for the new process
e. Research options to address the overall business and technology needs
For example, these could include:
1. Views 2. Synonyms 3.Service Broker 4.SSIS 5.Migrate to a new platform 6.Upgrade in place
f. Design and develop a new solution
g. Conduct testing (functional, load, regression, unit, etc.)
h. Run the systems in parallel
i. Sunset the existing system
Questions are collected by K.V.N SUBBA REDDY
j. Promote the new system

How do you identify and correct a SQL Server performance issue?


Identification - Use native tools like Profiler, Perfmon, system stored procedures, dynamic management views,
and custom stored procedures or third party tools
Analysis - Analyze the data to determine the core problems
Testing - Test the various options to ensure they perform better and do not cause worse performance in other
portions of the application
Knowledge sharing - Share your experience with the team to ensure they understand the problem and solution,
so the issue does not occur again

Explain about Profiler? What are the Uses of Profiler?


SQL Profiler is a graphical tool.It can capture SQL Server events from the server to analyze or troubleshoot
performance problems such as Finding Slow-running queries and Monitoring performance etc. Profiler is useful
for maintaining security, troubleshooting, monitoring and optimization.
Uses of SQL Profiler:-
a) Find the worst-performing queries.
b) Identify the cause of a deadlock.
c) Monitor stored procedure performance
d) Audit SQL Server activity.
e) Monitoring T-SQL activity per user.
f) Collect a representative sample of events for stress testing.
g) Collect a sample of events for tuning the physical database design by using Database Engine
Tuning Advisor(DTA)
Is it possible to save profiler data into table? Yes, in text file also

While tracing server activities using profiler, any blocking occurs?


While using “Tuning template” in profiler causes blocking.

What are the Events is captured SQL Profiler?


We can capture the events such as
a) T-SQL Statements, Stored Procedures
b) Cursors, Locks (deadlocks)
c) Databases objects and auto growth of size of data & log files
d) Errors & warnings (syntax errors)
e) Performance (show plan)
f) Table Scans
g) Security audits (failed logins, password changes)
h) Monitor server control, memory changes (CPU, Reads, Writes)
i) Sessions, Transactions, Tuning

The key difference between SQL Server Profiler and System Monitor is that SQL Server Profiler monitors
Database Engine events, whereas System Monitor monitors resource usage associated with server processes.,

How do you trace the traffic hitting a SQL Server?


SQL profiler is the SQL Server utility you can use to trace the traffic on the SQL Server instance

What is blocking? How to identify and resolve the blockings?


Let say one session has placed a lock which will not allow other sessions to access the same resource (table or
row or page). The other session query waits for unlimited time till the previous session releases the lock. This
scenario is called blocking.
Scenarios where sessions experience with excessive blocking
1. Long running queries which places Shared or Exclusive locks.
2. Queries which are cancelled and not rollback.
3. In some cases, lock escalation also one reason for blocking because SQL has escalated locks, and
so locked the entire table.
4. When the process of index rebuilding is running.
5. Snapshot agent is generating fresh snapshot in case of Snapshot of transactional replication.
6. Missing indexes.
7. Poor database design.
8. Inappropriate isolation level
9. Poorly design queries.
10. Application design structure.
Steps to reduce blocking
1. Keep the workload small as possible
Questions are collected by K.V.N SUBBA REDDY
a. Avoid INSERTing, UPDATEing, or DELETEing large numbers of records in a single transaction.
2. Ensure that your tables have appropriate indexes
a. For the above indexes specially clustered we can set Online Index Processing to true.
3. Use NOLOCK hint or read uncommitted isolation level
a. We can make use of NOLOCK option to read the rows and provide more concurrency.
4. Using SNAPSHOT ISOLATION LEVEL
Determine Blocking sessions:- Activity Monitor, sp_who2, sp_lock, sys.sysprocess, sys.dm_exec_requests,
sys.dm_os_waiting_tasks
Resolve Blocking Session: - (1) Right click on session and Kill in Activity Monitor (2) Kill Session_id

While tracing server activities using profiler, any blocking occurs?


While using “Tuning template” in profiler causes blocking.

What is Deadlock?
A deadlock occurs when users try to place exclusive locks on each other’s objects.
Ex: - User1 places an exclusive lock on Table1 and then tries to place an exclusive lock on Table2. User2
already has an exclusive lock on table2, and User2 tries to put an exclusive lock on Table1. This condition
causes endless loop of waiting for the locks to be released.
The Database engine picks one of the victim (users) and kills their query and send a error message to users
“You are the victim of a deadlock and try again later”.
Deadlock Information Tools
Trace Flags: - DBCC TRACEON (1204) & DBCC TRACEON (1222). When these trace flags is enabling, the
deadlock information captured by the SQL Server error log. DBCC TRACEON (3605, 1204,-1).
Deadlock graph event in SQL Profiler: - SQL Server Profiler graphically representation of tasks and resources
involved in a deadlock. (Lock: Deadlock and Lock: Deadlock chain events in the Locks events)
System View: - We can find the blocking sessions by writing the following query
Select session_id, status, blocking_session_id from sys.dm_exec_requests where blocking_session_id > 0
Resolving Deadlock: - After find the session causing the problem we can use KILL command. > KILL
process_id
The following types of resources can cause blocking that could result in a deadlock.
 Locks.
 Worker threads. A queued task waiting for an available worker thread can cause deadlock.
 Memory. When concurrent requests are waiting for memory grants that cannot be satisfied with the
available memory, a deadlock can occur.
 Parallel query execution-related resources Coordinator, producer, or consumer threads associated
with an exchange port may block each other causing a deadlock
 Multiple Active Result Sets (MARS) resources.
To help minimize deadlocks:
• Access objects in the same order.
• Avoid user interaction in transactions.
• Keep transactions short and in one batch.
• Use a lower isolation level.
• Use a row versioning-based isolation level.
o Set READ_COMMITTED_SNAPSHOT database option ON to enable read-committed
transactions to use row versioning.
o Use snapshot isolation.
• Use bound connections.
• In stored procedures or programming we have to handle deadlocks using TRY/ CATCH blocks. In Catch
block when error number 1205, write the logic to run the query again.

What is bound Connection? Bound connections allow two or more connections to share the same transaction
and locks. Bound connections can work on the same data without lock conflicts. Bound connections can be
created from multiple connections within the same application, or from multiple applications with separate
connections
Types of Bound Connections: Local bound connection (Single server)
Distributed bound connection (Multiple servers)

What are the Types of Locks? Explain each? USEBISK


Lock: DB engine locks the rows/page/table to access the data which is worked upon according to the query.
There are 7 locks types are available in SQL Server 2005.
a) Shared Lock:- Shared (S) locks allow concurrent transactions to read (SELECT) a resource under
pessimistic concurrency control.
b) Update Lock:- Used on resources that can be updated. Prevents a common form of deadlock that
occurs when multiple sessions are reading, locking, and potentially updating resources later.
Questions are collected by K.V.N SUBBA REDDY
c) Exclusive Lock:- Exclusive (X) locks prevent access to a resource by concurrent transactions
d) Intent Lock:- Used to establish a lock hierarchy. The types of intent locks are: intent shared (IS),
intent exclusive (IX), and shared with intent exclusive (SIX).
e) Schema:- Used when an operation dependent on the schema of a table is executing.
f) Bulk Update:- Used when bulk copying data into a table and the TABLOCK hint is specified
g) Key-Range:- Protects the range of rows read by a query when using the serializable transaction
isolation level

What is a live lock?


When a request for exclusive lock is denied again and again because a series of overlapping shared locks are
interfering with each other and to adapt from each other they keep on changing the status, it is known as live
lock.
A human example of live lock would be two people who meet face-to-face in a corridor and each moves aside to
let the other pass, but they end up moving from side to side without making any progress because they always
move the same way at the same time and never cross each other. This is good example of live lock.

What is NOLOCK?
Using the NOLOCK query optimizer hint is generally considered good practice in order to improve concurrency
on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are taken when data is
read. The result is a Dirty Read, which means that another process could be updating the data at the exact time
you are reading it. There are no guarantees that your query will retrieve the most recent data. The advantage to
performance is that your reading of data will not block updates from taking place, and updates will not block your
reading of data. SELECT statements take Shared (Read) locks.

What is lock escalation? What is its purpose?


Lock escalation is when the system combines multiple locks into a higher level one. This is done to recover
resources taken by the other finer granular locks. The system automatically does this. The threshold for this
escalation is determined dynamically by the server.
Purpose:
 To reduce system over head by recovering locks
 Maximize the efficiency of queries
 Helps to minimize the required memory to keep track of locks.

Error severity 13 indicates what? Transactional deadlock errors.

Describe optimistic and pessimistic concurrency.


Optimistic concurrency: - Assumes that a resource is likely to be available at all times. This means that
resource locking is very unlikely. If a conflict occurs, the application must read the data and attempt the change
again.
Pessimistic concurrency: - This locks the resources as and when required. A transaction can be assured to be
completed unless a deadlock occurs.

What is Database Snapshot? Give the Syntax?


A Database snapshot is a read-only static view of the database. Snapshots must be located on the same
server. Snapshots doesn’t contain un-committed transactions at the time of snapshot was taken. It is very
useful for report queries. (This option is available in 2005 EE edition)
Ex: - CREATE DATABASE AdventureWorks_dbss1800 ON (NAME = AdventureWorks_Data, FILENAME =
'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\ AdventureWorks_data_1800.ss') AS
SNAPSHOT OF AdventureWorks;

What is Transaction? What is Transaction (ACID) Properties?


Transaction is a set of Logical unit of work and it contains one or more database operations. A valid transaction
should be met (ACID) Atomicity, Consistency, Isolation, Durability properties.
Atomicity:- A transaction must be an atomic unit of work, either all of it data modification are performed (or)
none of them is performed. Example: The transaction subtracts 10 from A and adds 10 to B. If it succeeds, it
would be valid because the data continues to satisfy the constraint. However, assume that after removing 10
from A, the transaction is unable to modify B. If the database retains A's new value, atomicity and the constraint
would both be violated. Atomicity requires that both parts of this transaction complete or neither.
Consistency:- When completed a transaction must leave all data in consistent state. In a relational database, all
rules must be applied to transactions modifications to maintain all data integrity. All internal data structures, such
as B-tree indexes (or) double linked lists must be correct at end of transaction. Example: Rules that can be
enforced by the database system are that the primary keys values of a record uniquely identify that record, that
the values stored in fields are the right type and in the right range.
Questions are collected by K.V.N SUBBA REDDY
Isolation:- Modifications made by concurrent transactions must be isolated from the modifications made by the
other consequent transactions. A transaction either sees a data in the state it was in before another concurrent
transaction modified it, (or) sees the data after second transaction completed.
Durability:- After a transaction has completed, its effects are permanently in place in the system. The
modification persists even in the event of a system failure. Example: Recovery to the most recent successful
commit after a database software failure, an application software failure, a CPU failure, a disk failure.

Describe isolation levels that SQL server supports


The isolation level describes the degree to which the data being updated is visible to other transactions
Serializable: All transactions occur in a completely isolated fashion. This means all the transactions must
execute serially.
Repeatable Read: All data records that are fetched by the Select statement cannot be changed unless a
Phantom read occurs in case where clause is mentioned.
Read committed: Data records retrieved by a query are not prevented from modification by some other
transaction. in this level, read locks are acquired on selected data but released immediately. Write locks are
released at the end of the transaction
Read Uncommitted: Here, One transaction may see uncommitted changes made by some other transaction.
Hence, dirty reads are allowed.

Can you say syntax of transaction? Begin Tran ……… Statements…… Commit Tran

Explicit transactions Each transaction is explicitly started with the BEGIN TRANSACTION statement and
explicitly ended with a COMMIT or ROLLBACK statement. Implicit transactions A new transaction is implicitly
started when the prior transaction completes, but each transaction is explicitly completed with a COMMIT or
ROLLBACK statement.

Can you have a nested transaction?


Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

Explain about RAID and RAID levels?


RAID stands for Redundant Array of Independent Disks. Allows you to create a collection of disk drives that
appears to OS as a single disk. You can implement raid by using software and existing I/O components, or you
can purchase hardware RAID devices. Typically 0, 1, and 5 RAID levels are used in SQL Server.
RAID 0: RAID 0, actually provides no redundancy at all. It involves striping data across all the disks in the RAID
array, which improves performance, but if any of the disks in the array fail, then the whole array fails. In that
sense, RAID 0 actually increases the chance of failure. Consider RAID 0 as the zero redundancy RAID
RAID 1: RAID 1, is essentially disk mirroring. Each disk in a RAID 1 array has a mirror partner, and if one of the
disks in a mirrored pair fails, then the other disk is still available and operations continue without any data loss
RAID 3: On RAID 3 systems, data blocks are subdivided (striped) and written in parallel on two or more drives.
An additional drive stores parity information. You need at least 3 disks for a RAID 3 array.
RAID 5: RAID 5, requires at least three disks. It addresses the low disk utilization inherent with RAID 1 by using
parity to provide redundancy rather than storing a duplicate copy of the data on another disk. When a disk failure
occurs in a RAID 5 array, the data stored on that disk is dynamically recovered using the parity information on
the remaining disks.
Parity: A parity bit is an additional piece of data that, when created on set of bits, determines what the other bits
are.
RAID 10: RAID 10 combines the best features of RAID 1 and 0, Also known as RAID 1+0, RAID 10 combines
the benefits of mirroring and striping while avoiding the parity overhead of RAID 5. As such, a RAID 10 partition
provides excellent performance and redundancy at the expense of higher cost.

Explain about Database Tuning Advisor? What is Workload?


Database Tuning Advisor can analyze the performance effects of workloads run against one or more Databases
or a SQL Profiler trace (they may contain T-SQL batch or remote procedure call). After analyzing, it recommends
to add, remove or modify physical design structures such as clustered and non-clustered indexes, indexed views
and partitioning.
Workload:- A workload is a set of Transact-SQL statements that executes against databases you want to tune

What is DAC? How to connect DAC?


DAC is stands for Dedicated Administrator Connection. This diagnostic connection allows an administrator to
access running instance to troubleshoot problems or execute diagnostic queries on the server - even when SQL
Server is not responding to standard connection requests. This connection uses 1434 port and can connect only
one connection per instance.
To connect DAC:-
1) SQLCMD:- -Sadmin:<instance_name>
2) GUI:- SSMS Query Editor by connecting to ADMIN:<instance_name>
Questions are collected by K.V.N SUBBA REDDY

What is SQLCMD?
sqlcmd is enhanced version of the isql and osql and it provides way more functionality than other two options.

What is Activity Monitor and use of that? What are the permissions required to use Activity Monitor?
Activity Monitor is used to get information about users connections to the Database Engine and the locks that
they hold. Activity Monitor is used to troubleshooting database locking issues, and to terminate a deadlocked or
unresponsive process.
To use activity monitor:- VIEW SERVER STATE permission on Server and SELECT permission to the
sysprocesses & syslocks tables in the master database.
To Kill a Process:- sysadmin and processadmin database roles and permission are required to KILL a process.

What is Execution Plan and explain it?(Control L+M)


Execution Plan graphically displays the data retrieval methods chosen by SQL Server. It represents the
execution cost of specific statements and queries in SQL Server. This graphical approach is very useful for
understanding the performance of the query.
From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop‐down menu).
If this option is turned on it will display query execution plan in separate window when query is ran again.

What is Trace flag? Give some Trace flags?


Trace flags are used to temporarily set specific server characteristics or to switch off/on a particular behavior.
There are two types of trace flags: session and global. Session trace flags are active for a connection and are
visible only to that connection. Global trace flags are set at the server level and are visible to every connection
on the server. Some flags can only be enabled as global, and some can be enabled at either global or session
scope.
(1) 260 (2) 1204 (3) 1211 (4) 1222 (5) 1224 (6) 2528 (7) 3205 (8) 3625 (9) 4616 (10) 7806 (11) 1400(Mirroring)
(12) 3608
To set on/off Traceflag:- (1) DBCC TRACEON (2) DBCC TRACEOFF
To Enable Trace flag globally :- DBCC TRACEON with the -1 argument (Ex:- DBCC TRACEON 2528, -1)
-T startup option:- Indicates that an instance of SQL Server should be started with a specified trace flag (trace#)
in effect.
To Determine trace Flags are currently active:- DBCC TRACESTATUS

How to know corrupted pages information?


Corrupted pages information can be extracted from one of a MSDB table suspect_pages.
Using DBCC CHECKDB(dbname) command
How to troubleshoot corrupted pages?
We can restore suspect pages from existing backup file.
Restore DATABASE <dbName> Page=’pageid’ FROM DISK=’backupfile.bak’
From SQL Server 2008 on wards if there is database mirroring feature is configured on the database then
automatically pages are repaired. The repaired pages information we can check using
select * from sys.dm_db_mirroring_auto_page_repair

What are the common failures occur in SQL Server 2005?


There are three common failures occur in SQL Server 2005.
1) Database Failures
2) Physical Server Failures
3) SQL Server Service failures

What are the causes of Database Failures?


There are three common issues will causes Database failures. Log File viewer is very useful to diagnose these
problems that will occur in SQL Server 2005.
Database has run out of Disk space:-
If a Database is online, and running out of disk space the data cannot be inserted into the database.
If the Database during recovery, and the data file becomes full the Database engine marks the Database as
“Resource Pending”.
T. Log is full:-
If the Database is Online, and the T.Log becomes full the Database Engine issues 9002 error and it is in read-
only state and will not allow updates.
If the Database during recovery, and the T.Log becomes full the Database engine marks the Database as
“Resource Pending”.
TempDB has run out of Disk space:- TempDB stores User objects, Internal Objects and Version stores. If the
TempDB database runs out of space, it causes significant problems for SQL Server 2005. The errors are written
to SQL Server log and these errors (1101, 1105, 3958 ,3959, 3966, 3967) indicates TempDB has insufficient
space.
Questions are collected by K.V.N SUBBA REDDY
Tempdb growing fastly:Check long running queries dbcc opentran (tempdb)
To display all sessions sp_who/sp_who2
To display currently running query or active transactions: dbcc inputbuffer(54)
To kill session kill <spid>

Best practices to avoid tempdb problems:


Always its file should be in unrestricted grow mode.
Always its recovery model should be SIMPLE.
Set some minimal size for tempdb database.
Place the files in highest rpm disks.
Add some no of data files, similar to no of CPUs present in the server
Do not change collation from the SQL Server instance collation.
Do not change the database owner from sa.
Do not drop the TempDB database.
Do not drop the guest user from the database.

How to understand Database Engine Errors?


If any error occurs, the server writes error messages to logs (Database mail, SQL Agent, SQL Server &
Windows NT). These logs having Error number, Error message, Severity, State, Procedure name, Line number.
We can easy to understand errors by viewing Log file viewer.

What is Severity level in Event log? At what severity levels are written to the SQL Server log?
The Severity level tells how bad the error is. Above 19 Severity level errors are written to the SQL Server log.

What is State Attribute of an error message in Event log?


The state attributes provides details of what caused the error.
ERROR STATE ERROR DESCRIPTION
2 and 5 Invalid userid
6 Attempt to use a Windows login name with SQL Authentication
7 Login disabled and password mismatch
8 Password mismatch
9 Invalid password
11 and 12 Valid login but server access failure
13 SQL Server service paused
18 Change password required

What are the Causes of Physical Server Failures?


There are five common issues will causes Physical Server failures.
1.Disk failures 2.Memory failures 3.Processor failures 4.Network card failures
5.RAID failures

When size of the log file is physically reduced? There are three events, which forces SQL Server
Database file to Shrink.
 When a DBCC SHRINKDATABASE statement is executed.
 When a DBCC SHRINKFILE statement referencing a log file is executed.
 When an autoshrink operation occurs

Is Truncate LOG File and Shrink a log file is same thing ?


NO, both are altogether different operation. Shrinking means releasing free space to the Operating System
DBCC SHRINKFILE (<[your database logical log filename]>, 1)
whereas process of deleting log records to reduce the size of the logical log is called truncating log.
BACKUP LOG <[your database logical log filename]> WITH TRUNCATE_ONLY
If a LOG file is 100% used and active then Shrink operation will reduce the size of the transaction log file.

Why is my transaction log file growing rapidly


• Uncommitted Transactions
• Mirroring i.e. mirror server fail
• Replication i.e. distribution fail.
• Many active tranaactions
• Due to active VLFs
• Operations: DBCC DBREINDEX and CREATE INDEX
• While Restoring from Transaction Log Backups
Questions are collected by K.V.N SUBBA REDDY
• Client Applications Do Not Process All Results
• Queries Time Out Before a Transaction Log Completes the Expansion and You Receive False 'Log Full'
Error Messages

If Log file is full what you will do?


If the T.Log file is full the Database issues 9002 error and it is in Read-only state and will not allow updates.
To check possible reason: select name, log_reuse_wait_desc from sys.databases
The following tasks will responding T.Log file
1) Backing up the log
2) Adding one or more log files
3) Moving the Log to another disk
4) Increasing log file size or enabling auto growth
5) Teminating long-running transactins.

If Data file is full what you will do?


If the primary data file is full we can add secondary data files.
Adding a file to database: - Right click on database > Properties > Files > click add > give the values for logical
name, file type, file group, initial size, auto growth, path and file name .

If a Database is under Suspect mode? What you will do?


Possible Scenarios: If the database files are corrupted or there is disk issue. If restoration fails. If data file was
full,Log file got deleted un-expectedly,Unexpected shutdown of the instance – it may be power failure
sp_resetstatus:- Resets the status of a suspect database (sp_resetstatus ‘Adventureworks’)
Alter db set single_user->emergency->dbcc checkdb (‘dbname’, REPAIR_ALLOW_DATA_LOSS) ->Multi_user.

If the server has completely failed, and how to all the backups restored onto a new server?
a) Build the Windows server and restore the domain logins to support Windows authentication.
b) Install SQL Server and any service-pack upgrades.
c) Put SQL Server in single-user mode and restore the master database.
d) Restore the msdb database.
e) If the model database was modified, restore it.
f) Restore the user databases.

How do you know when a table is fragmented?


• Poor query performance over time.
• More disk activity.
• Poor cache utilization.
• Verify the I/O of a query.
• Verify scan density in SQL 2000 using DBCC SHOWCONTIG and in SQL 2005 using the dynamic
management view sys.dm_db_index_physical_stats.
Table fragmentation can occur when modifying data with INSERT, UPDATE, or DELETE statements, which over
time cause gaps in each page. If a query search is based on a table scan or partial table scan, then it will create
overhead for the SQL Server process with additional page reads, leading to high CPU activity and
unresponsiveness. Defragmentation targets logical fragmentation at the leaf level of an index, ensuring optimum
performance.

How can you reduce the fragmentation?


 The DBCC INDEXDEFRAG and DBCC DBREINDEX statements are best used to reduce table
fragmentation.
 DBCC INDEXDEFRAG will defrag the leaf level of an index, which will enable the physical order of
pages to match the logical order of the leaf nodes. This statement reports the estimated percentage of
the process every five minutes.
 When a database is created, make sure the data files are created with or assigned the largest values
possible.
 Specifying a maximum data file growth size that leaves some available space on the hard disk.
 If the data files are heavily used then locate them in a different file group or on a different partition.
 If the table row(s) are modified or deleted frequently then it is better to run intermittent UPDATE
STATISTICS on the table, which will help it avoid any slow performance from the execution plan.

What is Index Segmentation?


A segment is a part of relational data base and consists of one or more extents. Each extent is further divided
into blocks. Every segment has an index for holding all of its data for quick data retrieval. Index segments can be
created explicitly by using the CREATE INDEX
Questions are collected by K.V.N SUBBA REDDY
If a Server performance is slow? How you can troubles shoot a problem?
 First check the processor and memory usage to see that processor is not above 80% utilization and
memory not above 40-45% utilization then check the disk utilization using Performance Monitor.
 Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which
might be a problem.
 Third would be to run UPDATE_STATISTICS command to update the indexes
What are the Performance Issues? Explain them?
Resource bottlenecks: CPU, memory, and I/O bottlenecks
Performance Monitor, SQL Server Profiler, DBCC commands, DMVs Extended Events, Data collector and the
management data warehouse (MDW)
Tempdb bottlenecks: Temporary user objects, Internal objects, Row versions
A slow-running user query: Changes in statistics, Missing indexes, Index fragmentation, Excessive blocking
and dead locks.

If a Database Performance is slow? How can you do Performance Tuning?


Step 1 - Task Manager: This one is very basic. Check the task manager whether SQL Server consuming most
of the CPU/Memory. A overall CPU usage exceeding 65%, with SQL contributing the majority (excess of 40%) is
perhaps a high usage. SQL can use only 50% of the RAM available (unless AWE is enabled).Any usage less
than the maximum allowed implies that your server is doing okay on memory front.
Step 2 - SQL Error log: : Check SQL Servers error log for any abnormalities. Note that by default errors with
Severity level between 19 and 25 are logged in sql error log.
Step 3 - Query sysprocesses/sys.dm_exec_query_stats: If your step 1 indicates high CPU or Memory
pressure then check sysprocesses right away. Check the number of connections that are using SQL Server.
This can be found by querying sysprocesses for spid greater than 50. On average OLTP systems, I would
expect 150 - 250 odd connections.
After connections, find the list of long running queries. If on SQL 2000 then observe the connection(spid) with
status = 'runnable' on sysprocesses. Fire DBCC inputbuffer(spid) to check the current statement running. If on
sql 2k5 use dm_exec_query_stats DMV to identify the longest query running .Also, note the connections that
are consuming high CPU/IO/Memory using sysprocesses.
Step 4 - Blocking queries: Identify blocking queries, if any. If on SQL 2005 use the script provided. If on SQL
2k use sp_lock/sp_who2.

What are the memory pools?


The memory pool is the main unit of memory for an instance of SQL Server. Almost all data structures that use
memory in an instance of SQL Server are allocated in the memory pool. The main types of objects allocated in
the memory pool are:
 System-level data structures: These are data structures that hold data global to the instance, such as
database descriptors and the lock table.
 Buffer cache: This is the pool of buffer pages into which data pages are read.
 Procedure cache: This is a pool of pages containing the execution plans for all Transact-SQL
statements currently executing in the instance.
 Log caches: Each log has a cache of buffer pages used to read and write log pages. The log caches
are managed separately from the buffer cache to reduce the synchronization between log and data
buffers. This results in fast, robust code.
 Connection context: Each connection has a set of data structures that record the current state of the
connection. These data structures hold items such as parameter values for queries and stored
procedures, cursor positioning information, and tables currently being referenced.

What is Full Text Search?


Full Text search allows for fast and flexible searching of text data stored in the database and can operate on
words as well as phrases based on rule of a particular language. It is not support in database snapshot.
What is Filtered Index?
Filtered Index is used to index a portion of rows in a table that means it applies filter on INDEX which improves
query performance, reduce index maintenance costs, and reduce index storage costs compared with full-table
indexes. When we see an Index created with some where clause then that is actually a FILTERED INDEX.

Clustering in SQL Server


It is concept of providing high avilability. By using using this we can reduce down time. It does not provide any
'Fault Tolarene' (i.e, I have Data Base, in this some table is missing.. By using Clustering we cont restore that
table data.)
Advantages: No down time i say ( i.e 99.9999%) not 100%.
Note:It is totally related to Windows based only. Not Sql Server related.
After installation of Clustering the total sql server behaves like normal sqlserver. There is no change in
Questions are collected by K.V.N SUBBA REDDY
behaviour.
Clustering supports only Server Operating Systems.
Requirements:
1. Minimum Two machines(we cal this machine as NODE) with same Hardware (Same Ram,
Same Hard drive, Same Processor)
2. Same Server Operating system(win 2003server..) in each node(Machine)
3. Active Directory in another machine(domain Controller)
4. SAN Box (Shared Array) like External Hard Disk.
5. 2 Network cards for each machine
6. 6 IP's (1 for Public Cluster, 1 for Public sqlserver, 4 for Network cards)

Types of Clusters ?
In Windows we can configure two types of clusters
1. NLB (network load balancing) cluster for balancing load between servers. This cluster will not provide any
high availability. Usually preferable at edge servers like web or proxy.
2. Server Cluster: This provides High availability by configuring active-active or active-passive cluster. In 2 node
active-passive cluster one node will be active and one node will be stand by. When active server fails the
application will FAILOVER to stand by server automatically. When the original server backs we need to
FAILBACK the application

Quorum: A quorum is essentially a log file, similar in concept to database logs. Its purpose is to record any
change made on the active node, and should any change recorded here not get to the passive node
because the active node has failed and cannot send the change to the passive node over the network,
then the passive node, when it becomes the active node, can read the quorum file and find out what the
change was, and then make the change before it becomes the new active node.
Quorum drive: Is a logical drive on the shared array devoted to the function of storing the quorum.

Why Quorum is necessary ?


For example, in a five node cluster that is using a node majority, consider what happens if nodes 1, 2, and 3 can
communicate with each other but not with nodes 4 and 5. Nodes 1, 2, and 3 constitute a majority, and they
continue running as a cluster. Nodes 4 and 5 are a minority and stop running as a cluster, which prevents the
problems of a “split” situation. If node 3 loses communication with other nodes, all nodes stop running as a
cluster. However, all functioning nodes will continue to listen for communication, so that when the network
begins working again, the cluster can form and begin to run.

Public and Private Networks: Each node of a cluster must have at least two network cards. One network card
will be connected to the public network, and the other to a private network. The public network is the
network that the SQL Server 2005 clients are attached, and this is how they communicate to a clustered
SQL Server 2005 instance. The private network is used solely for communications between the nodes of
the cluster. It is used mainly for heartbeat signal.

Heartbeat signal: In a cluster, the active node puts out a heartbeat signal, which tells the other nodes in the
cluster that it is working. Should the heartbeat signal stop then a passive node in the cluster becomes
aware that the active node has failed, and that it should at this time initiate a failover so that it can become
the active node and take control over the SQL Server 2005 instance.

The Virtual Server : When you create a cluster, one of the steps is to create a virtual cluster name and IP
address. This name and IP address is used by the active node to communicate with clients. Should a
failover occur, then the new active node uses this same virtual name and IP address to communicate with
clients.
Clustering Commands:
C:\>Cluster GroupTo listing status for all available resource group(Information of GROUP+NODE+STATUS)
C:\>cluster /cluster:node1 res -> To listing status for all available resources
C:\>cluster /cluster:node1 node -> To listing status for all available nodes
C:\>cluster /cluster:node1 group

Adding nodes in cluster:If u want add a node in 2005,we need to uninstall & rerun the setup,But from 2008,no
need to uninstall.,simple by click add node to sql server failover cluster in sql server installation center
ISCSI (Inter small computer system interface): Is a technology. It is used to show the drives in Node1 or
node2.
How to Failover the Cluster Group from Node1 to Node2 without any SQL Services Interruptions?
Sol 1 – Using CMD: Simply Issue the below command from your cmd prompt.
C:\>cluster group “cluster group” /move ->Moving resource group ‘cluster group’…
Questions are collected by K.V.N SUBBA REDDY
Sol2 – Using PS: Simply use Move-Cluster Group “Cluster Group”. You might get the below Error if you
are using Power shell for your Cluster for the First time.
PS C:\> Move-ClusterGroup “Cluster Group”.

How to generate Logs related to a specific Node?


c:\>Cluster log /gen /node:’’node1”

How to change the Quorum Configuration?


Right click on your Windows Cluster and choose More Actions->configure cluster quorum setting
Now, you can click Next and choose your Quorum Configuration type and proceed further.

Can we rename SQL Server failover cluster instance name?


Yes, if your SQL Server failover cluster instance is a default instance then you can just rename the SQL Network
Name which obviously changes the SQL Server instance name.
No, if you SQL Server failover cluster instance name is a named instance.

Is SQL Server supported on a geographically distributed cluster? Yes.

Does SQL Server support Windows Server 2008 R2 Hyper-V Live migration? Yes.

What is a server "cluster"? A server cluster is a group of independent servers managed as a single system for
higher availability, easier manageability, and greater scalability.

Does SQL Server 2000 clustering support load balancing?


SQL Server 2000 clustering does not provide load balancing; it provides failover support. To achieve load
balancing, you need software that balances the load between clusters, not between servers within a
cluster.

Does SQL Server 2000 Full-Text Search support clustering? Yes.

What does it take to create a server cluster?


The minimum requirements for a server cluster are (a) two servers connected by a network, (b) a method for
each server to access the other's disk data, and (c) special cluster software like Microsoft ® Cluster Server
(MSCS). The special software provides services such as failure detection, recovery, and the ability to manage
the servers as a single system.

What are the benefits of server clustering?


There are three primary benefits to server clustering: improved availability, easier manageability, and more cost-
effective scalability. Using Microsoft Cluster Server as an example:
 Availability: MSCS can automatically detect the failure of an application or server, and quickly restart it
on a surviving server. Users only experience a momentary pause in service.
 Manageability: MSCS lets administrators quickly inspect the status of all cluster resources, and easily
move workload around onto different servers within the cluster. This is useful for manual load balancing,
and to perform "rolling updates" on the servers without taking important data and applications offline.
 Scalability: "Cluster-aware" applications can use the MSCS services through the MSCS Application
Programming Interface (API) to do dynamic load balancing and scale across multiple servers within a
cluster.

What are clusters used for?


Customer surveys indicate that MSCS clusters will be used as highly available multipurpose platforms, mirroring
the current uses of the Microsoft Windows NT® Server operating system. Surveyed customers suggested that
the most common uses of MSCS clusters will be mission-critical database management, file/intranet data
sharing, messaging, and general business applications.

When a cluster is recovering from a server failure, how does the surviving server get access to the failed
server's disk data? There are basically three techniques that clusters use to make disk data available to more
than one server:
 Shared disks:
 Mirrored disks
 Shared nothing

What is "Wolfpack"? "Wolfpack" was the code name for Microsoft Cluster Server.

What is Microsoft Cluster Server (MSCS)?


MSCS is a built-in feature of Windows NT Server, Enterprise Edition. It is software that supports the connection
Questions are collected by K.V.N SUBBA REDDY
of two servers into a "cluster" for higher availability and easier manageability of data and applications. MSCS
can automatically detect and recover from server or application failures. It can be used to move server workload
to balance utilization and to provide for planned maintenance without downtime. And, over time, MSCS will also
become a platform for highly scalable, cluster-aware applications.

What is "failback," and how does it work in MSCS?


"Failback" is the ability to automatically rebalance the workload in a cluster when a failed server comes back
online. This is a standard feature of MSCS. For example, say "Server A" has crashed and its workload failed-
over to "Server B." When Server A reboots, it automatically finds Server B and rejoins the cluster. It then checks
to see if any of the cluster groups running on Server B would "prefer" to be running on Server A. If so, it
automatically moves those groups from Server B to Server A as soon as the time is right. Failback properties—
that is, which groups can failback, which is their preferred server, and during what hours the time is "right" for
failback—are all set from the cluster administration console.

How will MSCS help do load balancing?


Load balancing is the ability to move work from a very busy server to a less-busy server. MSCS will support load
balancing in four ways over time:
1. Manual load balancing:
2. Automatic cluster group load balancing:
3. Automatic workload balancing in "cluster aware" applications:
4. Automatic transaction load balancing through Microsoft Transaction Server:

Different types of Quorum in Windows server 2008 ?


1.Node Majority - Used when Odd number of nodes are in cluster.
2.Node and Disk Majority - Even number of nodes(but not a multi-site cluster)
3.Node and File Share Majority - Even number of nodes, multi-site cluster
4.No Majority - Even number of nodes, no shared storage

Different types of Quorum in Windows server 2003 ?


1.Standard Quorum 2.Majority Node Set Quorums:

How is the quorum information located on the system disk of each node kept in synch?
The server cluster infrastructure ensures that all changes are replicated and updated on all members in a
cluster.

Can this method be used to replicate application data as well? No, that is not possible in this version of
clustering. Only Quorum information is replicated and maintained in a synchronized state by the clustering
infrastructure.

Can I convert a standard cluster to an MNS cluster?


Yes. You can use Cluster Administrator to create a new Majority Node Set resource and then, on the cluster
properties sheet Quorum tab, change the quorum to that Majority Node Set resource.

What is the difference between a geographically dispersed cluster and an MNS cluster?
A geographic cluster refers to a cluster that has nodes in multiple locations, while an MNS-based cluster refers
to the type of quorum resources in use. A geographic cluster can use either a shared disk or MNS quorum
resource, while an MNS-based cluster can be located in a single site, or span multiple sites.

Does a cluster aware application need to be rewritten to support MNS?


No, using an MNS quorum requires no change to the application. However, some cluster aware applications
expect a shared disk (for example SQL Server 2000), so while you do not need shared disks for the quorum, you
do need shared disks for the application.

Does MNS get rid of the need for shared disks?


It depends on the application. For example, clustered SQL Server 2000 requires shared disk for data.
Remember, MNS only removes the need for a shared disk quorum.

What does a failover cluster do in Windows Server 2008 ?


A failover cluster is a group of independent computers that work together to increase the availability of
applications and services. The clustered servers (called nodes) are connected by physical cables and by
software. If one of the cluster nodes fails, another node begins to provide service (a process known as failover).
Users experience a minimum of disruptions in service.
Questions are collected by K.V.N SUBBA REDDY
What new functionality does failover clustering provide in Windows Server 2008 ?
New validation feature. With this feature, you can check that your system, storage, and network configuration
is suitable for a cluster. Support for GUID partition table (GPT) disks in cluster storage. GPT disks can have
partitions larger than two terabytes and have built-in redundancy in the way partition information is stored, unlike
master boot record (MBR) disks.

What happens to a running Cluster if the quorum disk fails in Windows Server 2003 Cluster ?
1. Determine why the Quorum disk failed and repair.
2. Reprovision a new LUN, present it to the cluster, assign it a drive letter and format. Then start one node with
the /FQ switch and through cluadmin designate the new disk resource as the Quorum. Then stop and restart the
clussvc normally and then bring online the second node.

What happens to a running Cluster if the quorum disk fails in Windows Server 2008 Cluster ?
Cluster continue to work but failover will not happen in case of any other failure in the active node.

I know that a cluster node can contain several instances of SQL Server, but does a node represent a
single physical machine? Does a node can represent several virtual machines (deployed on a single
physical machine) ?YES

In a active/active/passive model, must all actives nodes have same installed databases ?
No, it is recommended that all versions will be same over all nodes

In a cluster, data are located on shared data. But what is the best thing to do in order to have backups of
the data?
I always copy backups another server for safety . But it node is failed over your backup jobs must running so
shared data should be there

What is Active/ Passive and Active/Active?


Active/Active: Here first node will be default and second node will be named instance. Both nodes will be
active.
Move group from cluster administration is possible for both sides. Active/Active clusters is really a mutli-instance
(in terms of SQL Server) cluster.System performance will go down, if both resources are in one node.

Active vs. Passive Nodes: In a two-node SQL Server 2005 cluster, one of the physical server nodes is referred
to as the active node, and the other one is referred to as the passive node. When we refer to an active
node, we mean that this particular node is currently running an active instance of SQL Server 2005 and
that it is accessing the instance's databases, which are located on a shared data array. When we refer to
a passive node, we mean that this particular node is not currently in production and it is not accessing the
instance's databases. When the passive node is not in production, it is in a state of readiness, so that if
the active node fails, and a failover occurs, it can automatically go into production and begin accessing
the instance's databases located on the shared disk array. In this case, the passive mode then becomes
the active node, and the formerly active node now becomes the passive node

Shared Disk Array: Unlike non-clustered SQL Server 2005 instances, which usually store their databases on
locally attached disk storage, clustered SQL Server 2005 instances store data on a shared disk array. By
shared, we mean that both nodes of the cluster are physically connected to the disk array, but that only
the active node can access the instance's databases. There is never a case where both nodes of a
cluster are accessing an instance's databases at the same time. This is to ensure the integrity of the
databases.
This shared array must have at least two logical partitions. One partition is used for storing the clustered
instance's SQL Server databases, and the other is used for the quorumHow to take Offline/Online? Right Click
on Group--> Select Offline

What are the issues you faced? The node getting down

What are the minimum IP's required for Clustering? For Two Cluster environment we need 6 IP's

How to trace failover?


What happened we plugged out SAN Box Cable?

Is it support Load balancing? NO

What is the minimum storage space require for Quorum? 500 MB

How much time it takes come online from Offline? 1 Min


Questions are collected by K.V.N SUBBA REDDY
What is heart beat? It is a process of authenticating both nodes it alive or not

What is group? A group is nothing but managing node resources separately

Is it possible to install Two Sql Server Instances in single Group? No, this feature is available in 2008
version

How to Stop and Start SQl Server Service in Cluster Environment?


From Cluadmin then Click on group-->Right Click on service appear in right side panel and Then click stop/start.
dont go to services.msc and stop from there

How to Check Is our Machine participating in Clustering? Select serverproperty('IsCluster')

How many cluster nodes are support in SQLSERVER 2005 with windows 2003 server? 8 nodes

How many cluster nodes are support in SQLSERVER 2008 with windows 2008 server? 16 nodes

How to add node for Cluster?

How many IP’s are required for 2 node cluster? 6 IP (2 external IP (public), 4 PrivateIP)

My SQL server instances are working fine on Node A but instances are not failover from Node B, what
could be the reason? Ans: Network down

Where we find Log files for clustering?


c:/program files/ windows/cluster. Log
cluster logs are stored in “C:\Windows\System32\winevt\Logs” folder with “etl” extension

How to read those .ETL files??


For that, we have to use “cluster.exe” command with “/gen” switch. Basically this will generate a human readable
text file in your “Reports” folder.
Syntax: c:\>Cluster log /gen

How to add drive for cluster?


Go to cluadmin->Choose groups from left side->Right click on add> Choose drive which we want to add for
existing cluster

Which cable is used for heart beat, Is it cross cable or plain cable? ANS: Cross cable

To check for Blocked Processes: Sp_who2


To find all the log files and the percentage space used of those log files in an instance: dbcc sqlperf
(logspace)
To list all the files and their details in a particular database:sp_helpfile
To list all the databases and their details in a instance:sp_helpdb
To shrink a database file without specifying target size(preferred for log files):dbcc shrinkfile(fileid)
To shrink a database file with specifying target size(preferred for datafiles):dbcc
shrinkfile(fileid,target_size)
To find the details about locks currently held by the processes:sp_lock
To find all the drive spaces through MS SQL:EXEC master..xp_fixeddrives
To put the database in single user mode at command prompt:sqlservr.exe –m
To put the database in Minimal mode at command prompt:sqlservr.exe –f -c for console applications
To find out the Database ID? Select db_id (‘db_name’)
To find out logins: - select * from sys.syslogins
To find out current user: - Select current_user
Short cut for MS SQL Server Management studio:sqlwb.exe
To check the service pack at product level: select serverproperty ('machinename')
SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY
('edition')
To check the open transactions :dbcc opentran(‘dbname’)
To find MS SQL Server product level details:exec master..xp_msver
To find the details of current processes running like percent completed:select * from
sys.dm_exec_requests
To find the longest running queries sys.dm_exec_query_stats
Questions are collected by K.V.N SUBBA REDDY
Command to find the free space and used space :select * from dbo.sysfiles
To check load in server and database and files:select * from sys.dm_io_virtual_file_stats(database id,file id)
To find the longest running queries sys.dm_exec_sql_text
To find Orphan login:sp_validatelogins
To find orphaned users EXEC sp_change_users_login 'Report'
To map users to logins sp_change_users_login @Action='update_one',
@UserNamePattern='<database_user>', @LoginName='<login_name>'
If you already have a login id and password for this user, fix it by doing:sp_change_users_login 'Auto_Fix',
'user'
To delete login:exec sp_revokelogin ‘USERX’
To list all the objects owned by user id: Select name from sysobjects where uid=user_id('user')
To enable ‘show advanced options’ for server configuration options:sp_configure 'show advanced options',
1
To enable particlar server configuration option:sp_configure 'option name', 1
To find performnce related stastictics:select * from sys.dm_os_performance_counters
To find the information about indexes on tables and views.select * from sys.dm_db_index_usage_stats
To find out all of the users who are connected to the database server:select * from sys.dm_exec_sessions
To display the error log using the query:xp_readerrorlog
To display error log archive numbers and their dates:sp_enumerrorlogs
To view no. of traces running.SELECT count(*) FROM :: fn_trace_getinfo(default) WHERE property = 5 and
value = 1
To find details about the traces which are runningSELECT * FROM :: fn_trace_getinfo(default)
To terminate a trace EXEC sp_trace_setstatus 1, @status = 0 / @status=2
To know the Space used bye Data,index in particular Database:Sp_spaceused
To know the DB status of particular Database:SELECT DATABASEPROPERTYEX('AdventureWorks',
'Status')
To view jobs which failed at last run: sysjobactivity, sysjobschedules, msdb.dbo.sysjobservers,
msdb.dbo.sysjobs
To check pages of table : Dbcc ind(‘dbname’,’tablename’,-1)
To check pages contents dbcc trace on(3604) dbcc page(‘dbname’,fid,pid,1) F:File P:page
To set maximum connections? SP_Configure
To find no.of connections? Sysprocess
If log file is full,To find out reason? Select name,log_reuse_wait_desc from sys.databases

IIS Interview Questions

What is the Role of IIS ?


 IIS provides a redesigned WWW architecture that can help you achieve better performance, reliability,
scalability, and security for our Web sites.
 IIS can support following Protocol HTTP/HTTPS, FTP, FTPS, SMTP Etc.
 We need to host the site on IIS, when request comes from client it first hits the IIS Server, then the
server passed it to ASP.NET worker process to execute. Then the response also passes to client via IIS
itself.
 Note only Hosting of Site we can create our FTP Server, SMTP Server using IIS itself.
 There are different version of IIS available like 5.1, 6.0, 7.0 etc

What are the different version on IIS that you have worked on ?
Windows Server 2008 - Windows Vista - Home Premium/ Ultimate - IIS 7.0
Windows Server 2003 - IIS 6.0
Windows XP Professional - IIS 5.1
“what is the difference between them ? ”

What is Application Pool in IIS ?


 Concept of Application pool has from IIS 6.0 .
 Application pools are used to separate sets of IIS worker processes that share the same configuration
and application boundaries.
 Application pools used to isolate our web application for better security, reliability, and availability and
performance and keep running without impacting each other.
 The worker process serves as the process boundary that separates each application pool so that when
one worker process or application is having an issue or recycles, other applications or worker processes
are not affected
 One Application Pool can have multiple worker process Also.
Main Point to Remember:
1.IsolationofDifferentWebApplication
Questions are collected by K.V.N SUBBA REDDY
2.Individual worker process for different web application
3.More reliably web application
4. Better Performance

What is the Name of Default Application Pool in IIS ?


IIS having its own default application pool named : DefaultAppPool

What are the different types of Identity available in IIS 6.0 ?


IIS having three different Identity.
1. Local System 2. Local Services 3. Network Services

Name of default Identity of IIS6.0


Default Identity of IIS 6.0 is Network Services . Which is having very minimum rights on your system. The user
can only have the read access of the site.

What is Recycling of Application Pool?


Recycling Application pool means recycle the Worker process (w3wp.exe) and the memory used for the web
application. There are two types of recycling related with Application pool
1.Recycling Worker Process - Predefined Settings
2. Recycling Worker Process - Based on Memory

What are the main layers of IIS Architecture?


IIS having mainly two layers Kernel Mode and User Mode
Below are the subsection of both of them.
1. Kernel Mode o HTTP.SYS
2. User Mode o Web Admin Service o Virtual Directory o Application Pool

What is the Role of Http.Sys in IIS?


 HTTP.SYS is the kernel level components of IIS. All client requests comes from client hit the Http.Sys of
Kernel level. HTTP.SYS then makes a queue for each and every request for each and individual
application pool based on the request.
 Whenever we create any application pool IIS automatically registers the pool with HTTP.SYS to identify
the particular during request processing.

What are the different security settings available in IIS ?


Below are the commonly used IIS Security settings
1 Anonymous
2 Integrated Windows Authentication
3. Basic Authentication
4. Digest Authentication
5. Passport Authentication
6. Client certificate mapping authentication
7. IIS Client certificate mapping authentication
For Set security permission you need to go to Virtul Directory > Right Click > Properties >
Directory Security Click on Edit Button .

What is the default authentication settings for IIS ?


Anonymous authentication is the default authentication mode for any site that is hosted on IIS, and it runs under
the "IUSR_[ServerName]" account.

What is web garden ?


By default Each Application Pool runs with a Single Worker Process (W3Wp.exe). We can assign multiple
Worker Process with a Single Application Pool. An Application Poll with multiple Worker process called Web
Gardens. Each Worker Process Should have there own Thread and Own Memory space.
Generally its not recommended to use InProc Session mode while we are using Web Garden.

What is Web Farm?


When we hosted our web Application on multiple web server under a load balancer call the Web Farm. This is
generally used for heavy load web application where there are many user request at a time. So When Web
Application is hosted on Different IIS Server over a load balancer, Load balancer is responsible for distribute the
load on different server.

Where session data stores in case of "In-Proc" Session mode ?


Session data store inside process memory of worker process [ w3wp.exe ] .
Questions are collected by K.V.N SUBBA REDDY
How we can create an web garden? For creating web graden we need to go to Application Pool, then Right
Click on Application Pool > Properties > Goto Performance Tab In Web Garden Section, increase the number of
worker process. By default it is 1.

How we can debug a web application which is hosted on IIS ?


We can easily debug any web application that are hosted on IIS by using Attaching of Worker Process.
From Visual Studio IDE > Tools > Attach To Process Select the particular Process, then start debugging.

How we can open IIS Configuration manager ?


Just simply Run >inetmgr or we can open it from control panel > Administrative tools.

How we can create a Virtual Directory on IIS ?


Open IIS Configuration Manager. First of all Right Click on Default web sites > New > Virtual Directory.
Browse the Physical Path. Set the properites. Click on OK

What are the permission settings are available for Virtual Directory ?
Below are the list of permission that can be set during virtual directory creation
1. Read 2. Run Scripts 3. Execute 4. Write 5. Browse

What is the folder location for Virtual Directory? <Drive>:\inetpub\wwwroot

What is the use of Enable Pinging Properties for Application Pool?


IIS should periodically monitor the health of a worker. Pining means, Activation Process monitor Worker process
performance, health, idle time etc. By default it sets to 30s .

Does One Web Application can have multiple Application Pool ?


No. Every Web Application should have one Application Pool. By default it is "DefaultAppPool ".

Which version of IIS is available in Windows Server 2008?


IIS 7.0 . Even Vista Home Premium and Ultimate edition is also having IIS 7.0

How we can save an Application Pool Settings?


Application Pool Settings can be save as "XML" Format. Right Click on Application Pool > All Task > Save
Configuration to a File . We can make it password protected also.

Which Tool is used for Remote IIS Debugging? Tool is: msvsmon.exe
This is located at: Install path\Microsoft Visual Studio 8\Common7\IDE\Remote Debugger\x86

What are the different authentication mode available for IIS Remote Debugging ?
For IIS Remote Debugging msvsmon supported two authentication mode
1. Windows Authentication 2. No-Authentication

How can we get the list of worker process running in IIS along with the Application pool name ?
By running iisapp.vbs script from command Prompt. Below are the steps:
1. Start > Run > Cmd
2. Go To Windows > System32
3. Run cscript iisapp.vbs

If there are multiple worker process running on IIS, then how can you attach a particular worker process
for application? Well, If there are multiple worker process running in IIS, it means I have to know the name of
my application pool. Then I can run cscript iisapi.vbs script to find out the process ID and Application Pool
name. Based on the process Id for particular application I have to attache the process from Visual studio IDE.

Why do we need to IIS Remote Debugging? There are following reasons where we can use remote
debugging
1. Your development server does not have IIS installed.
2. Development server and Build/Released/Hosting Server is different
3. Multiple users want to debug simultaneously.

Does IIS allows multiple user to Remote debug simultaneously? Yes. This is one of the great features of
msvsmon.exe . Each instance of the remote debugger has a unique server name. we can give an instance of the
remote debugger any server name. Now multiple user can able to access the server instance.

What is the use of aspnet_regiis -i command?


Questions are collected by K.V.N SUBBA REDDY
This is used automatically register the .NET Framework with your IIS.

Can we have multiple web sites on IIS? Yes. IIS Can have multiple web sites and Each and every web sites
can have multiple virtual Directory. Note : Here web sites means the Root Node.

Where is the default location for IIS Log files? Its C:\WINDOWS\system32\LogFiles\W3SVC1

What is ISAPI Filter?***


 ISAPI filters are DLL files that can be used to modify and enhance the functionality provided by IIS.
 ISAPI filters always run on an IIS server, filtering every request until they find one they need to process.
 The ability to examine and modify both incoming and outgoing streams of data makes ISAPI filters
powerful and flexible.
 Filters are registered at either the site level or the global level and are initialized when the worker
process is started.
 A filter listens to all requests to the site on which it is installed.
 Both ISAPI filters and ISAPI extensions can only be developed using C/C++.
 Visual Studio comes with wizards that make ISAPI development fast and easy.

What is an ISAPI? ISAPI's are implemented using palin old DLLS used for compilation of IIS Pages,

Possible Uses for ISAPI Filters ISAPI filters can be registered with IIS to modify the behavior of a server.
For example, filters can perform the following tasks:
• Change request data (URLs or headers) sent by the client
• Control which physical file gets mapped to the URL
• Control the user name and password used with anonymous or basic authentication
• Modify or analyse a request after authentication is complete
• Modify a response going back to the client
• Run custom processing on "access denied" responses
• Run processing when a request is complete
• Run processing when a connection with the client is closed
• Perform special logging or traffic analysis.
• Perform custom authentication.

What are the major innovation in IIS 7.0 ?


Components are designed as module and there are major change in administration settings.

What is the Role of Windows Activation Process in IIS ?


WAP is the Controller of Worker process under an Application Pool. Windows Activation Process which is
managed by the worker process by starting, stopping and recycling the application pool.
When to start, stop and Recycle should be defined on Application Pool Settings.
Activation Process is also responsible for Health Monitor of Application Pool during runtime.
FYI: Health monitoring setting can be easily found in Properties of Application Pool.

What are the different type of application pool available in IIS 7.0 ?
IIS 7.0 having two types of application pool. 1. DefaultAppPool (Integrated) 2. ClassicAppPool

What are the worker process for IIS 5.1 and IIS 6.0 ? For IIS 5.1 > aspnet_wp.exe For IIS 6.0 >
w3wp.exe

How can we set the default page for any web application ? We can set the default page for a web site from
the Virtual Directory Setting. How To : IIS Manager > Virtual Directory > Right Click > Properties > GoTo
Document Tab.

How we can set the Idle Time out of an worker process ?


We can set the Idle time out for a worker process from Application Pool Properties. In Performance Tab of
Application pool, we can set the Idle Time out of the worker process. This means worker process will shut down
after that given time period if it stay idle. And will again wake up again if a new request comes.

Is there any alternative way to host site on IIS rather than opening IIS Manager ?
Yes, We can directly host any site from the physical location of directory itself. Right Click on Physical Folder >
Properties > Web Sharing There you need to select > "Share This Folder" Option Button. Then it will ask for
alias name and other setting. Then Click on OK. To Validate : Run > Inetmgr > Check there should an virtual
directory with the same "Alias" name that you have given. If there are already one Virtual directory exist it will
showing you the error message while you providing the "Alias" name.
Questions are collected by K.V.N SUBBA REDDY
Can we create one Application Pool From Another Application Pool ?
Yes. We can. While creating Application Application Pool From IIS, there should have two option available first
one is for Default Setting and Another is for Existing Setting as template. We can select the second one and
from the drop down listed below we can select any on the Application Pool as Template,.

What are the main components of SVCHost.exe ? Main components for SVCHost.exe are WWW Publishing
Service (W3SVC) and Windows Activation Process (WAP) . W3SVC is the mediator of HTTP.SYS and Windows
Activation Process. Windows Activation Process maintain the worker processes.

What are the different way that we can hosted site on IIS ?
We can hosted site on IIS either creating Virtual Directory through IIS manager or Using Folder Web Sharing .
Apart from that Visual studio provide some inbuilt features to host the site on IIS like using Publishing the web
site , Using Copy web Tool or Creating Virtual directory during the creating the project by choosing Location as
HTTP

How does IIS process an ASP.net request ?


When client request for an aspx pages, request comes to kernel level off IIS means to HTTP.SYS . HTTP.SYS
receives the request and based on the application pool name [ Which is already registred with the HTTP.SYS ] it
send the request to worker process. Windows Activation process works as mediator of them. w3wp.exe loads
"aspnet_isapi.dll" files to start the HTTPRuntime . HTTPRuntime creates HTTPApplication objects and all
request are passed through HTTPModule and finally reached to HttpHandler . This is the request pipeline. After
end of Request pipeline ASP.NET Page lifecycle starts.

From where we can set the Session Time Out in IIS ? We can set the Session time out settings from the
Virtual Directory for that site. Right Click on Virtual Directory > Properties > Click on "Configuration" Button
Goto the "Option" Tab. There in Enable Session State Section you can configure the Session Timeout .

What are the different "Execution Permission" available for IIS for an virtual directory ?
There are three Execution Permission available.
1. None 2. Scripts Only 3. Scripts and Executable

From where you can change the ASP.NET Version in IIS ? This can be change from Virtual Directory
properties. First open Properties of Virtual Directory > GoTo ASP.NET Version Tab. There we can have change
the ASP.NET Version.

What is the latest version of IIS released with Windows 7? IIS 7.5

How can we take back-ups in IIS Server?


Step 1 : In the IIS (inetmgr), right click on the "Computer" icon under "Internet Information Services" . Click "All
Tasks" and select "Backup/Restore Configuration".
Step 2 : Click on button "Create backup". Give Name for your backup file. If you want encryption enable
encryption option and give UserName and Password and then click OK.

What is IIS metabase? And In which format IIS stores configurations?


IIS metabase is a special database which is used to maintain the settings and configurations data for IIS. In
simple term, it is a configuration base for IIS (Metabase.xml).
IIS 5.0 --> Metabase is in Binary. IIS 6.0 & 7.5 --> Metabase is in XML.

List of Error & Status codes in IIS 6.0? Status Code Type of Code
100 Series - Informational 400 Series - Client Error
200 Series - Success 500 Series - Server Error
300 Series - Redirection

How to recycle application pool from the command prompt in IIS7?


1. Use appcmd.exe to recycle the application pool from the command prompt.
2. appcmd.exe is the command line tool for IIS7, you will find this tool at following location : %systemroot
%\system32\inetsrv\appcmd
3. To recycle your application pool use the following command:
appcmd recycle apppool /apppool.name:<application pool name>

What are the Different steps to be followed to get SSL(Secure Sockets Layer) for our Web Application ?
 Intially we have to Generate a certificate request from our IIS
 Now we have to request a certificate from the certificate authority(CA)
 This CA is an entity which issues Digital Certificates.
Questions are collected by K.V.N SUBBA REDDY
 After receiving the certificate we have to install that particular certificate on our Web Server using IIS
 We have to use Secure Hyper Text Transfer Protocol(HTTPS) when accessing secure pages in our
application.
 By this way we could make our web page as SSL protected. !!!

Which DLL is used to translate XML to SQL in Internet Information Services (IIS)? Sqlisapi.dll

What is the purpose of IIS application pools?


We use applicaiton pools for isolation purpose. Every application within an application pool used the same
worker process. Each worker process operates as a separate instance of the worker process executable,
W3wp.exe, the worker process that services one application pool is separated from the worker process that
services another.
In simplest words we use applicaiton pools for ISOLATION purpose.

what is Windows Process Activation Service ?


The Windows Process Activation Service (WAS) provides process activation, resource management and health
management services for message-activated applications. It manages application pool configuration and the
creation and lifetime of worker processes for HTTP and other protocols (net.tcp,net.pipe,net.msmq)

What are the Different Authentication Methods(Using Windows Authentication) which are provided by IIS
?
Generally IIS provides four different kinds of Authentication Methods they are :
Anonymous Method If we select this authentication, IIS doesn't perform any authentication so that any one can
access the application.
Basic Metho If we select this method, the user who access the application should provide windows username
and password to access the application. Although this is sent through a network by transmitting direct text so it it
very insecure.
Digest Method This method is almost equal to Basic method but the difference is the password is hashed
before it is transmitted through out a network.
Windows Integrated Method In this the application uses the Kerberos protocol to validate(Authenticate) the
user. This uses a Secret key cryptography which provides strign authentication for Client/Server applications.
Client Certificate Mapping A certificate is a digitally signed statement that contains information about an entity
and the entity’s public key, thus binding these two pieces of information together. A trusted organization (or
entity) called a Certification Authority (CA) issues a certificate after the CA verifies that the entity is who it says it
is. Certificates can contain different types of data.

How can we check whether IIS is being installed in my system or not?


To verify if IIS is installed or not we need to go to ’Add or Remove Programs’ utility in the Control panel and click
on the ’Add/Remove Windows Components’ in the side menu. There we must locate an item called "Internet
Information Services (IIS)". If this is checked, IIS should be installed. So that you can have your IIS installed in
your system if it is not installed

IIS Port numbers?


HTTP : 80 (default port for iis), SSL : 443,FTP : 21,SMTP : 25,POP2 : 109,POP3 : 110,IMAP : 143,NNTP :
119,LDAP : 89, DNS : 53,DHCP : 67

IIS Services? These are the default iis services


1. www services 2. FTP services 3. SMTP services 4. NNTP services

In which process does IIS runs? IIS runs in 2 modes (application isolation modes): 1. worker process isolation
mode is a new feature of IIS6.0. 2. IIS5.0 isolation mode – for compatibility with apps depending on IIS5.0

What is App Pool and App Domain? What is the difference between these two?
Application Pool is created the each and every website.
Application Domain is created to one domain Purpose.

What is the difference between IIS 5.1 and 6 Administration?


IIS 5.1 is for Windows XP. IIS 6 is for Windows Server, We can create separate application pool with worker
process for a separate website, in IIS 6.0 Server only.

What is the properties of App Pool in IIS? The properties are: 1.Recycling 2.Perfomance 3.Health
4.Identity

In which process does IIS runs (was asking about the EXE file)
Questions are collected by K.V.N SUBBA REDDY
inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests among other things. When an
ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it
by passing the request to the actual worker process aspnet_wp.exe.

IIS Isolation Levels?


• Low (IIS Process): ASP pages run in INetInfo.Exe, the main IIS process, therefore they are executed in-
process
• Medium (Pooled): In this case ASP runs in a different process, which makes this setting more reliable: if ASP
crashes IIS won’t.
• High (Isolated): Each ASP application runs out-process in its own process space, therefore if an ASP
application crashes, neither IIS nor any other ASP application will be affected. The downside is that you
consume more memory and resources if the server hosts many ASP applications.

How to add multiple websites with same port no. and same ip address?
Using Host Headers In IIS Manager, right click on a Web Site

What is the settings that you need to do inorder an ASP code to run?
Enable Web Service Extensions from IIS Menu from the Left Panel of IIS Manager

How to take back up of IIS Configuration & Settings?


Using IISBack.vbs from C:\Windows\System32\ directory
Usage: @command prompt> cscript IISBack.vbs {Paramaters}
What is default port for SSL? Ans: 443 whats the default port for IIS?Ans: 80

If suppose every time I add a Web Site into my IIS Manager, the default port should take 8080? What will
you do?
The default port of 80, will be defined in IIS Metabase file located at C:\Windows\System32\inetsrv directory
then I will change the default port of 80 to 8080 in the metabase file
Any idea on NLB? Have you worked on it?
Yes, but just in a test environment, by enabling NBL through the LAN Properties

I will give you a scenario: If suppose we are having 50 Web sites running on a IIS Server, and suddenly
there is a load on CPU taking it to consume 90-100 % frequently. How will you troubleshoot to know
which application is taking this much CPU usage?Before answering what is the process which runs the
application in IIS?
w3wp.exe is the process which makes the applications runs in IIS.
First I will check in Task Manager(Run>Taskmgr) then i will see a number of w3wp.exe processes running.
I will check which one is taking the most CPU usage
I will make a note of the PID for that particular w3wp.exe
Then through command prompt, go to C:\Windows\System32>
in the prompt I will use the command IISApp.vbs , to find particular application name associated with that PID

Action SSMS-Shortcut Key


Move to the SQL Server Management Studio menu bar ALT
Display the context menu(Right click) SHIFT+F10
Display the New File dialog box to create a file CTRL+N
Display the New Project dialog box to create a new project CTRL+SHIFT+N
Display the Open File dialog box to open an existing file CTRL+O
Display the Open Project dialog box to open an existing project CTRL+SHIFT+O
Display the Add New Item dialog box to add a new file to the
CTRL+SHIFT+A
current project
Disp the Add Existing Item dialog box to add an existing file to the
ALT+SHIFT+A
current project
Display the Query Designer CTRL+SHIFT+Q
Close a menu or dialog box, canceling the action ESC
Clear all bookmarks CTRL-SHIFT-F2
Cancel a query ALT+BREAK
Connect CTRL+O
Disconnect CTRL+F4
Disconnect and close child window ALT+F4
Database object information ALT+F1
Clear the active Editor pane CTRL+SHIFT+DEL
Comment out code CTRL+SHIFT+C
Questions are collected by K.V.N SUBBA REDDY
Decrease indent SHIFT+TAB
Delete through the end of a line in the Editor pane CTRL+DEL
Find CTRL+F
Go to a line number CTRL+G
Increase indent TAB
Make selection lowercase CTRL+SHIFT+L
Make selection uppercase CTRL+SHIFT+U
Paste CTRL+V or Shift+Insert
Remove comments CTRL+SHIFT+R
Repeat last search or find next F3
Replace CTRL+H
Select all CTRL+A
Undo CTRL+Z
Execute a query F5 or Ctrl + E
Help for Query Analyzer F1
Help for the selected Transact-SQL statement SHIFT+F1
Switch between query and result panes F6
Switch panes Shift+F6
Window Selector CTRL+W
New Query window CTRL+N
Object Browser (show/hide) F8
Object Search F4
Parse the query and check syntax CTRL+F5
Print CTRL+P
Display results in grid format CTRL+D
Display results in text format CTRL+T
Move the splitter CTRL+B
Save results to file CTRL+SHIFT+F
Show Results pane (toggle) CTRL+R
Save CTRL+S
Insert a template CTRL+SHIFT+INSERT
Replace template parameters CTRL+SHIFT+M
Display estimated execution plan CTRL+L
Display execution plan (toggle ON/OFF) CTRL+K
Index Tuning Wizard CTRL+I
Show client statistics CTRL+SHIFT+S
Show server trace CTRL+SHIFT+T
Use database CTRL+U

If Above Questions are helpful to u ,Say thanks to [email protected]


If U faced any other questions in interview,send Questions to same mail id.

You might also like