34
1) What is SQL server? Micro soft SQL server 2005 is a database platform for large-scale online transaction processing (OLTP), data warehousing, and e-commerce applications; it is also a business platform for data integration, analysis, and reporting solutions 2) What are 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), 10(2008). 3) What is the difference between SQL server 2000 and 2005? SQL server-2000 SQL server-2005 SQL server-2008 SQL Server 2012 T-SQL T-SQL as well as CLR Compress backup file option Columnstore Indexes -- This a cool new feature that is completely unique to SQL Server Enterprise manager SSMS 3 min for storing the backup file User-Defined Server Roles -- DBAs have always had the ability to create custom database role, but never server wide Query Analyzer Query editor Stores large files in sql server immigrated for Oracle BIG data support DTS SSIS Date & time data types AlwaysOn Availability Groups -- This feature takes database mirroring to a whole new level No Reporting Tools SSRS New features added like CMS(central mngt server) allows you to mngt multiple SQL server into once. Windows server core support(CMD Prompt) No Exception handling in DTS Exception handling in SSIS PBM-policy based mngt. it allows you to define & enforce policies for configuring & managing SQL server to your enterprise. Can create up to 16 instances Can create up to 50 instances ‘sa’ blank password Enforce password policy No database mirroring Database mirroring Object oriented programming Common language runtime 4) What are the editions available for SQL server 2005? There are six editions available in SQL Server 2005 A) Enterprise Edition B) Standard Edition C) Developer Edition D) Workgroup Edition E) Mobile Edition F) Express Edition 5) What are the tools available in SQL Server 2000 and 2005? Sl 2000 2005 1 Enterprise manager & Query analyzer Management Studio

What is SQL Server Updated

Embed Size (px)

Citation preview

Page 1: What is SQL Server Updated

1) What is SQL server? Micro soft SQL server 2005 is a database platform for large-scale online transaction processing (OLTP), data warehousing, and e-commerce applications; it is also a business platform for data integration, analysis, and reporting solutions

2) What are 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), 10(2008).

3) What is the difference between SQL server 2000 and 2005?

SQL server-2000 SQL server-2005 SQL server-2008 SQL Server 2012T-SQL T-SQL as well as

CLRCompress backup file option Columnstore Indexes -- This a cool

new feature that is completely unique to SQL Server

Enterprise manager SSMS 3 min for storing the backup file User-Defined Server Roles -- DBAs have always had the ability to create custom database role, but never server wide

Query Analyzer Query editor Stores large files in sql server immigrated for Oracle

BIG data support

DTS SSIS Date & time data types AlwaysOn Availability Groups -- This feature takes database mirroring to a whole new level

No Reporting Tools SSRS New features added like CMS(central mngt server) allows you to mngt multiple SQL server into once.

Windows server core support(CMD Prompt)

No Exception handling in DTS

Exception handling in SSIS

PBM-policy based mngt. it allows you to define & enforce policies for configuring & managing SQL server to your enterprise.

Can create up to 16 instances

Can create up to 50 instances

‘sa’ blank password Enforce password policy

No database mirroring

Database mirroring

Object oriented programmingCommon language runtime

4) What are the editions available for SQL server 2005?There are six editions available in SQL Server 2005A) Enterprise EditionB) Standard EditionC) Developer EditionD) Workgroup EditionE) Mobile EditionF) Express Edition

5) What are the tools available in SQL Server 2000 and 2005?

Sl 2000 20051 Enterprise manager & Query analyzer Management Studio

Page 2: What is SQL Server Updated

2 Network client utilities Configuration manager3 SQL profiler Profiler4 Service manager Surface area configuration5 Reporting services configuration6 Database tuning advisor7 Command prompt utilities

6) What are services available in SQL server? There are 3 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)

7) How many ways to run services?Services are run by 5 ways they areA) At task pane>right click on server and click start/stopB) Management studio>right click on server and click start/stop/restart.C) Surface area configuration D) Command prompt> Net start/stop mssqlserverE) SQL server configuration manager>right click on server and click start/stop/restart.

8) What is a window Authentication? When windows authentication is used to connect SQL server, Microsoft windows is completely responsible for authenticating the client by identifying its windows user account.

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

10) What is the difference between Windows Authentication and SQL Server authentication?a) 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 person will be less, windows authentication uses the default windows login credentials. b) 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.c) 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.

11) What is AWE? How configure dynamic memory allocation? Generally SQL Server reserves only a small portion of memory. Sometimes reserved memory is not sufficient to SQL server and required additional memory. AWE 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 up to 4GB 2) EE up to 32GB 3) DC up to 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.

12) What is the linked server? How to connect to it and test it?One server connected with another server to execute queries against OLEDB data sources on remote servers.

Page 3: What is SQL Server Updated

OLEDB Provider: an OLEDB provider is a DLL that manages and interacts with a specific data sources such as SQL Server-7.0, Access, Excel, ODBC, Oracle, DB2, Local file system, Exchange Server etc. SQL Native client (PROGID:SQLNCLI) is the official OLEDB provider for SQL server.

To connect to linked server using OLEDB provider: sp_addlinkedserver @server=’servername’,@srvproduct=’SQLServer/Oracle’ Tests the connection to a linked server:

sp_testlinkedserver<server name>Note: select * from sys.servers select state_desc from databases

13) What is purpose of registered servers?Registering a server to store the server connection information for future connections.

14) What do you mean by collation?Collation is basically the sort order. There are three types of sort orders a) Dictionary case sensitive,b) Dictionary case insensitive,c) Binary

15) What are the protocols used in Networking? What is the default port number of TCP/IP?The protocols uses in networking are TCP/IP, NAMED PIPES, VIA, SHARED MEMORY(Dedicated admin connection). The default port no of TCP/IP is: 1433.

16) What is the syntax used for find the SQL server version?A) Select @@versionB) Click on server>summary reports>server dashboard>configuration details>see product version. Note: select server property (edition, product version, product level)

17) What is blocking? How to identify and resolve the blockings?Blocking happens when one user holds an exclusive lock on an object and a second user requires an exclusive lock on the same object. This forces the second user to wait, block on the first. (system.DB_operational_stats)Determine Blocking sessions: activity monitor, spwho2, sp_lock, sys.sysprocess, sys.dm_exec_requets, sys.dm_os_waiting_tasks. Resolve Blocking session: 1) right click on session and kill in Activity monitor 2) kill session_id (sysdm_exec_query_stats)

18) What is Deadlock? [Kill SPID with stats only]A deadlock occurs when users try to place exclusive locks on each other’s objects. Ex: user-1 places an exclusive lock on table-1 and then tries to place an exclusive lock on table-2. User-2 already has an exclusive lock on table-2, and user-2 tries to put an exclusive on table-1. This condition causes endless loop of waiting for the locks to be released. The data base engine picks one of the victim(users) and kills their query and send an error message to users “you are the victim of a deadlock and try again later”. Deadlock Graph Event:lock : deadlock & deadlock chain event.Deadlock information tools: DBCC TRACE ON(1222, -1)

a) Trace flags: DBCC TRACEON (1204) & DBCC TRACEON (1222). When these trace flags is enabling, the deadlock information captured by the SQL Server error log.

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

Page 4: What is SQL Server Updated

c) System views: 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

d) Resolving deadlock: after find the session causing the problem we can use KILL command.

>KILL process_id

