Friday, October 7, 2022

Config SQL instances using powershell -- TempDB, Port and Services

 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12



Import-Module -Name SqlServer



function ConfigureSQLPorts()


{


    Param

    

    (

        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$SQLInstance,

        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Instance_Id,

        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Port


    )


$MachineObject = new-object ('Microsoft.SqlServer.Management.Smo.WMI.ManagedComputer')


$ProtocolUri = "ManagedComputer[@Name='" + (get-item env:computername).Value + "']/ServerInstance[@Name='$Instance_Id']/ServerProtocol"


$tcp = $MachineObject.getsmoobject($ProtocolUri + "[@Name='Tcp']")


$np = $MachineObject.getsmoobject($ProtocolUri + "[@Name='Np']")


$sm = $MachineObject.getsmoobject($ProtocolUri + "[@Name='Sm']")


$np.IsEnabled = $true


$np.alter()


$tcp.IsEnabled = $true


$tcp.alter()


$sm.IsEnabled=$true

$sm.alter()


$MachineObject.getsmoobject($tcp.urn.Value + "/IPAddress[@Name='IPAll']").IPAddressProperties[1].Value = "$Port"


$tcp.alter()



}


function ConfigSQLServices()


{  

    Param

    

    (

        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$SQLInstance,

        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Instance_Id


    )     

Write-Host "Configure SQL Server & SQL Agent Service Fault Tolerance Properties"

$ServiceName="MSSQL`$$Instance_Id"

[string] $action1 = "restart"

[int] $time1 =  100000         

[string] $action2 = "restart"

[int] $time2 =  100000 

[string] $actionLast = "restart"

[int] $resetCounter = 86400 

sc.exe config $ServiceName start= delayed-auto

   $action = $action1+"/"+$time1+"/"+$action2+"/"+$time2

sc.exe  failure $ServiceName actions= $action reset= $resetCounter


$ServiceName="SQLAgent`$$Instance_Id"

[string] $action1 = "restart"

[int] $time1 =  200000         

[string] $action2 = "restart"

[int] $time2 =  200000 

[string] $actionLast = "restart"

[int] $resetCounter = 86400 

sc.exe config $ServiceName start= delayed-auto

   $action = $action1+"/"+$time1+"/"+$action2+"/"+$time2

sc.exe  failure $ServiceName actions= $action reset= $resetCounter


}


function Optimize-TempDBSize


{

    Param

    (

        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$SQLInstance,

        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Instance_Id,

        [Parameter(Mandatory=$true,ValueFromPipeline=$true)][int]$SQLInstance_Count


    )

    

               

        $TempDB_FIlePath="Z:\"+$Instance_Id+"\MSSQL\TempDB\"

        

        New-Item -ItemType Directory -Path $TempDB_FIlePath -Force -ErrorAction Stop |Out-Null      

    

        $property = 'NumberOfLogicalProcessors'

    

        $NumberOfLogicalProcessors=Get-WmiObject -class win32_processor -Property  NumberOfLogicalProcessors |Select-Object -ExpandProperty NumberOfLogicalProcessors 

    

        Write-Host "Total Number Of Logical Processsors : $NumberOfLogicalProcessors" 

    

        $tempSize=Get-WmiObject -class win32_logicaldisk|Where-Object {$_.DeviceID -eq 'Z:'}|Select-Object -ExpandProperty Size

    

        $DiskSize=[math]::round($tempSize/1GB)

    

        Write-Host "Total Disk Space Available In GB On Z Drive : $DiskSize" 

    

        [bigint]$TagetDiskSizeUsage=0.9*$DiskSize

    

        $TagetDiskSizeUsage=$TagetDiskSizeUsage/$SQLInstance_Count

    

        Write-Host "Disk Space available for TempDB Use for the SQL Instance $SQLInstance : $TagetDiskSizeUsage" 


        [int]$NoOfDataFiles=0

        [int]$DataFileSize=0

    

        if($NumberOfLogicalProcessors -lt 4)

        

            {

        

                $NoOfDataFiles=4

                

                $DataFileSize=$TagetDiskSizeUsage/$NoOfDataFiles

                }

    

    else

        {

        $NoOfDataFiles=8

        $DataFileSize=$TagetDiskSizeUsage/$NoOfDataFiles       

    }

    #if($NumberOfLogicalProcessors -ge 8 )

    #{

       # $NoOfDataFiles=16

       # $DataFileSize=$TagetDiskSizeUsage/$NoOfDataFiles

        

    #}

    Write-Host "Total Number of TempDB Data Files to be Created : $NoOfDataFiles" 

    Write-Host "Size of each TempDB Data File : $DataFileSize" 

    $FIleSize=$DataFileSize.ToString()

    $FIleSize=$FIleSize+'GB'

    $query_TempDBFile="select name,physical_name,size/128 as Size_In_MB from sys.master_files where type=0 and database_id=db_id('tempdb')"

    $result_TempDBFile=Invoke-Sqlcmd -ServerInstance $SQLInstance -Database master -Query $query_TempDBFile

    $Optimize_TempDBSize=""

    foreach($tempdbFile in $result_TempDBFile)

        {

               $Name=$tempdbFile.Name

               $tempDB_Query="

               USE master

               

               ALTER DATABASE [tempdb] MODIFY FILE ( NAME = N'$Name', SIZE = $FIleSize )

               `n"

               $Optimize_TempDBSize=$Optimize_TempDBSize+$tempDB_Query


        }


    for($i = $result_TempDBFile.Count+1; $i -le ($NoOfDataFiles-1); $i++)

        { 

            $LogicalName='tempdev'+$i

            $PhysicalFile=$TempDB_FIlePath+$LogicalName+'.ndf'

    $tempDB_Query="

               ALTER DATABASE [tempdb] ADD FILE ( NAME = N'$LogicalName', FILENAME = N'$PhysicalFile' , SIZE = $FIleSize , FILEGROWTH = 0)

               `n"  

               $Optimize_TempDBSize=$Optimize_TempDBSize+$tempDB_Query

        }

     Write-Host "Optimize TempDB T-SQL Script to be Applied is  : $Optimize_TempDBSize" 


    Invoke-Sqlcmd -ServerInstance $SQLInstance -Database master -Query $Optimize_TempDBSize


}



