22 December 2019

Important Question:- SQL-SERVER ARCHITECTURE


3.SQL-SERVER ARCHITECTURE

Q1. Tell me something about the SQL Server Architecture?
SQL Server is divided into two main engines: Relational Engine and Storage Engine.
Relational Engine components: Cmd Parser, Optimizer, Query Executor
Storage Engine components: Access Methods code, Buffer Manager, Transaction Manager
Q2. What is Relational Engine and its Role?
The Relational Engine is also sometimes called the query processor because its primary function is query optimization and execution.
The main responsibilities of the relational engine are:
Parsing the SQL statements.
The parser scans an SQL statement and breaks it down into the logical units, such as keywords, parameters, operators, and identifiers. The parser also breaks down the overall SQL statement into a series of smaller logical operations.
Optimizing the execution plans.
Typically, there are many ways that the server could use data from the source tables to build the result set. The query optimizer determines what these various series of steps are, estimates the cost of each series (primarily in terms of file I/O), and chooses the series of steps that has the lowest cost. It then combines the specific steps with the query tree to produce an optimized execution plan.
Executing the series of logical operations defined in the execution plan.
After the query optimizer has defined the logical operations required to complete a statement, the relational engine steps through these operations in the sequence specified in the optimized execution plan.
Processing Data Definition Language (DDL) and other statements.
These statements are not the typical SELECT, INSERT, UPDATE, or DELETE statements; these statements have special processing needs. Examples are the SET statements to set connection options, and the CREATE statements to create objects in a database.
Formatting results.
The relational engine formats the results returned to the client. The results are formatted as either a traditional, tabular result set or as an XML document. The results are then encapsulated in one or more TDS packets and returned to the application.
Q3. What is Storage Engine and its Role?
The Storage Engine is responsible for managing all I/O to the data. The main responsibilities of the storage engine include:
·         Managing the files on which the database is stored and managing the use of space in the files.
·         Building and reading the physical pages used to store data.
·         Managing the data buffers and all I/O to the physical files.
·         Controlling concurrency. Managing transactions and using locking to control concurrent user access to rows in the database.
·         Logging and recovery.
·         Implementing utility functions such as the BACKUP, RESTORE, and DBCC statements and bulk copy.
Q4.  What is SNI Protocol Layer?
SQL Server Network Interface (SNI) is a protocol layer that establishes the network connection between the client and the server. It consists of a set of APIs that are used by both the database engine and the SQL Server Native Client (SNAC). SQL Server has support for the following protocols:
·         Shared memory
·         TCP/IP
·         Named Pipes
·         VIA — Virtual Interface Adapter
Q5. What are Tabular Data Stream (TDS) Endpoints?
TDS is a Microsoft-proprietary protocol originally designed by Sybase that is used to interact with a database server. Once a connection has been made using a network protocol such as TCP/IP, a link is established to the relevant TDS endpoint that then acts as the communication point between the client and the server.
Q6. What is a Command Parser?
The Command Parser’s role is to handle T-SQL language events. It first checks the syntax and returns any errors back to the protocol layer to send to the client. If the syntax is valid, then the next step is to generate a query plan or find an existing plan. A query plan contains the details about how SQL Server is going to execute a piece of code. It is commonly referred to as an execution plan.
To check for a query plan, the Command Parser generates a hash of the T-SQL and checks it against the plan cache to determine whether a suitable plan already exists. The plan cache is an area in the buffer pool used to cache query plans. If it finds a match, then the plan is read from cache and passed on to the Query Executor for execution. Otherwise an Execution plan is created by the optimizer.
Q7.What is an Execution Plan?
An execution plan is composed of primitive operations. Examples of primitive operations are: reading a table completely, using an index, performing a nested loop or a hash join. All primitive operations have an output: their result set. Some, like the nested loop, have one input. Other, like the hash join, has two inputs. Each input should be connected to the output of another primitive operation. That’s why an execution plan can be sketched as a tree: information flows from leaves to the root.
Q8. What is a Plan Cache?
Plan cache is the part of SQL Server’s buffer pool, is used to store execution plans in case they are needed later when the same type of scripts are submitted by the users.
Q9. What is the role of an Optimizer?
The Optimizer is one of the important assets of a database engine. This is the component on which a particular RDBMS stands off. The primary function of the optimizer is to generate execution plan.
Q10. What is Query Executor?
The Query Executor’s job is self-explanatory; it executes the query. To be more specific, it executes the query plan by working through each step it contains and interacting with the Storage Engine to retrieve or modify data.
Q11. What are Access methods and its roles?
Access Methods is a collection of code that provides the storage structures for your data and indexes, as well as the interface through which data is retrieved and modified. It contains all the code to retrieve data but it doesn’t actually perform the operation itself; it passes the request to the Buffer Manager.
Suppose our SELECT statement needs to read just a few rows that are all on a single page. The Access Methods code will ask the Buffer Manager to retrieve the page so that it can prepare an OLE DB rowset to pass back to the Relational Engine.
Q12. What is a Buffer Manager?
The buffer management component consists of two mechanisms: the buffer manager to access and update database pages, and the buffer cache (also called the buffer pool), to reduce database file I/O.
The Buffer Manager, as its name suggests, manages the buffer pool, which represents the majority of SQL Server’s memory usage. If you need to read some rows from a page, the Buffer Manager checks the data cache in the buffer pool to see if it already has the page cached in memory. If the page is already cached, then the results are passed back to the Access Methods.
If the page isn’t already in cache, then the Buffer Manager gets the page from the database on disk, puts it in the data cache, and passes the results to the Access Methods.
Q13. What is a Buffer pool? What is the importance of Data cache?
Buffer Pool consist of various type of cache like data cache, plan cache, log cache etc. Here data cache is the very important part of buffer pool which is used to store the various types of pages to serve particular query. Suppose if we run a particular select query on a table to show all data rows of that table. Then all the data pages of that table will be required to fulfill the requirement of this query. Here first all data pages will move from disk to buffer pool. This operation of reading data pages from disk to memory is known as physical IO. But if we running the same query again then there is no need to read data pages from disk to buffer pool because all the data pages are already in buffer pool. This operation is known as Logical IO.
Q14. What is the Data cache?
The data cache is usually the largest part of the buffer pool; therefore, it’s the largest memory consumer within SQL Server. It is here that every data page that is read from disk is written to before being used.
The sys.dm_os_buffer_descriptors DMV contains one row for every data page currently held in cache. You can use this script to see how much space each database is using in the data cache:
SELECT count(*)*8/1024 AS 'Cached Size (MB)'  ,CASE database_id  WHEN 32767 THEN 'ResourceDb' ELSE db_name(database_id) END AS 'Database'
FROM sys.dm_os_buffer_descriptors
GROUP BY db_name(database_id),database_id ORDER BY 'Cached Size (MB)' DESC
Q15. What is a Transaction manager and its role?
Transaction Manager interacts with the Access Methods and has two components thorugh which it works on the transactions.