19) What are the types of Locks? Explain each?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.c) Exclusive lock: Exclusive(x) locks prevent access to a resource by concurrence transactionsd) 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 levelNote: update lock prevents common found of dead locks.

20) What are the Components can be installed with SQL server 2005?We can install the following components with Microsoft SQL server 2005A) SQL server database engineB) Analysis servicesC) Reporting servicesD) Notification servicesE) Integration servicesF) Management servicesG) Documentation and samples

21) What are the SQL server Editions of SQL server 2005?SQL server 2005 is available in 32-bit and 64-bit editions. a) SQL server 2005 Enterprise Edition(32-bit&64-bit)b) SQL server 2005 Evaluation Edition(32-bit&64-bit)c) SQL server 2005 Standard Edition(32-bit&64-bit)d) SQL server 2005 workgroup Edition(32-bit only)e) SQL server 2005 Developer Edition(32-bit&64-bit)f) SQL server 2005 Express Edition(32-bit only)g) SQL server 2005 Compact Edition(32-bit only)h) SQL server 2005 Runtime Edition(3-bit & 64-bit)

22) what is the process of installation?

logical file name:

• physical location• name of the folder • path location

Software Requirements to install SQL server 2005:

o IISo .NET framework 3.5

Page 5: What is SQL Server Updated

o SQL Native client o windows installer 4.5 o IE 6.0 or latero SQL server support fileso system configuration checkero security

Hardware Requirement for SQL Server 2005:

o minimum --> 512 MB RAMo Minimum -- > Pentium 3 processoro Approximately 800 MB hard driveo Enterprise edition supports only in server editions [WINDOWS 2000, 2005, 2008].

23) The process and review of SQL server installation?A) To install SQL server-2005: to prepare your computer for SQL server-2005, review hardware and software requirements, system configuration checker requirements and blocking issues, and security considerations.B) Install SQL server 2005: To install SQL server 2005, run setup using the SQL server-2005 installation wizard or install from the command prompt. You can also add components to an instance of SQL server 2005, or upgrade to SQL server 2005 rfom a previous SQL server version.C) Configure your SQL server 2005 Installation : After setup completes the installation of SQL server 2005, you can configure SQL server using graphical and command prompt utilities.

Note: To change the installation of existing components --> ARPWRAPPER

24) What is the virtual memory? How to assign virtual memory & how much space required for virtual memory?A reserved disk space to maintain transactions whenever memory (RAM) is full. Virtual memory size is at least 15 times of the physical memory installed in the computer.To set virtual memory: right click on system>select system properties advanced> performance settings>advanced>virtual memory>change>select directory>provide min and max values.Note: Virtual memory needs to be changed at directory level.Note: Min log file size is 512 KB

25. Tell me the process of upgradtion ? Upgradation: moving the instances and its db’s from lower version to higher version

1.inplace upgradtion (package migration wizard):moves sql 2000 to instance to sql 2005.so your older version won't be visible.this requires down time.in sql 2000 services.msc shows the instance service as MSSQL $ <instance_name>before upgrade of sql 2000 instance make sure your instance latest service pack on sql 2000 then you can proceed for upgradation to 2005

2.side by side upgradtion (upgrade advisor): [sql 7\2000 to 2005]take the full backup of all db’s in 2000\7 for precautionary purpose. script all the logins and jobs in 2000\7. install sql server 2005.

detach all the user db’s in sql 7\2000 and copy the files. attach all the user db’s in sql 2005 run the script taken in step 2(to re create logins/jobs) in order to migrate dts packages to SSIS. Once everything completed login and check the application functionality

Page 6: What is SQL Server Updated

(make sure that to change the compatibility level to 90(sql 2005) for whatever the user db’s we transferred1.run DBCC updateusageDBCC UPDATEUSAGE (‘db_name’) with count_rowsIn sql 2000 sometimes the metadata will be out of sync but in sql 2005 it was taken careAfter running the DBCC UPDATEUSAGE cmd if it doesn’t return any error the it means the db is good .if there is some error the it fixes and shows up the errors 2.run DBCC check DBDBCC checkdb (‘db_name’) with ALL_ERRORMBGS

DATABASE

1) What is database? What are the files created while creating a database?A database is a collection of meaningful and related data that are stored in row and columns format (table). While creating a database is SQL server there are two data files are reated called master data file(.mdf), log data file(.ldf) and we can add one or more optional N-Dimensional data files(.ndf).Note: user data and objects --> primary data file.

2) Explain about data files(.mdf, .ldf, .ndf)(file structure)?Primary data file(.mdf): Primary data files holds user data ans 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(.ndf). Log data files(.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. Min log file size is 512 KB.

3) What is lazy writer?lazy writer monitors the size/use of buffer cache and, it scans the whole data cache to age out any pages that haven't uses for a while.Note: VSO scans, monitors the free physical memory on the server and releases the memory from the buffer list back to windows

4) How store the data in SQL server? What is page and page size? What is Extent and Extent size?The fundamental unit of data storage in SQL server is the PAGE. The size of the page is 8 kb. Collection of eight contiguous pages is known as an EXTENT. The size of an extent is 64 kb(8x8). In a DB 1 MB = 16 extents

DatePage 1

2 3 4 5 6 7 8

1 Extent 5) What is fill factor? How to assign fill factor?

A fill factor is 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.Assign Fill factor: right click on server>properties>database settings>default index Fill factor>provide the value.

6) Tell me about system database and user database in 2000 and 2005?SQL server-2000:1)Master 2)Model 3)MSDB 4)Temp DBSQL server-2005: 1)Master 2)Model 3)MSDB 4)Temp DB 5)Resource DB

Page 7: What is SQL Server Updated

7) Explain about system databases in SQL server-2005?There are five system databases available in SQL server-2005.

A) Master database: records server level objects such as login accounts, End points, linked servers, system configuration settings, location of the database files and initialization information for SQL server. SQL server cannot starts if Master DB is unavailable.

B) Model database : the model DB is used as a template for all databases created on instances of SQL server. If we create a new database the model DB structure will be inherited to new database.

C) MSDB database: the MSDB database is used by SQL server agent for scheduling alerts and jobs and by other features such as service broker and database mail. SQL server automatically maintain completed online backup and restore history in MSDB.

D) TempDB : Temp DB is a global resource DB. It stores user objects (global or local temporary tables, stored procedures, table variables, or cursors), internal objects intermediate results for spools or sorting) and versions(onine index operations, multiple active result sets(MARS) ,and AFTER triggers). We cannot bacup the temp DB because when SQL server start or stop the Temp DB can be deleted permanently or refresh Temp DB.Note: tempDB is resource global DB. it contains global temporary tables, and local temporary tables.

E) Resource Database: The Resource database is a hidden (read only)database that contains all the system objects such as sys.objects that are included with SQL server 2005. The resource database makes upgrading process easier and faster.

8) 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 re build the master database.SQL server 2000 (Rebuild Master DB: start>run>rebuild.exeSQL server 2005 (Rebuild Master DB) :start> run> setup.exe

9) How to move model, MSDB, TempDB?a. Check the path of temp DB through sp_helpDB temp DB b. ALTER DATABASE tempdb MODIFY FILE (NAME = tempdev, FILENAME = ’E:\tempdb .mdf’)c. Stop the servicesd. Move the files to desired locatione. Restart the servicesf. Check the path of tempDB through sp_helpDB tempDBNote: Recovering model, msdb, tempdb can be done by rebuilding master start/ wait. Trace 3607 recovers master.