try


    {

    

        $SQLInstance=Read-Host -Prompt "SQL Instance Name :"


        $Instance_Id=Read-Host -Prompt "SQL Instance ID :"


        $SQLInstance_Count=Read-Host -Prompt "SQL Instance Count :"


        [string]$Port=Read-Host -Prompt "SQL Port Number :"

        

        Optimize-TempDBSize -SQLInstance $SQLInstance -Instance_Id $Instance_Id -SQLInstance_Count $SQLInstance_Count


        ConfigureSQLPorts -SQLInstance $SQLInstance -Instance_Id $Instance_Id -Port $Port


        ConfigSQLServices -SQLInstance $SQLInstance -Instance_Id $Instance_Id 




    }


catch


    {

            $ErrorMessage = $_.Exception.Message

            $FailedItem = $_.Exception.ItemName

            Write-Host $ErrorMessage

            Write-Host $FailedItem

    }


Thursday, February 10, 2022

Find Currently running query with all details in SQL server

SELECT s.session_id

    ,r.STATUS

    ,r.blocking_session_id AS 'blocked_by'

    ,r.wait_type

    ,r.wait_resource

    ,CONVERT(VARCHAR, DATEADD(ms, r.wait_time, 0), 8) AS 'wait_time'

    ,r.cpu_time

    ,r.logical_reads

    ,r.reads

    ,r.writes

    ,CONVERT(VARCHAR, DATEADD(ms, r.total_elapsed_time, 0), 8) AS 'elapsed_time'

    ,CAST((

            '<?query --  ' + CHAR(13) + CHAR(13) + Substring(st.TEXT, (r.statement_start_offset / 2) + 1, (

                    (

                        CASE r.statement_end_offset

                            WHEN - 1

                                THEN Datalength(st.TEXT)

                            ELSE r.statement_end_offset

                            END - r.statement_start_offset

                        ) / 2

                    ) + 1) + CHAR(13) + CHAR(13) + '--?>'

            ) AS XML) AS 'query_text'

    ,COALESCE(QUOTENAME(DB_NAME(st.dbid)) + N'.' + QUOTENAME(OBJECT_SCHEMA_NAME(st.objectid, st.dbid)) + N'.' + QUOTENAME(OBJECT_NAME(st.objectid, st.dbid)), '') AS 'stored_proc'

    --,qp.query_plan AS 'xml_plan'  -- uncomment (1) if you want to see plan

    ,r.command

    ,s.login_name

    ,s.host_name

    ,s.program_name

    ,s.host_process_id

    ,s.last_request_end_time

    ,s.login_time

    ,r.open_transaction_count

FROM sys.dm_exec_sessions AS s

INNER JOIN sys.dm_exec_requests AS r ON r.session_id = s.session_id

CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS st

--OUTER APPLY sys.dm_exec_query_plan(r.plan_handle) AS qp -- uncomment (2) if you want to see plan

WHERE r.wait_type NOT LIKE 'SP_SERVER_DIAGNOSTICS%'

    OR r.session_id != @@SPID

ORDER BY r.cpu_time DESC

    ,r.STATUS

    ,r.blocking_session_id

    ,s.session_id

Saturday, November 10, 2018

Index and isolation level interview questions

1. What is clustered index?
2. What is non-clustered index?
3. What is unique index?
4. What is Hash index?  ( in memory OLTP)
5. What is filtered index?
6.  Index with included column
7. Clustered column-store index
8. Non-clustered column-store index
     The nonclustered index contains a copy of part or all of the rows and columns in the               underlying table. The index is defined as one or more columns of the table and has an           optional condition that filters the rows.
9. Difference between clustered column-store index vs non-clustered column-store index
     The difference is that a nonclustered index is a secondary index that's created on a                  rowstore table, but a clustered columnstore index is the primary storage for the entire            table.
10.What is a primary key, foreign key and unique key?
11. Composite index
12. covering index
13. Natural key
14.surrogate key
15. Online index.
16. Resumable online index? (yes, row-store index only for SQL 2017 and above version )
17.


SQLServer Interview Questions-2