Lock Manager: It is responsible for providing concurrency to the data, and it delivers the configured level of isolation by using locks.
Log Manager: It writes the changes to the transaction log. Writing to the transaction log is the only part of a data modification transaction that always needs a physical write to disk because SQL Server depends on being able to reread that change in the event of system failure
Q16. What is Write Ahead Logging?
At the time a modification is made to a page in the buffer, a log record is built in the log cache recording the modification. This log record must be written to disk before the associated
dirty page is flushed from the buffer cache to disk. SQL Server has logic that prevents a dirty page from being flushed before the associated log record. Because log records are always written ahead of the associated data pages, the process is called a write-ahead logging.
Q17. What are dirty pages?
When a page is read from disk into memory it is regarded as a clean page because it’s exactly the same as its counterpart on the disk. However, once the page has been modified in memory it is marked as a dirty page.
A dirty page is simply a page that has changed in memory since it was loaded from disk and is now different from the on-disk page.
Q18. Which DMV can be used to check how many dirty pages exists in the memory for each database?
SELECT db_name(database_id) AS 'Database',count(page_id) AS 'Dirty Pages' FROM sys.dm_os_buffer_descriptors WHERE is_modified =1 GROUP BY db_name(database_id)ORDER BY count(page_id) DESC
Q19. How is the dirty page written to disk?
Dirty pages are written to disk on the following events.
Lazy writing is a process to move pages containing changes from the buffer onto disk. This clears the buffers for us by other pages.
Checkpoint writes all dirty pages to disk. SQL Server periodically commits a CHECKPOINT to ensure all dirty pages are flushed to disk.
Explicitly issuing a CHECKPOINT will force a checkpoint
Examples of events causing a CHECKPOINT
         net stop mssqlserver
         SHUTDOWN
         ALTER DATABASE adding a file