10) How to move master database?a. Check the path of master db through sp_helpDB masterb. Stop the servicesc. Change the path at startup parameters

SQL server configuration manager> services> right click on service> properties> advanced> add new_path at startup parametersd. Move the files to desired locatione. Restart the servicesf. Check the path of master DB through sp_helpDB master

REBUILDING MASTER DATABASE

Start / wait setup.exe/in <INSTANCE NAME> --> Reinstall = SQL engine

rebuild database = 'master' = 1

Note: By re-building master database we can re-create model and msdb.

11) What are the database states and explain them?The main database states are online, offline, restoring, recovering, resource pending, suspect and emergency.

Page 8: What is SQL Server Updated

12) What is database snapshot? Give the syntax?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 ADVENTURE WORKS_DBSS1800 ON(NAME = Adventureworks_data, FILENAME =’c:\programfiles\Microsoft SQL Server\MSSQL.1\MSSQL\ Data\ Adventureworks _data_1800.ss’) AS SNAPSHOT OF Adventureworks;

13) What is Transaction? What are 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.a. Atomicity: A transaction must be an atomic unit of work, either all of it data modification are performed or none of them is performed.b. 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.c. 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.d. 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.Note: there are transaction 1) Implicit transactions and 2) explicit transaction.

14) What are transaction Isolation levels?An Isolation level determines the degree of isolation of data between concurrent transactions. The default isolation level is read committed.a. Read uncommittedb. Read committedc. Repeatable readd. serializable

ISOLATION --> Row versioning is possible.Snapshot Isolation: allowing updates.

15) 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.

16) Explain about RAID and RAID levels?RAID stands for Redundant Array of Independent Disks. RAID is a disk system that contains arrays to provide greater performance, reliability, storage capacity, and lower cost. Typically 0, 1, and 5 RAID levels are used in SQL server. Note: transaction log RAID 1, data files RAID 5.

17) If a database in single user mode? How to change into Multi-user mode?After database <database name> set multi_user

18) Minimal mode and single user mode?Minimal mode: start->run->command prompt->SQLSERVER.EXE-fSingle user mode: start->run->command prompt-> SQLSERVER.EXE-m

19) 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 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’

Page 9: What is SQL Server Updated

Note: DB users not mapped to security identifier.

20) What is row size of a database?Row size of database is 8060 bytes.

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

22) What is check point?Check point is a operations that synchronizes the physical data with the current state of the buffer cache by writing out all modified data pages in buffer cache to disk. Note: Trace flag 3502--> undocumented trace flag that records in the error log when Check Point start/stop synchronizes the physical data with state of buffer cache.• check point flushes dirty pages from buffer cache to data file.• check point does not remove the page form cache. • check point is the point in time created by check point process.

23) How many ways you can move the data or databases between servers and databases?SSIS, DTS, ATTACH & DETACH, Bulk copy program, bulk Insert & importand Export wizard.

24) Syntax for find out the database ID?Select db_id(db_name)

25) Syntax for find out Logins? Current user?To find out logins: select*from sys.sysloginsTo find out current users: select current_user

26) Backup and Recovery errors?After a full backup of DB-> restore verify only from disk = 'C:\DB_FULL.bak'

Results: the backup is valid.backup Errors: 1. Media errors, 2. Backup fails, 3. Checksum errors.Media Errors: Cannot copy to the N/W drive (Permission problem)

Specified N/W drive not accessible( location cannot detect).Backup Fails: If backing up the tran_log & if the recovery model is simple then error out.

While backing up the T-Log, check there should be a full backup.Checksum Errors: If we check the option backup with checking then it verifies the pages that had checksum, calculates the trace flag option checksum. If it doesn't match then errors out.--> Continue after error.

27) What will you do if the TempDB is full?1. Move tempDB from one drive to another drive. 2. Truncate the transaction log file of tempDB.3. Make sure that tempDB is set to 'AUTOGROW' [Note: DO not set MAX size for tempDB].4. Use tempDB

GOEXEC SP_HELpLINEGO

OUTPUT: NAME FIELD FILENAME FILEGROUP SIZEuse mastergo alter database tempdb modify file (name = tempdev, filename = 'D:\datatempDB.mdf')

28) Errors we will get when we are accessing data files Files permission at OS level.

Page 10: What is SQL Server Updated

database may be suspect mode files may be removed logical disk drive full trace or log files present in SQL server log folder in real directory. SQL server job failed.

29) List some DBCC Commands?DBCC checkDBDBCC shrinkfileDBCC checkidentDBCC updateusageDBCC DBreindexDBCC showcontigDBCC shrinkdatabaseDBCC checktableDBCC indexdefrag

RECOVERY MODELS:

1. What is recovery model? Benefits of recovery models?”A recovery model is a database property that controls the basic behavior of the backup and restore operations for a DB”. Recovery models are designed to control transaction log maintenance.(how it can be truncated and regulated)

2. Explain full, bulk-logged & simple recovery models?a. Full: with full recovery model we can recover the data up to the minute of crash (point in time),because itrecords everyoperation in the transaction log.b. Bulk-logged: with bulk logged recovery model we can recover most of the data. But we will lost bulk-operations becausethose are not recorded in to the log. We can set this option just beforeperforming a bulkinsert operation to speed up the bulk insert.Note: bulk operations --> insert into, BCP, create index, alter index, write text, blog.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 todatabase after the last backup was performed will be lostbecause they are not recorded in the transaction log. Generally it is useful for test and development databases or data warehouses, but it is not appropriate choice for production database.

3. Which DBs can we use simple recovery model?Simple recovery model is useful for development, test databases, data warehouses or not often changed databases.

4. In which recovery models point-in-time recovery is possible?Point-in-time recovery is possible only in full and bulk-logged recovery models. bulk-logged recovery model point-in-time recovery is may or may not possible.NOTE: Recovery models are used for controlling transaction-log maintenance.

Page 11: What is SQL Server Updated

5. In system DBs what are the default recovery models used?Master -simpleModel -fullMSDB -simpleTempDB -simple

6. Why in simple recovery model we can’t take T.Log backup?In simple recovery model the Transaction logs are truncated. In simple recovery model, every transaction is logged into transaction log, but at regular intervals when check point occurs, t-log file is truncated.

7. Can we take Diff. backup in simple recovery model?We can take differential backup in simple recovery model because it belongs to .mdf

BACKUPS

1. What is backups? Types of backups?“a copy of data that is used to restore and recover the data after a system failures.” There are four types of backups available

1.full backups 2. Differential backup 3. Transaction log backup 4.file/file group backup

2. What is use of backups?Backup is safe guard to databases because data may can loss due to many failures such as media failures, user errors, hardware failures and natural disasters etc. with good backups, we can recover database from failures.

3. What is full, diff, T.Log backups? 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.b. Differential backup: differential backup records only the data that has change or modified extents since the last 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.d. File-file group backup: file and file group backups are specialized form of DB backup. In which only certain individual file (or) file groups from a DB are backup.WAL( write ahead transactional log)IT comes in file and file group. Sql server uses(WAL) which generates that no modifications are written to disk before the associated log record is

4. Can we take Diff. backups without full backups?No, it is not possible. Note: Query to know the % of backup completedselect * from sys.dm_exec_request where session_ID = <SPID>

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

Page 12: What is SQL Server Updated

c. T.logbackup: backup log dbname to disk=”path”