1. What is the query store in SQL 2016?
2. How do you upgrade SQL server with minimum downtime?
3. Can we setup AlwaysOn availability group between Windows and linux cluster?
4.  How do you partition database?
5. What will be the best practice for selecting RANGE value(LEFT/RIGHT) when you create function?
    By default function will use LEFT RANGE value however best practice would be RIGHT range.
6. What is the Change Data Capture?
7. Can we restore database with CDC enabled from one server to another server
   Answer:-  Yes, we can restore database with "KEEP_CDC" option while restoring database on another server.  also we need to script out following job and create on server where you're restoring the database. or you can simply run below command so it will create job for you on new server.

Exec sys.sp_cdc_add_job 'capture'
go
Exec sys.sp_cdc_add_job 'cleanup'
go
 
8. What is temporal database? difference between CDC vs Temporal database
9. What is a contained database? 
     Independent to SQL server instance. we can use SQL server authentication to connect to the database
10. Estimated vs Actual query plan
11. How SQL server optimizer decides what physical join  will be used to create query plan?
12. Physical join summary:



Nested Loops Join

Merge Join

Hash Join

Best for …

Relatively small inputs with an index on the inner table on the join key.

Medium to large inputs with indexes to provide order on the equijoin keys and/or where we require order after the join.

DW queries with medium to large inputs.  Parallel execution that scales linearly.

Concurrency

Supports large numbers of concurrent users.

Many-to-one join with indexes to provide order supports large numbers of concurrent users.

Best for small numbers of concurrent users with high throughput requirements.

Stop and go

No

No

Yes (build input only)

Equijoin required

No

Yes (except for full outer join)

Yes

Outer and semi-joins

Left joins only (full outer joins via transformation)

All join types

All join types

Uses memory

No

No (may require sorts which use memory)

Yes

Uses tempdb

No

Yes (many-to-many join only)

Yes (if join runs out of memory and spills)

Requires order

No

Yes

No

Preserves order

Yes (outer input only)

Yes

No

13. How to find out if  ColumnStore index is being used from Query plan?
14. Check AlwaysON synchronization status between replicas and find out if there's delay in synchronization
    Alwayson Dashboard
      or DMVs
    SELECT 
ar.replica_server_name, 
adc.database_name, 
ag.name AS ag_name, 
drs.is_local, 
drs.is_primary_replica, 
drs.synchronization_state_desc, 
drs.is_commit_participant, 
drs.synchronization_health_desc, 
drs.recovery_lsn, 
drs.truncation_lsn, 
drs.last_sent_lsn, 
drs.last_sent_time, 
drs.last_received_lsn, 
drs.last_received_time, 
drs.last_hardened_lsn, 
drs.last_hardened_time, 
drs.last_redone_lsn, 
drs.last_redone_time, 
drs.log_send_queue_size, 
drs.log_send_rate, 
drs.redo_queue_size, 
drs.redo_rate, 
drs.filestream_send_rate, 
drs.end_of_log_lsn, 
drs.last_commit_lsn, 
drs.last_commit_time
FROM sys.dm_hadr_database_replica_states AS drs
INNER JOIN sys.availability_databases_cluster AS adc 
ON drs.group_id = adc.group_id AND 
drs.group_database_id = adc.group_database_id
INNER JOIN sys.availability_groups AS ag
ON ag.group_id = drs.group_id
INNER JOIN sys.availability_replicas AS ar 
ON drs.group_id = ar.group_id AND 
drs.replica_id = ar.replica_id
ORDER BY 
ag.name, 
ar.replica_server_name, 
adc.database_name;

Database Mirroring interview questions

1. How to add data files to different drive of mirrored databases?


The steps below will explain the route we took to move database files with zero downtime without disturbing the database Mirroring.

For Mirror Instance:

1. Suspend mirroring on Principal Server (optional).
2. Issue Alter database statement on the mirrored server to point to the new location. 
3. Stop mirrored SQL Server services.
4. Move database files of the mirrored database to the new location and make sure that permissions on the files are preserved.
5. Start mirrored SQL Server services.
6. Resume mirroring on Principal server databases and Verify mirroring is successfully resumed.

For Principal Instance:

1. Fail over databases to Mirror Server so that Mirror server can now act as Principal server.
2.  Suspend mirroring on new Principal server (optional).
3. Issue Alter database statement on the new Mirror server to point databases to the new location.
4. Stop new mirrored SQL Server services.
5. Move database files of the new mirrored database to the new location and make sure permissions on the files are preserved.
6. Start new mirrored SQL Server services.
7. Resume mirroring on Principal server databases and verify mirroring is successfully resumed.

2. Can we configure SQL DB mirroring using local system account on both principal and mirrored server?


No, WE can't configure or run DB mirroring using local system account. Local system account is limited to local system. It won't have an access to different server. you can use domain account or named account to run database services for db mirroring.

3. How to add Data files in mirorred database?

An overview of the entire procedure can be summed up in the following four points:
Remove the existing mirroring partner
Create a new file or file group on the primary server
Take transaction log file backup and restore the same on the mirror server with the help of
   WITH MOVE option
- Once done, database mirroring has to be re-established

4. How to remove witness server from mirrored database?


Using below T-SQL you can remove witness server