Eager writing – Nonlogged bcp, SELECT INTO, WRITETEXT,UPDATETEXT,BULK INSERT are examples of non-logged operations. To speed up the tasks , eager writing manages  page creation and page writing in parallel. The requestor does not need to wait for all the page creation to occur prior to  writing pages
Q20. What is a check point?
A checkpoint is a point in time created by the checkpoint process at which SQL Server can be sure that any committed transactions have had all their changes written to disk. This checkpoint then becomes the marker from which database recovery can start. The checkpoint process ensures that any dirty pages associated with a committed transaction are flushed to disk.
Q21. What is the frequency of checkpoint in an ideal scenario?
The Database Engine supports several types of checkpoints: automatic, indirect, manual, and internal. The following table summarizes the types of checkpoints.
a. Automatic
Transact-SQL Interface
EXEC sp_configure'recovery interval','seconds'
Description: Issued automatically in the background to meet the upper time limit suggested by the recovery interval server configuration option. Automatic checkpoints run to completion. Automatic checkpoints are throttled based on the number of outstanding writes and whether the Database Engine detects an increase in write latency above 20 milliseconds.
b. Indirect
Transact-SQL Interface
ALTER DATABASE … SET TARGET_RECOVERY_TIME =target_recovery_time{ SECONDS | MINUTES }
Description Issued in the background to meet a user-specified target recovery time for a given database. The default target recovery time is 0, which causes automatic checkpoint heuristics to be used on the database. If you have used ALTER DATABASE to set TARGET_RECOVERY_TIME to >0, this value is used, rather than the recovery interval specified for the server instance.
c. Manual
Transact-SQL Interface
CHECKPOINT [ checkpoint_duration ]
Description Issued when you execute a Transact-SQL CHECKPOINT command. The manual checkpoint occurs in the current database for your connection. By default, manual checkpoints run to completion. Throttling works the same way as for automatic checkpoints. Optionally, the checkpoint_duration parameter specifies a requested amount of time, in seconds, for the checkpoint to complete.
d. Internal
Transact-SQL Interface
None.
Description Issued by various server operations such as backup and database-snapshot creation to guarantee that disk images match the current state of the log.
 22. What is LazyWriter?