6. 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 point of a failure. (A backup taken that have not been backed up just before restoring a database).Query: backup log database_name to disk = 'Path" with stop at = 'tail' with no truncate no recoveryNote:Active part of log will be bckedup. with the DB in suspect then 'with no_truncate

7. Backup’s strategy?Generally backups are done by client requirement. But most of the companies are following this strategy.1. Full backup: every Saturday evening 6.00PM2. Differential backup: every day evening 6.00PM3. Transaction log backup: every one hour

RESTORE

1. What is Restore? What are the recovery states? Explain each?Restore means recover the data from backups. There are three recovery states for restore.a) With recoveryb) With no recoveryc) Standby

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.b) With no-recovery: with no-recovery databases will comes to offline and and we can’t access DB. Generally except recent log we can choose with no-recovery option.c) Standby: with standby, databases will comes to online and users can have read only access. Generally except recent log we can choose standby option for read only access.

2. What are the common scenarios to restoring the data?1. To restore the lost and corrupted data after a system failure2. To restore a database onto a development system for user by application developers while developing and testing new code.3. To restore a database onto a test system to load test applications and database features.4. To restore a database on separate server as a read-only database to perform queries for reports.

3. In which edition on-line restoration possible?On-line restoration is possible only in enterprise edition

4. What are the syntaxes for restore?A. With recovery: restore database dbname from disk=”path” with recoveryB. With no-recovery: restore database dbname from disk=”path” with norecoveryC. Standby: restore database dbname from disk=”path with no standby.”

5. What is point-in-time restore and use of that?Point-in-time restore is used to restore the data base to a particular time just before a failure has occurred or before corrupt data.

6. Explain about STOPAT clause?STOPAT clause is used to restore a database at point of time.

Page 13: What is SQL Server Updated

7. Restore strategy?a. First restore recent last full backupb. Then restore last Diff. backupc. Then restore all transaction log backups.

8. Restore with move option:restore DB DBname from disk = 'path.bak' with move 'DBname' to 'Newpath_data.mdf'move 'DBname_log' to 'newpath_log.ldf' stats = 5 no recovery

9. Restore Errors:Restore with verify onlyRestore continue_after_error

10. what are the Different types of restore Options?1. Restore verify only: this verify the backup file (DB.bak) file is in readable format this doesn't restore the

DB. just check the backup file.2. Restore header only: If there are multiple databases backups in the backup device. you want to know DB

belongs to which backup file then this option to see al the information.3. Restore label only: This describes the information of the media set that is used to backup the information.4. Restore with No-recovery: DB is offline, still able to restore more transactions.5. Restore with standby: DB is visible, still able to restore more transactions.6. Restore with recovery: DB is online, not able to restore transactions.

LOGSHIPPING

1. What is lo shipping and purpose of log shipping?To achieve high availability and high protection, log shipping copies transactions from a ‘primary serve’ 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 standby mode)

2. What is primary server, secondary server & monitor server?a. 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 the primary server.b. 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.c. 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 monitors multiple log shipping configurations.

3. What are the Jobs running for log shipping and explain them?Log shipping having four operations which are handled by SQL server Agent job.a. Backup job: backup job is created on primary server instance and it performs backup operation. It logs history on the local server and monitor servers and deletes old backup files and history information.b. Copy job: copy job is created on secondary server instance and it performs copies the backup files from primary server to secondary server. It logs history on the secondary server and monitor server.

Page 14: What is SQL Server Updated

c. 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 server and deletes old files and history information.d. 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.

4. Requirements for log shipping?A. SQL server 2005 standard edition, workgroup edition, or enterprise edition must be installed on a l server instances involved in log shipping.B. All servers should have the same case sensitivity settings.C. The databases must use the full recovery model or bulk-logged recovery model.

5. 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 databasee. Choose copy and restore schedule for secondary database.f. Choose alert job scheduling for monitor server if configured.

6. What are permissions required for log shipping?We must have sysadmin on each server instance to configure log shipping.

7. In log shipping which recovery models can we used?We can use either full or bulk logged recovery model for log shipping.

8. Where you monitoring log shipping and how?We can monitoring the log shipping in the following ways.1. Monitor server()history tables: monitor server tracks all statistics, status and errors that could be happen during log shipping.

a. Log_shipping_monitor_primary: stores primary server statusb. Log-shipping_monitor_secondery: stores secondary servers status c. Log-shipping_monitor_history-detail:contains history details for log shipping agents.d. Log-shipping_monitor_error_detail:stores error details for log shipping jobs.e. Log-shipping_monitor_alert: stores slert job ID.

2. System stored procedures(MSDB): system stored procedures gives the history information about the specified server that are configured in log shipping.

a. Sp_help_log_shipping_monitor (run at monitor server)b. Sp_help_log_shipping_monitor _primary@primary_database=’DBName’(run at MS)c. Sp_help_log_shipping_monitor_secondary@secondary_database=’DBName’ (run at MS)

d. Sp_help_log_shipping_alert_job(run at Mon Server)e. Sp_help_log_shipping_primary_database@database=’DBName’(run at primary server)f. Sp_help_log_shipping_secondary_database@database=’DBName’(run at sec server)

3. Transaction log shipping status report(summary reports): this report showa the status of log shipping configurations for which this server instance is a primary, secondary or monitor.4. SQL Server agent job history5. Checking the SQL server log.

9. 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.a. Take the tail of log from primary serverb. Restore tail of log into all secondary database c. Remove lo shipping configuration from primary serverd. Select any one of secondary server and bring into online with alter database DBName set online

Page 15: What is SQL Server Updated

e. Right click on primary database and generate script for user and logins.f. Then move the scrpt to secondary server to create users and logins.

10. What are errors occurred in log shipping?There are two errors are occurred during log shipping1. 14420: this error occurs when the backup job fails2. 14421: this error occurs when the restoring job fails

MIRRORING

1. What is 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:a. Increases data protectionb. Increases availability of a databasec. Improves the availability of the production database during upgrades.Note: Mirroring uses full recovery mode. Morror server must be used with 'No recovery'

2. What are the prerequisites for database mirroring?A. both servers are requires same edition either standard edition or enterprise edition B. if witness server configured, the server should be installed standard edition, enterprise edition,

work group edition, or express edition.C. All servers should use the same master code page and collation D. Mirror server has same database name and use only with No recovery optionE. Mirroring uses the full recovery model(simple and bulk-logged not supported)F. All logins for connecting principle database should be reside on mirror database.

3. What are the restrictions for database mirroring?a. Maximum 10 databases per instance can support on 32-bit system b. Database mirroring is not supported with either cross-database transactions or distributed

transactions.

4. Explain about principal mirror and witness servers?1. Principal-server: one server serve 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 separate server.2. Mirror server: other server instance acts as a hot or warm standby server is czlled 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.

5. In which operations are running the operating modes?Asynchronous: under asynchronous operation, the principal server does not wait for a response from mirror server after sending long buffer.Synchronous: under the synchronous operation, the principal server sends the long buffer to the mirror server, and then waits for a response from the mirror server.

6. What are the operating modes and explain them?a. high availability: high availability mode, run synchronously. Requires a witness server instance. The principal server sends the log buffer to the mirror server, and then waits for a response from the mirror servers.

Page 16: What is SQL Server Updated

b. High-protection: high-protection mode, runs synchronously. Always commit changes at both principal and mirror.c. High-performance: high-performance mode, runs asynchronously and the transactions 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 but could data on the mirror server.

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