ALTER DATABASE DBNAME SET WITNESS OFF;

5. Types of DB mirroring :-

    - Synchronous mirroring(automatic fail-over) -- High Safety
           High Availability  ( require witness server )
           High protection (doesn't require witness server)
   - Asynchronous Mirroring
           High performance ( requires manual fail-over)

6. Is is possible to mirrored database as read only purpose?

   Yes, it is possible only using SNAPSHOT

7. How Database snapshot works?

High level tasks of snapshot involves
· When you create a snapshot a sparse file is created for each data file
· When data is modified in the source database for the first time, the old value of the modified data is copied to the sparse file
· If the same data is the subsequently changed again, those changes will be ignored and not copied to the snapshot
· When you query the snapshot, it first checks if the data is available in the snapshot. If its there it reads if from the snapshot. If its not there, I reads through to the source database and gets the data from there instead, because that means the data has not yet changed since the time the snapshot was taken



Wednesday, August 17, 2016

SQL Server Interview questions-1

view vs materliazied view
Ans:-
1) First difference between View and materialized view is that, In Views query result is not stored in the disk or database but Materialized view allow to store query result in disk or table.
2) Another difference between View vs materialized view is that, when we create view using any table,  rowid of view is same as original table but in case of Materialized view rowid is different.
3) One more difference between View and materialized view in database is that, In case of View we always get latest data but in case of Materialized view we need to refresh the view for getting latest data.
4) Performance of View is less than Materialized view.
5) This is continuation of first difference between View and Materialized View, In case of view its only the logical view of table no separate copy of table but in case of Materialized view we get physically separate copy of table
6) Last difference between View vs Materialized View is that, In case of Materialized view we need extra trigger or some automatic method so that we can keep MV refreshed, this is not required for views in database.

Stored proc vs UDF
Basic Difference:-
Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
Functions can have only input parameters for it whereas Procedures can have input/output parameters .
Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advance Difference
Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
The most important feature of stored procedures over function is to retention and reuse the execution plan while in case of function it will be compiled every time.
Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
We can go for Transaction Management in Procedure whereas we can't go in Function.


Delete vs Truncate

DELETE
1. DELETE is a DML Command.
2. DELETE statement is executed using a row lock, each row in the table is locked for deletion.
3. We can specify filters in where clause
4. It deletes specified data if where condition exists.
5. Delete activates a trigger because the operation are logged individually.
6. Slower than truncate because, it keeps logs.
7. Rollback is possible.
 
TRUNCATE
1. TRUNCATE is a DDL command.
2. TRUNCATE TABLE always locks the table and page but not each row.
3. Cannot use Where Condition.
4. It Removes all the data.
5. TRUNCATE TABLE cannot activate a trigger because the operation does not log individual row deletions.
6. Faster in performance wise, because it doesn't keep any logs.
7. Rollback is not possible.
 
DELETE and TRUNCATE both can be rolled back when used with TRANSACTION.
 
If Transaction is done, means COMMITED, then we can not rollback TRUNCATE command, but we can still rollback DELETE command from LOG files, as DELETE write records them in Log file in case it is needed to rollback in future from LOG files.


Seek perdicate vs predicate
Ans:-
Generally a predicate is a 'condition template' that returns TRUE if it satisfies the condition or FALSE if doesn't satisfies the condtion. For example EmployeeID = 1002, is a predicate applies to a WHERE condition (this can also be applied to table join conditions)
For example, let's say there is an Employee table with millions of data. Execute a query like SELECT Name FROM Employee WHERE EmployeeID = 1002. If there is no index on EmployeeID and Name column, the query engine will scan each row and check the 'predicate' (EmployeeID = 1002) against each row and if the row satisfies the condition, then return the row. This is what you are seeing in execution plan as 'Predicate:'
Let us say the table has a non clustered index on EmployeeID and Name columns. Then the query engine only need to seek the relevant index pages and rows to match the predicate to find the satifiying row. This is called 'Seek Predicates:'

An excellent series on scan and seek are in Craig Freedman's blog below:

http://blogs.msdn.com/b/craigfr/archive/tags/scans+and+seeks/

Seek Predicate is the operation that describes the b-tree portion of the Seek. Predicate is the operation that describes the additional filter using non-key columns. Based on the description, it is very clear that Seek Predicate is better than Predicate as it searches indexes whereas in Predicate, the search is on non-key columns – which implies that the search is on the data in page files itself.


Union vs Union all
UNION performs a DISTINCT on the result set, eliminating any duplicate rows.
UNION ALL does not remove duplicates, and it therefore faster than UNION.

Index seek vs Index scan
http://saurabhsinhainblogs.blogspot.com/2014/01/difference-between-index-seek-vs-index.html
Index Scan --- will scan each row of Table and get query result
Index Seek:-    will scan index leaf level pages  for query result. So performance wise Index Seek is better


                           Scan
                                Seek
  1