Lazywriter also flushes dirty pages to disk. SQL Server constantly monitors memory usage to assess resource contention (or availability); It’s job is to make sure that there is a certain amount of free space available at all times. As part of this process, when it notices any such resource contention, it triggers LazyWriter to free up some pages in memory by writing out dirty pages to disk. It employs Least Recently Used (LRU) algorithm to decide which pages are to be flushed to the disk.
23. What is log flush?
Log Flush also writes pages to disk. The difference here is that it writes pages from Log Cache into the Transactional log file (LDF). Once a transaction completes, LogFlush writes those pages (from Log Cache) to LDF file on disk.
Each and every transaction that results in data page changes, also incurs some Log Cache changes. At the end of each transaction (commit), these changes from Log Cache are flushed down to the physical file (LDF).
24. What is the difference between check point lazy writer?
Checkpoint
Lazy writer
Checkpoint is used by sql engine to keep database recovery time in check
Lazy writer is used by SQL engine only to make sure there is enough memory left in sql buffer pool to accommodate new pages
Check point always mark entry in T-log before it executes either sql engine or manually
Lazy writer doesn’t mark any entry in T-log
To check occurrence of checkpoint , we can use below queryselect * from ::fn_dblog(null,null) WHERE [Operation] like ‘%CKPT’
To check occurrence of lazy writer we can use performance monitor
SQL Server Buffer Manager Lazy writes/sec
Checkpoint only check if page is dirty or not
Lazy writer clears any page from memory when it satisfies all of 3 conditions. 1.Memory is required by any object and available memory is full
2.Cost factor of page is zero
3.Page is not currently reference by any connection
Checkpoint is affected by two parameters
1.Checkpoint duration: is how long the checkpoint can run for.
2.Recovery interval: affects how often it runs.
Lazy writer is affected by
1.Memory pressure
2.Reference counter of page in memory
Check point should not be very low , it can cause increasing recovery time of database
No. of times lazy writer is executing per second should always be low else it will show memory pressure
Checkpoint will run as per defined frequency
No memory pressure, no lazy writer
Checkpoint tries to write as many pages as fast as possible
Lazy writer tries to write as few as necessary
checkpoint process does not put the buffer page back on the free list
Lazy writer scans the buffer cache and reclaim unused pages and put it n free list
We can find last run entry of checkpoint in Boot page
Lazy writer doesn’t update boot page
Checkpoint can be executed by user manually or by SQL engine
Lazy writer cant be controlled by user
It keeps no. of dirty pages in memory to minimum
It helps to reduce paging
Auto frequency can be controlled using recovery interval in sp_configure
Works only @ memory pressure , It uses clock algorithm for cleaning buffer cache
It will be automatically executed before every sql statement which requires consistent view of database to perform task like (Alter, backup, checkdb, snapshot …..)
It kicks pages out of memory when reference counter of page reaches to zero
Command : Checkpoint
No command available
It comes in picture to find min lsn whenever t-log truncates
No entry in T-log
Checkpoint is affected by Database recovery model
Lazy writer doesn’t get impacted with recovery model of database
To get checkpoint entry in error log DBCC TRACEON(3502, -1)
Not Applied
Members of the SYSADMIN, DB_OWNER and DB_BACKUPOPERATOR can execute checkpoint manually
Not Applied
25. What are ghost records in SQL server?
When a record is deleted from a clustered index data page or non-clustered index leaf page or a versioned heap page or a forwarded record is recalled, the record is logically removed by marking them as deleted but not physically removed from the page immediately. Pages which are marked as deleted but actually not deleted physically are called Ghost Records.
26. Which process removes the records which are marked as Ghost Records?
Ghostcleanuptask: SQL Server Ghostcleanuptask thread physically removes the records which are marked as deleted.
27. How Ghost cleanup task works?
Ghostcleanuptask thread wakes up every 10 seconds.
Sweepdatabases one by one starting from master.
Skip the database if it is not able to take ashared lock for database (LCK_M_S) or database is not in Open read/write state.
Scans the PFS pages of the current database to get the pages which has ghost records.
PFS Page:A PFS page occurs once in 8088 pages. SSQL Server will attempt to place a PFS page on the first page of every PFS interval(8088Pages). The only time a PFS page is not the first page in its interval is in the first interval for a file.
In this case, the file header page is first, and the PFS page is second. (Page ID starts from 0 so the first PFS page is at Page ID 1)
Remove the records which are marked as deleted (ghosted) physically
28. What is the different protocol supported by SQL server, explain each of these?
Shared memory — Simple and fast, shared memory is the default protocol used to connect from a client running on the same computer as SQL Server. It can only be used locally, has no configurable properties, and is always tried first when connecting from the local machine.
TCP/IP — This is the most commonly used access protocol for SQL Server. It enables you to connect to SQL Server by specifying an IP address and a port number. Typically, this happens automatically when you specify an instance to connect to. Your internal name resolution system resolves the hostname part of the instance name to an IP address, and either you connect to the default TCP port number 1433 for default instances or the SQL Browser service will find the right port for a named instance using UDP port 1434.
Named Pipes — TCP/IP and Named Pipes are comparable protocols in the architectures in which they can be used. Named Pipes was developed for local area networks (LANs) but it can be inefficient across slower networks such as wide area networks (WANs).
VIA — Virtual Interface Adapter is a protocol that enables high-performance communications between two systems. It requires specialized hardware at both ends and a dedicated connection.
29. What is HOT ADD CPU term in SQL server?
‘Hot ADD’ means being able to plug in a CPU while the machine is running and then reconfigure SQL Server to make use of the CPU ONLINE! (i.e. no application downtime required at all)
There are a few restrictions:
Need a 64-bit system that support hot-add CPU (obviously :-))
Need Enterprise Edition of SQL Server 2008
Need Windows Server Datacenter or Enterprise Edition
30. What is MaxDOP term in SQL server?
When SQL Server runs on a computer with more than one processor or CPU, it detects the best degree of parallelism that is the number of processors employed to run a single statement, for each query that has a parallel execution plan. You can use the max degree of parallelism option to limit the number of processors to use for parallel plan execution and to prevent run-away queries from impacting SQL Server performance by using all available CPUs.
Q. What is a Batch, Task, Windows Thread, Fiber, Worker Thread  in SQL Server OS architecture?
Batch
An SQL batch is a set of one or more Transact-SQL statements sent from a client to an instance of SQL Server for execution. It represents a unit of work submitted to the Database Engine by users.
Task
A task represents a unit of work that is scheduled by SQL server. A batch can map to one or more tasks. For example, a parallel query will be executed by multiple tasks.
Windows Thread
A windows thread represents an independent execution mechanism.
Fiber
A fiber is lightweight thread that queries fewer resources than a windows thread and can switch context when in user mode. One Windows thread can be mapped to many fibers.
Worker Thread
The worker thread represents a logical thread in SQL Server that is internally mapped (1:1) to either a windows thread or, if lightweight pooling is turned ON, to a fiber. The mapping is maintained until worker thread is deallocated either because of memory pressure, or if it has been idle for long time. The association task to a worker thread is maintained for the life of the task.

12 December 2019

Important Questions-INSTALLATION