8. What is the end point ? how you create end point?An end point is a network protocol which is used to communicate over the network.Creation of an end-point: Create endpoint < endpoint name > State=started/stopped/disabled as tcp(listener port=5022/5023) for database_mirroring (role=partner/witness)

9. Which trace flag is used in mirroring?Trace flags are used to temporarily set specific server characteristic or to switch off/on particular behavior. 1400trace flag is sued in mirroring.To set trace flag for database mirroring: configuration manager> right click on server instance> properties>advanced tab> startup parameters> -t 1400(add).

10. In which recovery model we can use in mirroring?In mirroring the principal and mirror databases are used only full recovery model.

11. What is role –switching?Interchanging of roles like principal and mirror are called role switching. Note: Alter database <DB> Set = partner Failover.

12. What is syntax to stop the database mirroring?Alter database <database name> set partner off.

13. How to configure mirroring?a. Choose the principal server, mirror server, and optional witness server .b. The principal and mirror server instance must be running the same edition either standard

edition or enterprise edition.c. The witness server instance can run on SQL Server standard edition, enterprise edition,

workgroup edition, or express edition.d. mirror database requires restoring a recent backup and one or more T.log backups of the principal database(with no recovery)Note: Modification are written to disk only after the associated log records is written to disk.Mirror Configuration:

--> Click on configure security.--> provide the end points for witness server

* DBCC Show config (table, Index)Local Fragmentation & External Fragmentation: % of out of order pages returned from scanning the leaf pages of index. this number is not relieved to heaps.% of out of order extends returned from scanning the leaf page of index.Database Mirroring states:

SynchronizingSynchronizedsuspendedpending failoverDisconnected

Page 17: What is SQL Server Updated

14. What is the process of monitoring mirroring?a. SQL server management studio: a green arrow on the mirror server is indicates running well. A red arrow indicates problems that need to investigation.b. SQL server log: it provides information of mirroring establishment and status. If any error occurs it will be logged to SQL server log and windows event log.c. 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.d. Profiler: profiler many events are providing the status of the database mirroring.e. Database mirroring monitor: database mirroring monitor is a GUI tool that shows update status and to configure warning thresholds.To open DM monitor: right click on principal database>tasks> select launch database mirroring monitor. f. System stored procedures: Sp_dbmmonitoraddmonitoring Sp_dbmmonitorchangemonitoringSp_dbmmonitorhelpmonitoringSp_dbmmonitordropmonitoring

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

16. What is log buffer? A log buffer is special location in memory (RAM). SQL server stores the changes in the database’s log buffer.

--> Database files participating in mirroring can't be shrink by using truncate only option.--> to shrink the log file of D.B participating in mirroring 1) backup the log file to any location 2) check whether all the transactions are written to disk.

DBCC LOGINFO (DBNAME)3) Shrink file --> DBCC SHRINKFILE (FILE NAME, MIN SIZE)

Active Log: Min LSN to last written log record. recovered for full recovery of DB. Active part of log can never be truncated.Write a head transaction log: WAL Concept : Write a head login.Modifications are written to disk only after the associated log records are written, comes inn files and file groups.

17. How to set 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 adventure works SET WITNESS=’TCP://prassad.local;5024’(Do this from the principal server)

18. How to remove a witness server from database mirroring?SSMS: right click on principal database > task>mirror>remove tcp address from the witness>click ok.T-SQL: ALTER database adventure works SET WITNESS OFF.

19. How to setup fully qualified names for database mirroring? I. FQDN Error: One or more of the server network addresses lacks of fully qualified domain name(FQDN). Specify the FQDN for each server, and click start mirror again.The syntax for a fully qualified TCP address is:

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

II. RECTIFIFYING FULLY QUALIFIED NAME:1. To view end points: SELECT*FROM sys.database_mirroring_endpoint;

Page 18: What is SQL Server Updated

2. Remove existing all end points from the principal, mirror and witness servers;DROP END POINT[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 he 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 appropriate DNs suffix for the domainf. Select the changes 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.

20. What are the mirroring states?1. SYNCHRONIZING: (Transaction safety set to high)

The contents of the mirror database are lagging behind the contents of the principal database. 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 catch up .2. SYNCHRONIZED: (Automatic failover & manual failover are supported)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 transactions 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 stat.3.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 shut down and startups.1. PENDING FAILOVER: This state is found only on the principal server after a failover begun, but the server has not transitioned into the mirror role.

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. 2. DISCONNECTED: The partner has lost communication with the other partner.

21. Difference Between Log Shipping and Mirroring ?

Log Shipping Mirroring

1. Manual 1. Automatic option available

2. Secondary DB's can be any Number of 2. Only one secondary DB for a primary DB

3. Depends on SQL Agent 3. Depends on DB Engine

4. Operations in 2 modes

The two operation modes in mirroring are:

Page 19: What is SQL Server Updated

1. Synchronous: Principal server sends the log buffer to the mirror server, & waits for a response from a mirror server.2. Asynchronous: The principal server doesn't wait for a response from the mirror server after sending log buffer.

REPLICATION

1. 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 the synchronizing between databases to maintain consistency.Uses Of Replication: Allows DBA's to distribute data to different servers throughout an organization. For load balancing, offline processing, redundancy, offline batch processing. Note: there are 2 main components 1. Publisher 2. Subscriber.

2. What are the uses of replication?a. Server to server replication: 1. Improving scalability and availability.2. Data warehousing and reporting.3. Integrating data from multiple sites.4. Integrating heterogeneous data5. Offloading batch processing.b. Server to client replication:1. Exchanging data with mobile users2. Retail point of sale(POS)applications3. Integrating data from multiple sites

3. Types of replication and explain each?a. Snapshot replication: snapshot replication takes a picture or a snapshot of the database and propagated to the subscribers. It reduce 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) .b. Transactional replication: transactional replication starts with a snapshot of the publisher’s 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’s and subscribers in almost exactly the same state.c. Merge replication: merge replication starts with a snapshot of the publishers database. Subsequent data changes and schema modifications made at the publishers and subscribers are tracked with triggers. The subscriber synchronizes with the publishers when connected to the network and exchanges all rows that have changed between the polisher and subscriber since the last time synchronization occurred.Note: SP_ADD PUBLICATION SP_ADD ARTICLE SP_DROP SUBCRIPTION SP_HELP_LOGREADER_AGENT

4. Explain about publisher, subscribers and distributers?a. Publishers: the publisher is a database that makes data available for replication. The publisher can have one or more publications.b. Distributer: the distributer is the intermediary between the publishers and subscriber. It receives published transactions or snapshots and then stores and forwards these publications to the subscribers.c. Subscribers: subscribers are database server that store the replicated data and receive updates. A subscriber can the publisher or republish the data to other subscribers. 5. Explain about article, publication, subscription?

Page 20: What is SQL Server Updated

a. Articles: an article is the data, transactions, or stored procedures that are stored with in a publication. This is the actual information that is going to be replicated.b. Publication: the publication is the storage container for different articles. A subscriber can subscribe to an individual article or an entire publication.c. Subscription: the subscription is request by the subscriber to receive the publication.

6. Which recovery models are used for replication? FULL and Bulk-logged recovery models.

7. 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 subscription. By using replication monitor we can find out. 1) which subscription 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 agent Running

Snapshot agent Replication snapshot Snapshot: delivered Cmds/sec

Snapshot agent Replication snapshot Snapshot:delivered trans/sec