When search definition can not point close on single row/ Range of rows to satisfy search predicates. It called as scan
When index definition can point close on single row/ Range of rows to satisfy search predicates. It called as Seek
2
SQL Server has to scan multiple pages to find range of rows which satisfy search predicates.
SQL Server knows which page / Range of rows to read
3
Scan is good if you have to retrieves all the rows from the table.
Seek is used if we need selected rows from the table
4
It reads every row in the table whether or not it qualifies
It reads rows that qualify and pages that contain these qualifying rows
5
Scan cost is proportional to the total number of rows in the table
The cost is proportional to the number of qualifying rows and pages rather than to the total number of rows in the table.
6
If Scan is table scan means table doesn’t have index
Seek is always on index only
7
If table is having very small no. of rows and its not very frequently used, scan and seek will be almost same
If table is having huge no. of records then seek will give huge performance impact.
8
When SQL Server does a scan it loads the complete object which it wants to read from disk into memory, then reads through that object from top to bottom looking for the records that it needs.
It knows where in the index data is going to be, so goes directly to the part of the index that it needs and load to memory
9
You never want to convert seek to scan but if  you just want it, then drop index
By addin column in where clause and select option in index, we can convert a scan into seek operation.
10
A scan means whole data irrespective of data you want
A seek means that you are looking for specific value(s) and the index provides you with the best way to do it
11
Scan can be possible with index or table
Seek is always with index , Db engine search data in B tree
12
Scan is of 3 types clustered index scan , non clustered index scan , table scan
Seek is of two types clustered index seek and nonclustered index seek
13
An Non Clustered index scan is a complete scan of all the leaf pages in B tree to to find index key of cluster index
An Non clustered index seek is a seek through the B-tree structure of a non-clustered index to find index key of clusterindex leaf page, from the root down to the leaf
14
A clustered index scan is a complete scan of all data pages at leaf in a clustered index
A clustered index seek is a seek through the b-tree structure of a clustered index, from the root down to the leaf
15
Nonclustered index scan means lot fewer pages then in clustered index scan
Nonclustered index seek means only pages required for data address, where as in clustered index seek it only reads data pages.
16
Order of data doesnt impact much
Search is fast beacause data is stored in order based on the clustered index key
17
Fragmented data affects scan most as whole data need to be read from disk
fragmented data affects but not as compare to scan, as sql engine reed minimal required data.
18
Scan is genreally not good , some queries it will use a table scan even when a useful index is present - this is usually because the data in the table is so small that it is more hassle to traverse the indexes (if this is the case you would expect the plan to change as the data grows, assuming the selectivity measure of the index is good).
seek is generally much better, but a great many seeks (caused by bad query design with nasty correlated sub-queries for instance, or because you are making many queries in a cursor operation or other loop) can be worse than a scan, especially if your query may end up returning data from most of the rows in the affected table.
19


20
Table scan only appears for a heap ie table without a clustered index. The first page in the heap is located based on info in the system tables, and then the pages are read one by one, using the next and, if necessary, previous pointers in the page headers. This is generally an expensive operation and should be avoided where ever possible
Seek is not possible without index
21
Clustered index scan is similar to table scan, just on a table that has clustered index. This operation reads the leaf pages of the clustered index, using the next and previous page pointers. Like with the table scan, this can be an expensive operation and should, wherever possible be avoided
Clustered index seek uses the clustered index’s b-tree structure. The seek starts at the root of the tree and navigates down the levels of the index until it reached the leaf page(s) with the desired data. This operation also appears when a partial scan of the table is done, when the index’s tree is used to locate a page, and the index is scanned from that point until another point in the table (possibly the end).
22
Index scan means reading all the leaf pages of a non-clustered index using the next and previous page pointers to navigate. Because non-clustered indexes generally have fewer pages in the leaf than a clustered index, this operation is usually cheaper than a clustered index scan
Non-clustered index seek is the same as the clustered index seek, just using a non-clustered index
23
This some times comes with lookups (Row \ Bookmark) , apart of scanning , Another idex is used to over result of scan
In a seak not all of the index is considered. Only one used index is enough
26
We can see scan is horizontal arrow
Seek is vertical arrow explain its nature of work

db mirroring vs log shipping VS Replication


Database Mirroring
Log-shipping
Database mirroring is functionality in the SQL Server engine that reads from the transaction log and copies transactions from the principal server instance to the mirror server instance.  Database mirroring can operate synchronously or asynchronously.
Log shipping is based on SQL Server Agent jobs that periodically take log backups of the primary database, copy the backup files to one or more secondary server instances, and restore the backups into the secondary database(s).  Log shipping supports an unlimited number of secondary’s for each primary database.
Database mirroring can operate synchronously or asynchronously. If configured to operate synchronously, the transaction on the principal will not be committed until it is hardened to disk on the mirror.
Log shipping is always asynchrony. Log shipping totally depends on the log backup and restore schedule
Database mirroring supports only one mirror for each principal database. That means DB mirroring is at database level
Log-shipping can work on database and server level. You can configure multiple databases in logshipping
Data Transfer:    Individual T-Log records are transferred using TCP endpoints
Transactional Consistency:  Only committed transactions are transferred
Server Limitation:   Can be applied to only one mirror server
Failover:   Automatic
Failover Duration:  Failover is fast, sometimes < 3 seconds but not more than 10 seconds
Role Change:   Role change is fully automatic
Client Re-direction:  Fully automatic as it uses .NET 2.0/.Net 3.0
With Log Shipping:
Data Transfer:    T-Logs are backed up and transferred to secondary server
Transactional Consistency:  All committed and un-committed are transferred
Server Limitation:   Can be applied to multiple stand-by servers
Failover:   Manual
Failover Duration:  Can take more than 30 mins
Role Change:   Role change is manual
Client Re-direction:  Manual changes required
Support only full recovery model
Supports full and bulk-logged recovery model
Mirror database is always in recovery mode. To read it you have use database snapshot.
You can use the stand-by option to read the database on standby server
Auto Page Recovery introduced with SQL SERVER 2008 so it will recover the damaged pages.
Not supported