INSTALLATION
Q1. Where will you find the SQL Server installation related logs?
Installation related logs are stored under the shared feature directory folder which was selected at the time of first SQL Server instance installation.
C:\programfiles\Microsoft SQL Server\110\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\
Q2. What is “ConfigurationFile.ini” file?
SQL Server Setup generates a configuration file named ConfigurationFile.ini, based upon the system default and run-time inputs.
The ConfigurationFile.ini file is a text file which contains the set of parameters in name/value pairs along with descriptive comments.
Q3. What is the location of ConfigurationFile.ini file?
C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\Log folder.
Q4. What is a service account?
Based on the selected components while doing the installation we will find respective service to each component in the Windows Services. e.g. SQL Server, SQL Server Agent, SQL Analysis Services, SQL Server integration Services etc. There will be a user for each and every service through which each service will run. That use is called Service Account of that service.
Mainly we categorize the Service account as below:
Local User Account: This user account is created in the server where SQL Server is installed; this account does not have access to network resources.
Local Service Account: This is a builtin windows account that is available for configuring services in windows.
This account has permissions as same as accounts that are in the users group, thus it has limited access to the resources in the server.
Local System Account: This is a builtin windows account that is available for configuring services in windows.
This is a highly privileged account that has access to all resources in the server with administrator rights.
Network Service Account: This is a builtin windows account that is available for configuring services in windows.
This has permissions to access resources in the network under the computer account.
Domain Account: This account is a part of our domain that has access to network resources for which it is intended to have permission. It is always advised to run SQL Server and related services under a domain account with minimum privilege need to run SQL Server and its related services.
Q5 . What are Shared Features Directory and its usages?
This directory contains the common files used by all instances on a single computer e.g. SSMS, sqlcmd, bcp, DTExec etc.
These are installed in the folder <drive>:\Program Files\Microsoft SQL Server\110\ , where <drive> is the drive letter where components are installed. The default is usually drive C.
Q6. What is an Instance?
An instance of the Database Engine is a copy of the sqlservr.exe executable that runs as an operating system service.
Each instance manages its own system databases and one or more user databases. An instance is a complete copy of an SQL Server installation.
Q7. Type of Instance and maximum no. of instances which can be installed on a server.
There are two types of Instances.
Default instance
Named Instance
Each computer can run maximum of 50 instances of the Database Engine.  One instance can be the default instance.
A connection request must specify both the computer name and instance name in order to connect to the instance.
Q8. What is a collation and what is the default collation?
Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence,
with options for specifying case-sensitivity, accent marks, kana character types and character width.
Default collation:  SQL_Latin1_General_CP1_CI_AS
Q9. What is an RTM setup of SQL Server?
RTM stands for release to manufacturing.
Q10. What is a Service Pack, Patch, Hot fix and its difference?
Service Pack is abbreviated as SP, a service pack is a collection of updates and fixes, called patches, for an operating system or a software program.
Many of these patches are often released before the larger service pack, but the service pack allows for an easy, single installation.
Patch – Publicly released update to fix a known bug/issue
Hotfix – update to fix a very specific issue, not always publicly released
Q11. What’s the practical approach of installing Service Pack?
Steps to install Service pack in Production environments:
First of all raise a change order and get the necessary approvals for the downtime window. Normally it takes around 45-60 minutes to install Service pack if there are no issues.
Once the downtime window is started, take a full backup of the user databases and system databases including the Resource database.
List down all the Startup parameters, Memory Usage, CPU Usage etc and save it in a separate file.
Install the service pack on SQL Servers.
Verify all the SQL Services are up and running as expected.
Validate the application functionality.
Note: There is a different approach to install Service pack on SQL Server cluster instances. That will be covered in SQL Server cluster.
Q12. What is a slip stream installation and its usages?
SQL Server 2008 introduced a concept that’s called “Slipstream Installation”. This is a way to deploy a SQL Server instance with all the needed Service pack as part of the installation.
 Everything will be installed in one go, hence there is no need to deploy any other service packs on the installation.
Q13. What is a silent installation and how can we use this feature?
The procedure to install SQL Server instance through command line using ConfigurationFile.ini file in Quite mode is known as Silent installation.
Q14. What is the default port of a SQL Server instance? 1433
Q15. Can we change the default port of SQL Server, How?
Yes, it is possible to change the Default port on which SQL Server is listening.
Step 1. Go to SQL Server Configuration Manager > SQL Server Network Configuration >Protocols for <Instance Name>
Step 2. Right Click on TCP/IP and select Properties
Step 3. In TCP/IP Properties dialog box, go to IP Addresses tab and scroll down to IPAllgroup. Now change the value to static value which you want to set for SQL Server port.
Q15. How to get the port number where the SQL Server instance is listening?
Below are the methods using which we can get the port information.
Method 1: SQL Server Configuration Manager (TCP/IP Properties)
Method 2: Windows Event Viewer-Event ID 26022
Method 3: SQL Server Error Logs 
(EXEC xp_readerrorlog 0, 1, N'Server is listening on', 'any', NULL, NULL, N'asc')
 Method 4: sys.dm_exec_connections DMV