Log reader agent Replication log reader Log reader: delivered Cmds/sec

Log reader agent Replication log reader Log reader: delivered Trans/sec

Log reader agent Replication log reader Log reader: 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

8. 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 operation outside of replication.a. Snapshot agent: 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 distributer.

Page 21: What is SQL Server Updated

b. Log reader agent: the log reader agent is used for transactional replication. It moves information from the transaction log on the publisher to the distribution database.c. Distribution agent: 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.d. Queue reader agent: the queue reader agent is used for transactional replication with the queued updating option. It runs on the distributer and is responsible for reading messages from the queue on the subscribers and applying them to the appropriate publication.Replication Snapshot: Will be located on 'distributor instance home directory' MSSQL = REPLDATA replication agent.Transactional with updatable subscription: Transaction replication and merge replication both these replication starts with snapshot of publisher database. Merge replication modifications are tracked.

9. What are the agents used for transactional replication?a. Snapshot agentb. Log reader agentc. Distribution agent

10. What are the agents used for merge replication?a. Snapshot agentb. Merge agent

11. What is the process of transactional replication?Three agents are doing the process for transactional replication.

12. Out of synch issue in replication:Condition of replication in monitor replication track down the error under action message( Transaction sequence number - TSN) violation of 'primary key constraint could not insert duplicate key.

MANAGEMENT

1. What is Maintenance plan?Maintenance plans create a workflow for database optimization, and make free from inconsistencies.

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

PERFORMANCE TUNING:

1. 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 counter and logs, tasks manager, network manager.b. SQL server tools for monitoring components: SQL trace, SQL profiler, DMVs, system stored procedures, graphical show plans, activity monitor, DBCC, built-in-functions, trace flags.

Page 22: What is SQL Server Updated

SET SHOW PLAN_ALL ON/OFFSET SHOW PLAN_TEXT ON/OFF

2. How to identify longest running queries ?There are two ways to identify slow running queries 1 profiler (by using duration of query) 2 sys . dm _ exec_ query_ starts and sys. Dm_ exec _ requests DMVs3 DBCC OPENTRAN 4DBCC LOGINFO (DBNAME)

USEFUL DMV's:1. SYS_DM_OS_SYS_INFO; SYS.DM_EXEC_CONNECTION2. SYS.DM_OS_HOSTS3. SYS.DM_OS_SCHEDULERS4. SYS.DM.OS_MEMORY_CLERKS5. SYS.DM_DB_INDEX_USAGE_STATS

3. Reasons for Slow Running Query ?

There are a number of common reasons for slow- running querier a) Lack of useful indexes , Lack of useful data striping (RAID).b) Blockings, Table scans, Lack of useful partitioning c) Missing or out of date statistics (u p date 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

4. How to analyze query performance?We can an 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, see Displaying Execution plans by Using SQL Server Profiler Event Classes.

Note: Sql server returns detailed information for each statement.Normalization: The goal of normalization is to reduce problems with the data consistency by reducing

redundancy. there are 4 normalization forms:1NF: No repetitive columns in table. Use primary key to have related data in the same table with unique

columns.2NF: Primary key & Column use temporary tables instead of cursors. 3NF: remove columns that are not dependent on primary key.

5. How to increase query performance? We can improve query performance in the following ways. 1. Add indexes if required.2. Run Update statistics for out of date statistics.3. Resolving Blocking issues.4. Add space to DB files or TempDB, if that are not having enough space.5. Reduce the too much normalization.6. Using Temporary tables instead of Cursors.7. SPS and Triggers are with Set NOCOUNT on.

6. Explain about profiler? What are the uses of profiler?

Page 23: What is SQL Server Updated

SQL profiler 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 deadlockc. monitor stored procedures performanced. audit SQL server activity e. monitoring T-SQL activity per userf. 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

Note: MSDTC: It's a windows service providing, transact infrastructure for distributed system. Transaction ACID properties.

7. What are the events is captured SQL profiler? We can capture the events such as a. T-SQL statements, stored procedures b. Cursors, locks(deadlock)c. Database objects and auto growth of size of data & log filesd. Errors & warnings(syntax errors)e. Performance(show plan)f. Table scansg. Security audits(failed logins, password changes)h. Monitor server control, memory changes(cpu, reads,writes)i. Sessions, transactions, tuning.

8. Explain about database tuning advisor? What is work load?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 portioning.Workload: a work load is set of transact-SQL statements that executes against databases you want to tune.

9. 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. There are two types DMVs a. Server–scoped DMVs: require the VIEW SERVER STATE permission on the server.b. Database-scoped DMVs: require the VIEW DATABASE STATE permission on the database.

10. 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 for instance.To connect DAC:a. SQLCMD: -sadmin:<instance_name>.b. GUI: SSMS query editor by connecting to ADMIN :<instance_name>.

11. Explain about database console commands(DBCC)?DBCC commands are used to check the consistency of the database or database objects. While executing DBCC commands the DB engine creates a database snapshot and then runs the checks against this snapshot. After the DBCC command is completed, this snapshot is dropped.

Page 24: What is SQL Server Updated

12. What is stored procedure? What are the types of stored procedures available in SQL server and explain each?A stored procedure is a pre-compiled executable object that contains one or more transacts-SQL statements. a. User defined stored procedure: stored procedure are modules or routines that encapsulate code for reuse. A stored procedures can take input parameters, return tabular or scalar results and messages to the client.b. System stored procedures: system stored procedures are used to perform many administrative and informational activities.c. Extended stored procedures: these are used to create own external routines in a programming language such as c. extended stored procedure are DLLs that an instance of Microsoft SQL server can dynamically load and run.

13. 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 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 pemissions are required to KILL a process.

14. What is execution plan and explain it?Execution plan graphically displace 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.Query execution plan = query optimizer = Avg. estimate time.

15. 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 tat 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 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 To set on/off trace flag: 1.DBCC TRACE ON 2. DBCC TRACE OFFTo enable trace flag globally: DBCC TRACE ON with the -1 argument (Ex: DBCC TRACE ON2528, -1).

16. What are the causes of database failures?There are three common issues will causes database failure. Log file viewer if very useful to diagnose these problems that will occur in SQL server 2005.1. Database has run out of disk space: a. If a database is online, and running out of disk space the data we cannot be inserted into the database. b. if the database during recovery, and the data file becomes full the database engine marks the database as “resource pending”

2. T-log is full: a. if the database is online, and the T-log becomes full the database engine issues 9002 error it has in read-only state and will not allow updates. b. if the database during recovery, and the T-log becomes full the database engine marks the database as “resource pending”

3. Temp DB has run out of disk space: Temp DB stores user objects, internal objects, and version stores. If the temp DB 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, 3959, 3967, 3958, 3966 ) indicates temp DB has insufficient space.

Page 25: What is SQL Server Updated