ISNULL VS COALESCE
Ans:-
•ISNULL can accept only two arguments where as COALESCE can accept any number of input parameters
•ISNULL is not ANSI standard and is proprietary to TSQL.
•With ISNULL, the datatype of the second argument is converted to equal the data type of the first argument where as COALESCE converts according to data type precedence.  
•ISNULL is generally accepted to be faster than COALESCE.
•COALESCE is a much cooler word and will usually earn you either an impressed glance or a blank confused stare when slipped into casual conversation.  

charindex vs patindex
Ans:-
Similarity
Both the functions accepts two arguments to search the specified text filed in the given expression.
Both the function returns the starting position of the matching pattern given in the function.

Difference
The PatIndex function is used with the wildcard characters. You must enclosed the wildcard characters before (when searching at last) or after (when looking for first) the searching text.
But, the CharIndex function can not be used any wildcard characters with the specified searching pattern. In the CharIndex function will not work upon the  wildcard characters.
Example of PatIndex
SELECT (PATINDEX('%Corner%', 'C-SharpCorner'))
Will result 8.

Example of CharIndex
SELECT (charindex('Corner', 'C-SharpCorner'))
Will also result 8.

ONLINE Index vs Offline Index
Ans:-
In ONLINE mode the new index is built while the old index is accessible to reads and writes.
any update on the old index will also get applied to the new index. An antimatter column is used to track possible conflicts between the updates and the rebuild (ie. delete of a row which was not yet copied).
See Online Index Operations. When the process is completed the table is locked for a brief period and the new index replaces the old index. If the index contains LOB columns, ONLINE operations are not supported in SQL Server 2005/2008/R2.
In OFFLINE mode the table is locked upfront for any read or write, and then the new index gets built from the old index, while holding a lock on the table.
No read or write operation is permitted on the table while the index is being rebuilt. Only when the operation is done is the lock on the table released and reads and writes are allowed again.

Bookmark Lookup VS RID Lookup


Clustered Index vs Non-Clustered Index
A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
A non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.


Having VS Where Clause


Both Having Clause and Where clause is used to filter the data coming from the Select statement, but still there are some differences between them. These difference are given below:-
Where clause can be used with Select, Update and Delete Statement Clause but having clause can be used only with Select statement.
We can't use aggregate functions in the where clause unless it is in a subquery contained in a HAVING clause whereas  we can use aggregate function in Having clause. We can use column name in Having clause but the column must be contained in the group by clause.
For example,  the sql query
select * from EmployeeDeptInfo where count(employeeid)>1 
will not  work but the query
Select Employeeid, Departmentid from EmployeeDeptInfo Group By Employeeid, DepartmentId having (count(employeeid) >1)
will work fine

Where Clause is used on the individual records whereas Having Clause in conjunction with Group By Clause work on the record sets ( group of records ).

CTE VS TEMP Table
CTEs... (creates tables being used in memory)/It just ad-hoc view
Are unindexable (but can use existing indexes on referenced objects)
Cannot have constraints
Are essentially disposable VIEWs
Persist only until the next query is run
Can be recursive
Do not have dedicated stats (rely on stats on the underlying objects)
#Temp Tables... (creates table being created tempdb databse/ on disk)
Are real materialized tables that exist in tempdb
Can be indexed
Can have constraints
Persist for the life of the current CONNECTION
Can be referenced by other queries or subprocedures
Have dedicated stats generated by the engine
As far as when to use each, they have very different use cases. If you will have a very large result set, or need to refer to it more than once, put it in a #temp table. If it needs to be recursive, is disposable, or is just to simplify something logically, a CTE is preferred.
Also, a CTE should never be used for performance. You will almost never speed things up by using a CTE, because, again, it's just a disposable view. You can do some neat things with them butspeeding up a query isn't really one of them

Rebuild index Vs Reorganize index