(select distinct local_net_address, local_tcp_port from sys.dm_exec_connections)
Method 5: Reading registry using xp_instance_regread
Q16. What is a Filestream?
FILESTREAM was introduced in SQL Server 2008 for the storage and management of unstructured data. The FILESTREAM feature allows storing BLOB data (example: word documents, image files, music and videos etc) in the NT file system and ensures transactional consistency between the unstructured data stored in the NT file system and the structured data stored in the table.
Q17. What’s the location of SQL Server log files?
Instance Root Directory\MSSQL\Log
Q18. How many SQL Server log files can be retained in the SQL Server error logs be default?
By default, there are seven SQL Server error logs; Errorlog and Errorlog.1 through Errorlog.6. The name of the current, most recent log is Errorlog with no extension.
The log is re-created every time that you restart SQL Server. When the Errorlog file is re-created, the previous log is renamed to Errorlog.1, and the next previous log (Errorlog.1) is renamed to Errorlog.2, and so on. Errorlog.6 is deleted.
Q19. Is it possible to increase the retention of Error log files and How?
Yes , Open SQL Server Management Studio and then connect to SQL Server Instance. In Object Explorer, Expand Management Node and then right click SQL Server Logs and click Configure as shown in the snippet below.
In Configure SQL Server Error Logs window you can enter the value between 6 and 99 for the number of error logs and click OK to save the changes.

Important Questions-SECURITY PERMISSIONS


SECURITY PERMISSIONS
Q1. What is Authentication and Authorization? What is the difference between both?
Authentication is the process of verifying who you are. Logging on to a PC with a username and password is authentication.
Authorization is the process of verifying that you have access to something. Authorization is gaining access to a resource (e.g. directory on a hard disk) because the permissions configured on it allow you to access it.
Q2. How many type of SQL Server authentication mode supported by SQL Server 2012?
There are two type of authentication available in SQL Server.
Windows Authentication — TRUSTED connection
Windows Logins, Windows Groups
MIXED authentication — NON Trusted connection
Windows Logins, Windows Groups, SQL Server logins
Q3. What’s the difference between Windows and Mixed mode?
Windows authentication mode requires users to provide a valid Windows username and password to access the database server. i.e. Active Directory domain credentials.
Mixed authentication mode allows the use of Windows credentials but supplements them with local SQL Server user accounts that the administrator may create and maintain within SQL Server
Q4. Being DBA which authentication mode you will prefer if you are asked to give an advice for a new Application?
Windows authentication is definitely more secure as it’s controlled and authenticated by Active Directory policies.
Q5. What are Principals?
Principals are entities that can request SQL Server resources. A Windows Login is an example of an indivisible principal, and a Windows Group is an example of a principal that is a collection.
Every principal has a security identifier (SID). e.g.
Windows-level principals
• Windows Domain Login
• Windows Local Login
SQL Server-level principals
• SQL Server Login
• Server Role
Database-level principals
• Database User
• Database Role
• Application Role
Q6. What is a Securable?
Securables are the resources to which the SQL Server Database Engine authorization system regulates access. For example, a table is a securable. Some securables can be contained within others, creating nested hierarchies called “scopes” that can themselves be secured. The securable scopes are server, database, and schema.
Q7. Explain scope of securable on Server, Database and Schema level?
Securable scope: Server
         Endpoint
         Login
         Server role
         Database
Securable scope: Database
         User
         Database role
         Application role
         Assembly
         Message type
         Route
         Service
         Remote Service Binding
         Full text catalog
         Certificate
         Asymmetric key
         Symmetric key
         Contract
         Schema
Securable scope: Schema —The schema securable scope contains the following securables:
         Type
         XML schema collection
         Object – The object class has the following members:
·         Aggregate
·         Function
·         Procedure
·         Queue
·         Synonym
·         Table
·         View