17. How to understand database engine errors? If any error occurs, the server writes error messages to logs (database mail, SQL agent, SQL server and 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.

18. What is severity level in event log? At what severity levels are written to the SQL server log?The severity level tell how bad the error is. Above 19 severity levels errors are written to the SQL server log.

19. What is state Attribute of an error message in event log?The state Attributes provides details of what cause the error.

20. What are the causes of physical server failures? There are five common issues will causes physical server failures.1. Disk failures2. Memory failures3. Processor failures4. Network card failure5. RAID failure.

21. 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. The following tasks will responding T.log file.1. backing up the log2. adding one or more log files3. moving the log to another disks4. increasing log file size or enabling auto growth5. terminating long running transactions

22. 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 file name.

23. if a database is under suspect mode? What you will do?Sp_resetstatus: resets the status of suspect database (sp_resetstatus ’adventureworks’) .

24. if the server has completely failed, and how to all the backups restored on to 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 databasee. If the model database was modified, restore it f. Restore the users databases

INDEXES

25. What is an index? Types of indexes? How many clustered indexes and non-clustered indexes created on a table?

Page 26: What is SQL Server Updated

Generally SQL server examines (table scan) every row in the table to satisfy the query result “index is a physical structure containing pointers to the data which is used for retrieving data more quickly and improves the query performance”.Clustered index: only one clustered index can create on a table. When we create a clustered index on a table, all the rows in the table are stored in the order of the clustered index key.Non clustered index: 249 non-clustered indexes can create on a table.non-clustered indexes are stored B-tree structures with the leaf level nodes having the index key and it’s row locator.

Note:satisfying query result 1.reorganise indexavg_fragmentation_in_percent >5 and <302.alter index reorganize online <=30% select * from sys.dm_db_index_physical_stat3.rebuild the index avg_fragmentation_in_percent >30 4.alter index rebuildoffline >30%

26. How we rebuild an index? By using DBCC DBREINDEX ,dbcc index defrag,dbcc showcontig (or) sys.dm_db_index_phy

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

SL Primary key Unique key

1 Primary kay creates a clustered index Unique key creates a non-clustered index

2 Primary key does not allow Nulls Unique key allows one Null only

28. What is stored procedure?

A stored procedure is a pre-compiled SQL statement that are stored in server database to performing a tasks. A single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version.Advantages: 1. Stored procedure can reduce network traffic because queries executed as a batch.2. Improving the performance because SPs are pre-compiled.3. Stored procedures provide better security to your data 4. Easily modify the SPs when business rules change

29. What is users defined function? Types of UDFs?User-defined functions that allow you to define your own T-SQL function that can accept zero or more parameters and returns a single scalar data value or a table data type . there are 3-types UDFs are available in SQL server 2005.

a. Scalar valid UDFs: a scalar valid UDF accepts parameters returns a single scalar data types (text, ntext, image)b. Table valid UDFs: a table-valid UDF is a function that accepts parameters and returns the results in the form of a

table.30. What are the differences between stored procedures and user defined functions?

sl User defined functions Stored procedures

1 Functions are compiled and executed at runtime Stored procedures are stored in parsed and compiled format in the database

2 Functions can not affect the state of the database which means we cannot perform insert, delete, update and create operations on the databases

Stored procedures can affect the state of the database by using insert, delete, update and create operation

Page 27: What is SQL Server Updated

3 Functions are basically used to compute values. We passes some parameters to functions as input and then it performs some operations on the parameter and return output.

Stored procedures are basically used to process the tasks.

4 Function cannot change server environment and our operating system environment.

Stored procedures can change server environment and our operating system environment.

5 Function cannot be invoked from SQL statements. Execute SELECT

Operating system can be invoked from SQL statements execute SELECT

6 Functions can run an executable file from SQL SELECT or an action query

Operating system use execute or exec to run

31. What is a trigger? What are the trigger models are available in SQL server 2005?A trigger is a set of T-SQL statements stored permanently in the database and automatically fire when event is occurs. They are used to impose user defined restrictions or business rules and also provides high security on database/tables.

There are two types of trigger models available in SQL server 2005.DML triggers: DML triggers created on DML statements like insert, update and delete of database objects.DDL triggers: DDL triggers created on DDL statements like create , alter and drop of DB objects or DB.

32. Types of triggers?There are two types of triggers.1. After Triggers: After triggers will fires after the data is inserted into the table. The typical use for an after triggers is to log the action to an audit or logging table.2. Before triggers: before triggers will fire before the data is inserted into the table. NOTE:DML triggers fire before or after issue, DDL triggers fire after the issue.

33. What is a view and advantage of views?A view is a pre-defined SQL statements that the DB engine executes and retrieves dynamically. A standard view acts as a virtual table based on the result set of SELECT statement. The fields in view are fields from one or more real tables or another view. Advantages: 1. To restrict the users to specific rows & columns and hide the columns with sensitive data.2. User friendly names can be provided instead of base table column names.

34. Types of views? Explain about indexed view?There are two types of views 1) standard views 2) indexed viewsAn indexed view (materialized view) is like standard view, and it has a unique clustered index created on it. It stored physically just like a table.Advantage: indexed views works best for queries that aggregates many rows or have joins that cause response time of the standard view to be slow.

35. What is the difference between local and global temporary tables?Local temporary table: it exists only for the duration of connection or, if defined inside compound statement, for the duration of the compound statement.

Page 28: What is SQL Server Updated

Global temporary table: remains in the database permanently, but the rows exists 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.

36. What is PRIMARY KEY?A primary key constraint is unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity.

37. What is unique constraint?A unique constraint enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.

38. What is foreign key?A foreign key constraint prevents any action that would destroy links between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign key is prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.

39. What is check constraints? 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.

40. What is a 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.

CLUSTERING

1. Active Vs Passive Nodes (Cluster Admin)2. Shared Disk Arrays TKO partitions clustering server Instance. DB’s Quorum3. The Quorum Quorum drives of the stored disk array.

Note: Log file, database logs Records changes made on active node4. Public and private networks. (Cluster name & IP Address)5. The virtual server 6. How a failover works

New features of SQL server SK5 Clustering:

1. 8 nodes 2. 64 bit clustering 3. 1 GB RAM and 20GB free hard disk space4. 2 GB RAM and 50 GB Free hard disk space5. RAID 1, 5, 106. MSDR

Note: CD named: ’70 cluster.lst’ X:/×86/setup directory

Both the nodes of the cluster server instance are physically connected to databases, disk array.

Disk array is shared disk. But only (primary) active node can access the instances databases.

Page 29: What is SQL Server Updated

The shared disk array must have at least two logical partitions. One partition is used for storing. The clustered instance SQL Server database and the other one is used for quorum.

Quorum:

It is stored on the quorum drive of the shared array. Quorum is essentially a log file, similar in concept to database logs. Its purpose is to

record any change made on the active node. Quorum file must read reside on what is called ‘Quorum Drive’.

Quorum drive is a logical drive on the shared array devoted to the function of storing the Quorum.

Making SQL dokin on cluster environment:

Opening CLUADMIN Groups on the left pane

SQL Groups on the left pane select SQL server on right pane take offline.

Public & Private Networks: (Cluster.exe/ Cluster: <Reddy(CL.N)> Resource ‘SQL Server’ offline).

Resource Group: Nodes + Shared disk + Network name + IP Address.

Each node of cluster must have at least two networks cards one network card will be connected to public network and other to private network.

The public network is the network that the SQL server 2005 clients are attached, this is now they communicate to clustered SQL server 2005 instance.

The private network is safely used for communicate b/w the nodes of the cluster. Synchronization & heart beat signal.

Note: (Resource failure) Cluster corruption issues. Cluster disk failure instance down.

Virtual Server: Each SQL server cluster instance is given a virtual name & IP Address. This name once IP address is used by the active node to communicate with clients.

When you create a cluster one of the step is to create cluster name and IP address. This cluster name and IP Address is Used to create communications B/w clients.