no
REBUILD
REORGANIZE
1
This process drops the existing Index and Recreates the index
This process doesn’t drop indexes; It physically reorganizes the leaf nodes of the index.
2
Syntax: ALTER INDEX ALL ON table_name REBUILD
Syntax: ALTER INDEX ALL ON table_name REORGANIZE
3
Index should be rebuild when index fragmentation is great than 30%
Index should be reorganized when index fragmentation is between 10% to 30%
4
Index rebuilding process uses more CPU and it locks the database resources
Index reorganize process uses less CPU and it doesn’t the database resources
5
Rebuilding an index can be executed online or offline
Reorganizing an index is always executed online
6
A nice thing about rebuilding an index is that you can change the setting for index properties like the fill factor and index padding
Index options cannot be specified when reorganizing an index
7
Requires ALTER permission on the table or view or  User must be a member of the sysadmin fixed server role or the db_ddladmin and db_owner fixed database roles
Requires ALTER permission on the table or view or  User must be a member of the sysadmin fixed server role or the db_ddladmin and db_owner fixed database roles
8
REBUILD locks the table for the whole operation period except in Enterprise Edition with ONLINE = ON
REORGANIZE doesn't lock the table.
9
It is changing the whole B-tree, recreating the index
It is a process of cleaning, organizing, and defragmenting of only  "leaf level" of the B-tree
10
REBUILD will automatically rebuild all index-column statistics
Statistics are NOT updated with a reorganization
11
This reclaims disk space by compacting the pages in new index
It works in two phases – compaction and defrag
12
Rebuild does require extra space as same the size of index
Reorganize essentially just swaps one page with another and thus does not require free space
13
Rebuild can fix extent fragmentation as well
Reorganize can remove almost all of the logical fragmentation but it cannot necessarily fix extent fragmentation
14
Index (clustered or non-clustered) cannot be built online if it contains LOB data (text, ntext, varchar(max), nvarchar(max), varbinary(max), image and xml data type columns).
Its always online operation.
15
If an index has multiple partitions, then you cannot rebuild a single partition online
You can reorganize a single index partition online
16
After rebuild statistics on non-indexed columns doesn’t get re-computed
Statistics are NOT updated with a reorganization
17
Rebuild is an atomic operation
Reorganize can be stopped while it is occurring and you won't lose the work it has already completed
18
Rebuild indexes always generates similar amount of  t-log for same size index
For large, heavily fragmented indexes the reorganization operation will generate more t-log as compared to less fragmented index
19
REBUILD requires enough free space in the database to accommodate the new index
REORGANIZE only requires 8KB of additional space in the database
20
REBUILD can use multiple CPUs so the operation runs faster
REORGANIZE is always single-threaded
21
REBUILD can use minimal-logging to reduce transaction log growth
REORGANIZE is always fully logged, but doesn’t prevent transaction log clearing.
22
An index rebuild will always rebuild the entire index, regardless of the extent of fragmentation
An index reorganize will only take care of the existing fragmentation
23
SQL 2000 use DBCC DBREINDEX
SQL 2000 use DBCC INDEXDEFRAG
24
Even If the index spans multiple data files, it will be taken care
If the index spans multiple data files, reorganizing will only reorder pages within the same file, it won’t move pages between files


PAGE VS Extent
Extent Vs Page?
Pages are low level unit to store the exact data in sql server. Basically, the data will be stored in the mdf, ldf, ndf files. Inturn, pages are logical units available in sql server.
The size of the page is 8KB.
Eight consecutive pages will form an extent 8 * 8KB = 64KB. Thus I/O level operation will be happening at pages level.
The pages will hold a template information at the start of each page (header of the page). They are,
1. page number,
2. page type,
3. the amount of free space on the page,
4. the allocation unit ID of the object that owns the page.

Extents will be classifed into two types,

1. Uniform extents
2. Mixed extents

Uniform Extents:
It occupied or used by a single object. Inturn, a single object will hold the entire 8 pages.
Mixed Extents:
Mulitple objects will use the same extent. SQL Server will allow a max of eight objects to use a shared extent.

Property of SQL Server :
Initally if an object is created, sql server will allocate the object to the mixed extent and once if the size reaches 8 pages and more... immediately, a new uniform extent will be provided for that particular object.

Dirty Read Vs Phantom
Dirty Read:-
Dirty read occurs when one transaction is changing the record, and the other transaction can read this record before the first transaction has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid data.
Dirty Read Example:-
Transaction A begins.
UPDATE EMPLOYEE SET SALARY = 10000 WHERE EMP_ID= ‘123’;
Transaction B begins.
SELECT * FROM EMPLOYEE;
(Transaction B sees data which is updated by transaction A. But, those updates have not yet been committed.)
Non-Repeatable Read:-
Non Repeatable Reads happen when in a same transaction same query yields to a different result. This occurs when one transaction repeatedly retrieves the data, while a difference transactions alters the underlying data. This causes the different or non-repeatable results to be read by the first transaction.
Non-Repeatable Example:-
Transaction A begins.
SELECT * FROM EMPLOYEE WHERE EMP_ID= ‘123’;
Transaction B begins.
UPDATE EMPLOYEE SET SALARY = 20000 WHERE EMP_ID= ‘123’;
(Transaction B updates rows viewed by the transaction A before transaction A commits.) If Transaction A issues the same SELECT statement, the results will be different.
Phantom Read:-
Phantom read occurs where in a transaction execute same query more than once, and the second transaction result set includes rows that were not visible in the first result set. This is caused by another transaction inserting new rows between the execution of the two queries. This is similar to a non-repeatable read, except that the number of rows is changed either by insertion or by deletion.
Phantom Read Example:-
Transaction A begins.
SELECT * FROM EMPLOYEE WHERE SALARY > 10000 ;
Transaction B begins.
INSERT INTO EMPLOYEE (EMP_ID, FIRST_NAME, DEPT_ID, SALARY) VALUES (‘111′, ‘Jamie’, 10, 35000);
Transaction B inserts a row that would satisfy the query in Transaction A if it were issued again.