Q8. What are logins and users and its difference?
A login is the principal that is used to connect to the SQL Server instance. A user is the principal that is used to connect to a database.
The security context on the instance itself is dictated by the login, it’s roles and the permissions granted/denied. The security context on the database is dictated by the user,
it’s roles and the permissions granted/denied.
Q9. What is a schema?
SQL Server 2005 introduced the concept of database schemas and the separation between database objects and ownership by users. An object owned by a database user is no longer tied to that user.
The object now belongs to a schema – a container that can hold many database objects. schema as a collection of database objects that are owned by a single principal and form a single namespace
Q10. What are Fixed Server roles and importance?
1.Bulk Admin: perform Bulk Insert operations on all the databases.
2.DBCreator: Create/Alter/Drop/Restore a database.
3.Disk Admin: Members can manage disk files for the server and all databases. They can handle backup devices.
4.Process Admin: manage and terminate the processes on the SQL Server.
5.Server Admin: change Server-wide configurations and shutdown SQL Server instance.
6.Setup Admin: Members of this role can Add/Remove Linked Servers.
7.Security Admin: manage Logins, including changing and resetting passwords as needed, and managing GRANT, REVOKE and DENY permissions at the server and database levels.
8.SysAdmin: Full Control on the instance and can perform any task.
9.Public: Public is another role just like Fixed Server Roles, that is by default granted to every login (Windows/SQL)
Q11. What are “View Server State”,”VIEW DATABASE STATE” permissions meant for?
Dynamic management views and functions return server state information that can be used to monitor the health of a server instance, diagnose problems, and tune performance.
There are two types of dynamic management views and functions:
Server-scoped dynamic management views and functions. These require VIEW SERVER STATE permission on the server.
Database-scoped dynamic management views and functions. These require VIEW DATABASE STATE permission on the database.
Q12. What are “View Definition” permissions?
The VIEW DEFINITION permission lets a user see the metadata of the securable on which the permission is granted. However, VIEW DEFINITION permission does not confer access to the securable itself. For example, a user that is granted only VIEW DEFINITION permission on a table can see metadata related to the table in the sys.objects catalog view. However, without additional permissions such as SELECT or CONTROL, the user cannot read data from the table.
The VIEW DEFINITION permission can be granted on the following levels:
         Server scope
         Database scope
         Schema scope
         Individual entities
Q13. What is a guest account?
Guest user permits access to a database for any logins that are not mapped to a specific database user. The guest user cannot be dropped but it can be disabled by revoking the CONNECT permission. The recommendation is not valid for master, msdb and tempdb system databases. If Guest user is disabled in msdb system database, it may cause some issues. Distribution database is also system database and more information about the Guest User in distribution database can be found below. It is recommended to disable guest user in every database as a best practice for securing the SQL Server.
Q14. Is it possible to create new User Defined Server role in 2012 or not? Yes
Q15. What are the security related catalog views?
Server-Level Views
         sys.server_permissions
         sys.sql_logins
         sys.server_principals
         sys.server_role_members
Database-Level Views
         sys.database_permissions
         sys.database_role_members
         sys.database_principals
Q16. What are the extra DB roles available in msdb?
SQL Server 2005 introduced the following msdb database fixed database roles, which give administrators finer control over access to SQL Server Agent.
         SQLAgentUserRole- least
         SQLAgentReaderRole
         SQLAgentOperatorRole- most privileged
SQLAgentOperatorRole includes all the permissions of SQLAgentUserRole and SQLAgentReaderRole. Members of this role can also view properties for operators and proxies, and enumerate available proxies and alerts on the serve.
Q17. What are Fixed Database Roles?
1.db_datareader: has the ability to run a SELECT statement against any table or view in the database.
2.db_datawriter: has the ability to modify via INSERT, UPDATE, or DELETE data in any table or view in the database.
3.db_denydatareader: role is the exact opposite of the db_datareader role: instead of granting SELECT permissions on any database object, the db_denydatareader denies SELECT permissions.
4.db_denydatawriter: serves to restrict permissions on a given database. With this role, the user is preventing from modifying the data on any data via an INSERT, UPDATE, or DELETE statement
5.db_accessadmin: has the ability to add and remove users to the database.
The db_accessadmin role does not, however, have the ability to create or remove database roles, nor does it have the ability to manage permissions.
Granted with GRANT option: CONNECT
6.db_securityadmin: has rights to handle all permissions within a database. The full list is:
DENY, GRANT, REVOKE, sp_addapprole, sp_addgroup, sp_addrole, sp_addrolemember, sp_approlepassword, sp_changegroup, sp_changeobjectowner, sp_dropapprole, sp_dropgroup, sp_droprole, sp_droprolemember
The list includes the DENY, GRANT, and REVOKE commands along with all the store procedures for managing roles.
7.db_ddladmin: A user with the db_ddladmin fixed database role has rights to issue Data Definition Language (DDL) statements in order to CREATE, DROP, or ALTER objects in the database.
8.db_backupoperator: has rights to create backups of a database. Restore permissions are not granted, but only backups can be performed.
9.db_owner: Equal to a sysadmin at instance level, DB_OWNER can perform any task at DB Level.
10.public: By default all the users in database level are granted Public Role.
 Q18. What are Application Roles?
An application role is a database principal that enables an application to run with its own, user-like permissions. You can use application roles to enable access to specific data to only those users who connect through a particular application. Unlike database roles, application roles contain no members and are inactive by default. Application roles work with both authentication modes. Application roles are enabled by using sp_setapprole, which requires a password. Because application roles are a database-level principal, they can access other databases only through permissions granted in those databases to guest. Therefore, any database in which guest has been disabled will be inaccessible to application roles in other databases.
Q19. What are Orphaned Users?
A database user for which the corresponding SQL Server login is undefined or is incorrectly defined on a server instance cannot log in to the instance.
         A database user can become orphaned if the corresponding SQL Server login is dropped.
         A database user can become orphaned after a database is restored or attached to a different instance of SQL Server.
         Orphaning can happen if the database user is mapped to a SID that is not present in the new server instance.