To see the errors In cluster log file: open the cluster log (CTRL+F) type the error check recent time stamp, 5-3 days log details are maintained.

C: /Windows/ cluster/dusterlog.logfle.

Cluster LOG: C: /winnt/cluster/clusterlog

Register Entries:

HLKM/ Cluster HIVE. %system root% cluster / clusDB file. HVEY – local machine – cluster – Resource CLUSSVC.EXE system.

How a cluster Failover Works:

Page 30: What is SQL Server Updated

Active node will be communicating with both the databases and the quorum on the shared array.

Active node is sending out heart beat signals over the private network, and passive node is monitoring them to see if they stop. Client is also interacting with active node via virtual name and IP address, running production transactions.

For whatever the reason, the active node stops working because of electricity issue. The passive node which is monitoring the heart beat signals from active node. After a pre determined delay. The passive node assumes the active node, now the active node takes over the control of shared array and reads the quorum, looking for any unsynchronized configuration settings. It also takes control the virtual server name and IP Address.

In addition, as the node takes over the database it has to do SQL Server startup using the databases, just as if it is starting from a shutdown, going through a database recovery.

Note: Do SQL Server setup work, Do SQL server uncluster, check database for instance.

The time is takes depends on many factors, including the speed of the system and the number of transactions that might have to roll forward or back during recovery process. Once the recovery process is completed, the new active node announces itself on the network with virtual name and IP address, which allows client to reconnect and begin using SQL server 2005 instance with minimal interruption.

SQL Server cluster setup & troubleshooting technologies:

What will you do if you don’t see the newly added disks in the SQL cluster setup wizard?What will you do if you don’t see the list of available nodes in SQL Cluster setup Screen?What if SQL cluster setup wizard fails to configure other nodes in cluster?

We must be able to explain the mechanism SQL setup, uses to find the list of nodes, lists of disks and list of interfaces available in cluster and also SQL cluster setup DLL(SQL cluster.DLL) which is responsible to do the initial pre-work for SQL setup wizard. How SQL cluster setup detects that is going to operate in cluster environment.

All the registry entries /SQL modules & files which are important for successful failover and how you can play with these registry entries and files to troubleshoot SQL server.

When SQL server setup, wizard realizes that it is going to operate in a cluster environment, the setup wizard will gave you on option to create SQL server virtual server.

Now we create a SQL Cluster:

After selecting virtual server option, the setup proceed to invoke the SQL cluster modules and performs many tasks in background.

How does SQL setup process detect that is going to operate cluster environment.How SQL setup knocks which files to copy?Which SQL module is responsible for SQL cluster setup and what all basic functions for successful

installation.From where does SQL setup gets lists of disk nodes and interfaces available in the cluster. HLKM/CLUSTER HIVE %system root % cluster / clusDB file

Page 31: What is SQL Server Updated

HKEY – local – machine / cluster / resource

SQL server cluster setup troubleshooting steps.How does SQL server cluster setup configure a second node to be cluster – aware?What all the registry entries are created during the setup and their importance in SQL cluster and

stand alone?What all the SQL cluster modules copied during setup and their importance in SQL cluster.A technique to manually uninstall SQL server instance from cluster( without running SQL

server wizard)

SQL server setup processes & Registry entries:

Three options to install the SQL server database engine

Local computer Remote computer Virtual server

Install SQL server database engine in cluster.

Note: setup wizard doesn’t check the registry of the cluster service at

HLKM\system\current control set\services\clussvc.

It checks clussvc.exe system

How SQL setup knows files to copy:

SQL server cluster setup invokes SQLCLUSTER.DLL from its BINN directory to execute the following functions.

DO SQL cluster setup works: - Installs SQL instance in Cluster.

DO un cluster setup: - uninstall

Check database for instance

SQL setup copies files during setup process setup doesn’t really know which files to copy. It reads a file on the CD named 70 cluster.LST. This files resides at X:\X86\setup directory

Installing failover cluster:

Pre-requisites: 1. SQL server

2. SQL Server Agent

3. FTS full text search service

Page 32: What is SQL Server Updated

The name of the named cluster must be unique to your domain. SQL server only acknowledges virtual IP address created during the installation of SQL server failover cluster.

Common issues are faced after clustering installation:

1. Performing failover form one node to other node.2. If a failover occurs, then finding analysis why specific failover occurred a finding the reasons for

it.3. Any resource failure due to many reasons like: resource hung resource DLL corrupt, service

account issues.

In these issues we need to focus on numerous things like service account permissions issue. Resource resorts.

4. Instance down, which would require traditional trouble shooting and looking into cluster log file to find out what caused the issue.

5. Cluster corruption issues, this might also require to build the entire cluster or may be to troubleshoot occurring

6. Cluster disk failures and ensuring these SAN drives and clustered drives are available.7. Memory configuring issues meaning insufficient memory for the instance participating in

cluster.

SQL SERVER 2005 CLUSTERING:

What is clustering?

Group of independent computer system referred as nodes, working together as unified computing resource. There are 3 types of clustering:

1. Network load balancing. (NLB cluster) – 32 nodes2. Microsoft cluster service (MSCS) – 8 nodes3. Component load balancing (CLB cluster) – 8 nodes.

Network load balancing acts as front end cluster, distributing incoming IP traffic across a cluster of servers. 32 members computers ruiing a member of windows server 2003 family can be connected to share the resource.

Clients N/W load balancing component load cluster service

I/P balancing 32 nodes balancing

Cluster service acts as back and cluster it provides high availability.

Each node has its own memory, system disk, operating system and subset of cluster resources. Microsoft cluster service is based on shared nothing clustering model, nothing is shared in shared nothing. Microsoft cluster service is comprised of three major components:

1. Cluster service2. Resource DLL’s3. Resource monitor

.NET server resource physical disk

Cluster services monitor resource DLL

DISK

Page 33: What is SQL Server Updated

IP address

Resource DLL

Generic application

Resource DLL

Custom resource DLL

Quorum: (contains metadata)

Cluster configuration database. The file named \mscs\quolog.log. the quorum is sometimes refered as quorum log. It tells the cluster which node is active. Its interfaces when communication fails b/w nodes.

The partition that okins the quorum is allowed to continue with the cluster service, the other partition removed from cluster.

Standard quorum & MNS quorum majority node set quorum. Each node has its own locally stored copy of databases.

How clustering works:

Private N/W for internal access and public N/W for client access

Private N/w can be referred as heart beat signal.

IDE & SCSI:

Intelligent/ Integrated drive electronic. IDE is a standard type of connection storage device in a PC. IDE as adopted by ANSI is called ATA( Advanced technology attachment) and implemented in clustering

SCSI:

Creating private n/w & public n/w virtual n/w create.

Virtual disk create fixed size disk.

We need to map quorum shared drive to SCSI drive

Creating cluster user account:

SQL Server 2000 failover clustering:

Hardware: - event logs & computer system report.

Operating system: - operating system error: services failures & disk failures

Networking: - DNS failures; NIC failures.

Security: - server access denied

MSCS: -cluster server reporting issues in eventlog

NETWORK

Cluster unaware application

Cluster aware app

Page 34: What is SQL Server Updated

SQL server: - error logs & event logs

Setup Basics: -

Troubleshooting basics: we will have all these reports in the form of 2 CAB files. Which contains customers event logs.

Review windows event log Review SQL server setup logs Review SQL server cluster log Review server error log Review windows NT cluster Log Test credentials Test connectivity & name resolution.