Differences Among CTE, Derived Table, Temp Table, Sub Query And Temp Variable:-


CTE:

The CTE is an abbreviation of “Common Table Expression.” CTE was introduced in SQL Server. It works as a temporary result set that is defined within the execution scope of a single select, insert, update, delete statements. CTE is typically the result of complex sub queries. Similar to temporary tables CTE doesn’t store as an object; the scope is limited to the current query. CTE improves readability and ease in maintenance of complex queries and sub-queries.
When to use CTE
  • Use for recursive query.
  • CTE is easy to implement compared to complex queries which involves several sub-queries.
Temp Variables:

Temp Variables are also used for holding the data fora  temporary time just like Temp tables. Temp variables are created using “DECLARE” statements and are assigned values by using either a SET or SELECT command. After declaration, all variables are initialized as NULL, unless a value is provided as part of the declaration. This acts like a variable and exists for a particular batch of query executions. It gets dropped once it comes out of batch. Temp variables are also created in the Tempdb database but not the memory.
Limitations Of Temp Variables
  1. Unlike the majority of the other data types in SQL Server, you cannot use a table variable as an input or an output parameter.
  2. The variable will no longer exist after the procedure exits - there will be no table to clean up with a DROP statement.
  3. We cannot create a non-clustered index on a table variable, unless the index is a side effect of a PRIMARY KEY or UNIQUE constraint on the table. It can only have indexes that are automatically created with PRIMARY KEY & UNIQUE constraints as part of the DECLARE statement. Indexes cannot be added after the table has been created.
When to use Temp Variables:
  • When you are required to use the current result set in next queries then store result into temp variables.
  • When your data set is smaller, approximately less than 1000 records, then use temp variables , if your result set is larger then use temp table instead of temp variables.
Temp Table:

Temporary tables are tables that are available only to the session that created them. 

These tables are automatically destroyed at the termination of the procedure or session that created them. SQL Server provides the concept of temporary table which helps the developers in a great way. These tables can be created at runtime and can do all kinds of operations that one normal table can do. In SQL Server all temporary tables are present in tempdbdatabase.

Types of Temporary Tables:

SQL Server contain two types of Temporary tables:
  1. Local Temporary Tables
  2. Global Temporary Tables
Local Temporary Tables:

Local temporary tables are temporary tables that are available only to the session that created them. These tables are automatically destroyed at the termination of the procedure or session that created them. Local temp tables are only available to the current connection for the user. Names of Local temp tables start with(“#”) hash sign.
Global Temporary Tables:

Global temporary tables are temporary tables that are available to all sessions and all users. Once this table has been created by a connection, like a permanent table, then it is available to any user by any connection. They are dropped automatically when the last session using the temporary table has completed. Names of Global temp tables start with (“##”) double hash sign.
When to Use Temporary Tables
  1. We required to hold data from further query.
  2. When we have a complex Join operation.
  3. In some cases it may be a replacement of cursors.
Derived Table:

Derived tables are the tables which are created on the fly with the help of the Select statement. Derived table expression appears in the FROM clause of a query. In derived table server create and populate the table in the memory, we can directly use it and we also don’t require to drop the table. But scope of derived table is limited to the outer Select query who created it. Derived table can’t be used further outside the scope of outer select query.
When to Use:
  • When you are required to perform some complex query and result of inner query work as table for outer query.
Subquery: 

A subquery is a SELECT statement that is nested within another statement. Subquery is also known as nested query. Result of subquery is used in the main query as a condition to further restrict the data to be retrieved. The subquery used in select, update, delete and insert command.
Difference between subquery and derived table:
Subquery
Derived
Subqueries must be enclosed within parentheses.
Derived table must be enclosed within parentheses and table name must be provided.
Subquery can have only one column.
Derived table can have one or more column.
Subquery mainly use in where clause.
Derived table used in from clause.
Difference b/w Temp table and Temp variable:
Temp Table
TempVariable
Scope of Temp Table is wider the temp variables of. Local temporary tables are temporary tables that are available only to the session that created them and Global temporary tables are temporary tables that are available to all sessions and all users.
Scope of the Temp variables are limited up to current batch and current stored procedure.
Temp tables can be create using Create Table and Select Into commands
Temp variables only through Declare command can’t be created using select into command.
Temp tables can be drop through Drop Command.
We can not drop a Temp variables but we can use truncate command for temp variables.
Name of Temp table can have maximum 116 characters.
Name of a temp variables can have MAXIMUM 128 characters.
Temp table support foreign key concept.
Temp variable doesn’t support foreign key.
Temp tables support transaction management.
Temp variables doesn’t support transaction management. Rollback not work for temp variables.
Temp tables can easily handle large amount of data.
Temp variables are suitable with small amount of data.

Difference b/w CTE and Derived table:
CTE
Derived Table
A CTE can be referenced multiple times in the same query. So CTE can use in recursive query.
Derived table can’t referenced multiple times. Derived table can’t use in recursive queries.
CTE are better structured compare to Derived table.
Derived table’s structure is not good as CTE.