Q20. How to troubleshoot issues with the Orphaned users?
This will lists the orphaned users:    EXEC sp_change_users_login 'Report'
If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'
If you want to create a new login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
 Q21. How can SQL Server instances be hidden?
To hide an instance of the SQL Server Database Engine
1. In SQL Server Configuration Manager, expand SQL Server Network Configuration, right-clickProtocols for , and then selectProperties.
2. On the Flags tab, in the HideInstance box, select Yes, and then click OK to close the dialog box. The change takes effect immediately for new connections.
Q22. Being a DBA what all measures you will follow to make SQL SERVER more secure?
         When possible, use Windows Authentication logins instead of SQL Server logins
         Using server, database and application roles to control access to the data
         Using an un guessable SA password
         If possible, disable and rename the sa account
         Restricting physical access to the SQL Server
         Disabling the Guest account
         Minimize the number of sysadmins allowed to access SQL Server.
         Give users the least amount of permissions they need to perform their job.
         Use stored procedures or views to allow users to access data instead of letting them directly access tables.
         Don’t grant permissions to the public database role.
         Remove user login IDs who no longer need access to SQL Server.
         Avoid creating network shares on any SQL Server.
         Turn on login auditing so you can see who has succeeded, and failed, to login.
         Ensure that your SQL Servers are behind a firewall and are not exposed directly to the Internet.
         Do not use DBO users as application logins
         Firewall restrictions ensure that only the SQL Server listening port is available on the database server.
         Apply the latest security updates / patches
Q23. What is Transparent Data Encryption?
Transparent Data Encryption (TDE) is a feature introduced in SQL Server 2008 and available in later versions for bulk encryption at the database file level (data file, log file and backup file) i.e. the entire database at rest. Once enabled for a database, this feature encrypts data into pages before it is written to the disk and decrypts when read from the disk. The best part of this feature is, as its name implies, it’s completely transparent to your application. This means literally no application code changes (only administrative change to enable it for a database) are required and hence no impact on the application code\functionalities when enabling TDE on a database being referenced by that application.
Q24. What is Service master key?
The Service Master Key is the root of the SQL Server encryption hierarchy. It is generated automatically the first time it is needed to encrypt another key. By default, the Service Master Key is encrypted using the Windows data protection API and using the local machine key. The Service Master Key can only be opened by the Windows service account under which it was created or by a principal with access to both the service account name and its password.
Q25. What are the types of keys used in encryption?
Symmetric Key – In Symmetric cryptography system, the sender and the receiver of a message share a single, common key that is used to encrypt and decrypt the message. This is relatively easy to implement, and both the sender and the receiver can encrypt or decrypt the messages.
Asymmetric Key – Asymmetric cryptography, also known as Public-key cryptography, is a system in which the sender and the receiver of a message have a pair of cryptographic keys – a public key and a private key – to encrypt and decrypt the message. This is a relatively complex system where the sender can use his key to encrypt the message but he cannot decrypt it. The receiver, on the other hand, can use his key to decrypt the message but he cannot encrypt it. This intricacy has turned it into a resource-intensive process.
Q26. How to take backup of the Service master key?
 BACKUP SERVICE MASTER KEY TO FILE = 'path_to_file'
 ENCRYPTION BY PASSWORD = 'password'
Q27. Is it possible to disable SA, how?
Disabling the SA account is a good option to prevent its use. When it is disabled no one can use it in any circumstance until it is enabled. The only disadvantage is that we can’t use the SA account in an emergency.
T-SQL to disable SA account.   ALTER LOGIN sa DISABLE;
Q28. Is it possible to Rename the SA Login
Yes we can rename the SA account which will prevent hackers/users to some extent.
Query to check account status:   ALTER LOGIN sa WITH NAME = [newname];
Q29. Define SQL Server Surface Area Configuration Tool
SQL Server 2005 contains configuration tools such as a system stored procedure calledsp_configure or SQL Server Surface Area Configuration tool (for services and features) in order to enable/disable optional features as needed. Those features are usually installed as disabled by default. Here is the list of the features that can be enabled using the tool:
         xp_cmdshell
         SQL Server Web Assistant
         CLR Integration
         Ad hoc remote queries (the OPENROWSET and OPENDATASOURCE functions)
         OLE Automation system procedures
         System procedures for Database Mail and SQL Mail
         Remote use of a dedicated administrator connection

Resource Governor

Resource Governor  is a feature that you can use to manage SQL Server workload and system resource consumption. Resource Governor enables y...