SQL Server Interview Questions With Answers Set 2 40 Questionsanswers
SQL Server Interview Questions With Answers Set 2 40 Questionsanswers
http://msbiskills.com/
Question1. We have a query which is running fine in development but facing performance issues at
production. You got the execution plan from production DBA. Now you need to compare with the
development execution plan. What is your approach? / Poor query performance in Prod.
Answer
This is an open ended question; there could be possible reasons for this issue. Some of them are given below1. Fragmentation could be one of the issues.
2. Check statistics are updated or not.
3. Check what other processes are running on production server.
4. Check if query is returning multiple query plans; if yes then there could be two reasons Parameter sniffing
or invalid plans due to set options
5. Check which indexes are getting used?
6. Examine the execution plan to find out the Red Flags. You have to understand what is going on bad and then
figure out the alternatives.
Notes You can disable Lock Escalation for time being, but you got to be very careful with this. You can use
loop to perform DELETE/UPDATE statements, so that you can prevent Lock Escalations. With this approach
huge transactions will be divided into multiple smaller ones, which will also help you with Auto Growth issues
that you maybe have with your transaction log.
COALESCE
Data type returned is the expression with the highest data type
precedence. If all expressions are non-nullable, the result is typed
as non-nullable.
It is a built in function
Here one of the values should be NON NULL otherwise It will throw
an error. At least one of the arguments to COALESCE must be an
expression that is not the NULL constant. We can do something
like below-DECLARE @d AS INT = NULL SELECT
COALESCE(NULL, @d)
Question5. What is the difference between CROSS APPLY & OUTER APPLY IN T-SQL?
Answer
The APPLY operator comes in two flavors, CROSS APPLY and OUTER APPLY. It is useful for joining two SQL
tables or XML expressions.
CROSS APPLY is equivalent to an INNER JOIN expression and OUTER APPLY is equivalent to a LEFT
OUTER JOIN expression. E.g. below-
EmpId
1
2
3
EmpName
Rohit
Rahul
Isha
DeptID
1
2
1
DeptID
1
2
1
Name
IT
Finance
IT
EmpId EmpName
1
Rohit
DeptID
1
DeptID
1
Name
IT
2
3
4
Rahul
Isha
Disha
2
1
NULL
2
1
NULL
Finance
IT
NULL
Question7. How to change the port number for SQL Server? Default port no of SQL SERVER
AnswerDefault PORT Number of SQL Server is 1433. You can view the port number under configuration Manager.
URL https://msdn.microsoft.com/en-us/library/ms177440.aspx
To assign a TCP/IP port number to the SQL Server Database Engine
In SQL Server Configuration Manager, in the console pane, expand SQL Server Network Configuration, expand
Protocols for, and then double-click TCP/IP.
1. In the TCP/IP Properties dialog box, on the IP Addresses tab, several IP addresses appear in the format
IP1, IP2, up to IPAll. One of these is for the IP address of the loopback adapter, 127.0.0.1. Additional IP
addresses appear for each IP Address on the computer. Right-click each address, and then click
Properties to identify the IP address that you want to configure.
2. If the TCP Dynamic Ports dialog box contains 0, indicating the Database Engine is listening on dynamic
ports, delete the 0.
3. In the IPn Properties area box, in the TCP Port box, type the port number you want this IP address to
listen on, and then click OK.
4. In the console pane, click SQL Server Services.
5. In the details pane, right-click SQL Server () and then click Restart, to stop and restart SQL Server.
After you have configured SQL Server to listen on a specific port, there are three ways to connect to a specific
port with a client application:
Run the SQL Server Browser service on the server to connect to the Database Engine instance by name.
Create an alias on the client, specifying the port number.
Program the client to connect using a custom connection string.
Query memory grant OR Query Work Buffer is a part of server memory used to store temporary row data while
sorting and joining rows.
It is called grant because the server requires those queries to reserve before actually using memory. This
reservation improves query reliability under server load, because a query with reserved memory is less likely to
hit out-of-memory while running, and the server prevents one query from dominating entire server memory. For
details please visit below
http://blogs.msdn.com/b/sqlqueryprocessing/archive/2010/02/16/understanding-sql-server-memory-grant.aspx
Answer
Parameter sniffing is an expected behavior. SQL Server compiles the stored procedures using the parameters
send to the first time the procedure is compiled and save it in plan cache for further reuse.
After that every time the procedure executed again, Now the SQL Server retrieves the execution plan from the
cache and uses it.
The potential problem arises when the first time the stored procedure is executed, the set of parameters
generate an acceptable plan for that set of parameters but very bad for other more common sets of parameters.
Workarounds to overcome this problem are given below
OPTION (RECOMPILE)
OPTION (OPTIMIZE FOR (@VARIABLE=VALUE))
OPTION (OPTIMIZE FOR (@VARIABLE UNKNOWN))
Use local variables
--**********OLD PROC******************
CREATE PROC Area
(
@ToPoint VARCHAR(20)
)
AS
SELECT ID , FromPoint , ToPoint , Distance FROM Area
WHERE ToPoint = @ToPoint
Question11. While creating non clustered indexes on what basis we should choose main columns and
include columns?
Answer
A NonClustered index can be extended by including nonkey columns in addition to the index key columns. The
nonkey columns are stored at the leaf level of the index b-tree.
The Syntax of a Non Clustered Index with Included column is given below
KeyColumns These columns are used for row restriction and processing E.g they were used in
WHERE, JOIN, ORDER BY, GROUP BY etc.
NonKeyColumns These columns are used in SELECT and Aggregation. For e.g. AVG(col) after
selection/restriction.
So always choose KeyColumns and NonKeyColumns based on the query requirements only.
Question12. What is the difference between pessimistic locking and optimistic locking?
Answer
Source http://dba.stackexchange.com/questions/35812/why-is-optimistic-locking-faster-than-pessimisticlocking
Lets start with the analogy with banks.
Pessimistic locking is like having a guard at the bank door who checks your account number when you try to
enter; if someone else accessing your account, then you cannot enter until that other person finishes his/her
transaction and leaves.
Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has
much better integrity than optimistic locking but requires you to be careful with your application design to avoid
Deadlocks.
Optimistic locking, on the other hand, allows you to walk into the bank at any time and try to do your business,
but at the risk that as you are walking out the door the bank guard will tell you that your transaction conflicted
with someone elses and you will have to go back and do the transaction again.
Optimistic Locking is a strategy where you read a record, take note of a version number and check that the
version hasnt changed before you write the record back. When you write the record back you filter the update
on the version to make sure its atomic. (i.e. hasnt been updated between when you check the version and
write the record to the disk) and update the version in one hit.
If the record is dirty (i.e. different version to yours), Optimistic locking possibly causes a transaction to fail, but it
does so without any lock ever having been taken. And if a transaction fails because of optimistic locking, the
user is required to start all over again. The word optimistic derives from exactly the expectation that the
condition that causes transactions to fail for this very reason, will occur only very exceptionally. Optimistic
locking is the approach that says I will not be taking actual locks because I hope they wont be needed anyway.
If it turns out I was wrong about that, I will accept the inevitable failure..
This strategy is most applicable to high-volume systems and three-tier architectures where you do not
necessarily maintain a connection to the database for your session. In this situation the client cannot actually
maintain database locks as the connections are taken from a pool and you may not be using the same
connection from one access to the next.
Every time space is allocated for the transaction log file (It may be an Initial creation or log growth) new VLFs
are created behind the scenes. The number of new VLFs is determined by the amount of space allocated.
Use below query to find out the growth and transaction log details
SELECT
name FileName,
CAST(size*8/1024 AS VARCHAR(10))+'MB' Size,
CASE is_percent_growth
WHEN 1 THEN CAST(growth AS VARCHAR(10))+'%'
ELSE CAST(growth*8/1024 AS VARCHAR(10))+'MB'
END AutoGrowth
FROM sys.database_files WHERE type_desc = 'LOG'
DBCC LOGINFO;
GO
Question14. Can you give some examples for One to One, One to Many and Many to Many
relationships?
Answer There are following types of database relationships.
Lets say we have two table Students and Teachers. We have a relationship between the Students table and the
Teachers table. One teacher can teach multiple students and one student can be taught be multiple teacher.
This kind of relationship called One to many relationship.
Note Please note that for this kind of relationship we require 3rd table to handle relationship.
Check out the example below.
After creating the above stored procedures, execute the parent stored proc using below command.
EXEC MainSP
For that please follow the steps given below.
Step 1.Open SQL Server profile by clicking on Start, type SQL SERVER Profiler and click on SQL Server
profiler.
Click on Show all events, then select stored procedures as shown below.
Now execute the Main SP and check out the trace below
We can see all the trace i.e. from Parent SP and child SP.
SET ROWCOUNT 2
SELECT TOP 4 * FROM Approver
SET ROWCOUNT 0
Note - using SET ROWCOUNT will not affect DELETE, INSERT, and UPDATE statements in a future
release of SQL Server.
Avoid using SET ROWCOUNT with DELETE, INSERT, and UPDATE statements in new development work,
and plan to modify applications that currently use it. For a similar behavior, use the TOP syntax.
Question18. What is the SQL Query Order of Operations? OR What is the Logical Query Processing
Phases and their order in SQL Statement Execution.
Answer
SQL Server processes SQL statements in a Logical Order. We call it Logical Query Processing Phases. Phases
and their order is given belowFROM
ON
OUTER
WHERE
GROUP BY
CUBE | ROLLUP
HAVING
SELECT
DISTINCT
TOP
ORDER BY
If you want to remember the above sequence use Fred-Will-Give-Her-Some-O
You can also learn this in detail from below URLhttp://tsql.solidq.com/books/insidetsql2008/Logical%20Query%20Processing%20Poster.pdf
Question19. What is .TUF file? What is the significance of the same? Any implications if the file is
deleted?
Answer
TUF file is the Transaction Undo File.
This file is created when Log Shipping is configured in SQL Server in standby mode. This file is located @ the
path where transaction log files were saved.
This File consists of list of uncommitted transactions while backup is going on the primary server in Log
Shipping. If .tuf file is got deleted there is no way to repair log shipping except reconfiguring it from scratch.
The transaction undo file contains modifications that were not committed on the source database but were in
progress when the transaction log was backed up AND when the log was restored to another database, you left
the database in a state that allowed addition transaction log backups to be restored to it (at some point in the
future. When another transaction log is restored, SQL Server uses data from the undo file and the transaction
log to continue restoring the incomplete transactions (assuming that they are were completed in the next
transaction log file). Following the restore, the undo file will be re-written with any transactions that, at that point,
are incomplete.
Question20. What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Answer
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock
on the others piece. Each process would wait indefinitely for the other to release the lock, unless one of the
user processes is terminated. SQL Server detects deadlocks and terminates one users process.
A live lock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping
shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared
locks. A live lock also occurs when read transactions monopolize a table or page, forcing a write transaction to
wait indefinitely.
A human example of live lock would be two people who meet face-to-face in a corridor and each move aside to
let the other pass, but they end up moving from side to side without making any progress because they always
move the same way at the same time and never cross each other. This is good example of live lock.
Question21. Can you tell us different types of Isolation levels? What is the default Isolation level?
Answer
There are five type of Isolation level in MS SQL Server.
Read Uncommitted
Repeatable Read
Serializable
Snapshot
Question23. When the lazy writer happens and what itll do?
Answer The lazy writer is a process that periodically checks the available free space in the buffer cache
between two checkpoints and ensures that there is always enough free memory. When the lazy writer
determines free pages are needed in the buffer for better performance, it removes the old pages before the
regular checkpoint occurs.
Ideally, Lazy Writes should be close to zero. That means that the buffer cache doesnt have to free up dirty
pages immediately, it can wait for the automatic check point.
For detailed explanation please click on the below URLhttp://www.sqlshack.com/sql-server-memory-performance-metrics-part-5-understanding-lazy-writes-free-liststallssec-memory-grants-pending/
Question24. What are the properties of a transaction? What are ACID Properties
Answer Atomicity Consistency Isolation Durability (ACID) is a concept referring to a database systems four
transaction properties: atomicity, consistency, isolation and durability.
Atomicity
Here either all the statements (whether an update, delete or insert) of the transaction will happen or not happen.
To guarantee atomicity, SQL Server uses a Write Ahead Transaction Log. The log always gets written to first
before the associated data changes. That way, if and when things go wrong, SQL Server will know how to roll
back to a state where every transaction happened or didnt happen.
Consistency
A transaction reaching its normal end, thereby committing its results, preserves the consistency of the database.
If something bad happens then everything in the transaction will be rolled back. After each transaction DB
should be in a consistent state.
Isolation
Events happening within a transaction must be hidden from other transactions running concurrently.
Durability
Once a transaction has been completed and has committed its results to the database, the system must
guarantee that these results survive any subsequent malfunctions.
Question25. Why do some system functions require parenthesis and some do not require?
Answer
In SQL Server most of the system functions require parenthesis at the end. The examples can be GETDATE(),
NEWID(), RAND(), ERROR_MESSAGE(), etc.
Some functions do not need the parenthesis. The examples can be CURRENT_TIMESTAMP,
CURRENT_USER, etc.
ANSI SQL standard functions do not need parenthesis.
SQL Server functions requires parenthesis
Question27. Does foreign Key slows down the insertion process in SQL Server?
Answer
Well the difference would be very negligible. Please read excellent post below for details.
http://www.brentozar.com/archive/2015/05/do-foreign-keys-matter-for-insert-speed/
Question29. How to calculate the likely size of an OLAP cube from the Relational database size?
Answer
You can use a general rule of Analysis Services data being about 1/4 1/3 size of the same data stored in
relational database.
Reference https://social.msdn.microsoft.com/Forums/sqlserver/en-US/6b16d2b2-2913-4714-a21d07ff91688d11/cube-size-estimation-formula
Question30. SQL Query | Consider the below table below and write some queries to replace 0 by 1 and 1
by 0.
DBINFO @0x00000000145FDAE0
dbi_version = 706
dbi_createVersion = 706
dbi_dvSplitPoint = 0:0:0 (0x00000000:00000000:0000)
dbi_dbbackupLSN = 15034:5896:37 (0x00003aba:00001708:0025)
dbi_SEVersion = 0
dbi_status =
dbi_dbid = 7
dbi_maxDbTimestamp
dbi_RebuildLogs =
dbi_RestoreFlags =
dbi_dbccFlags = 2
dbi_RecoveryFlags
dbi_relstat =
dbi_recoveryForkNameStack
entry 0
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
m_guid = ced081af-d46a-41b0-911c-d42adc6b04ce
entry 1
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
m_guid = 00000000-0000-0000-0000-000000000000
dbi_differentialBaseGuid = 555d80f3-3003-419b-a1eb-c1b059f76d22
dbi_firstSysIndexes = 0001:00000014
dbi_oldestBackupXactLSN = 0:0:0 (0x00000000:00000000:0000)
dbi_versionChangeLSN = 0:0:0 (0x00000000:00000000:0000)
dbi_mdUpgStat =
0x0004
dbi_category = 0x0000000000000000
dbi_safetySequence = 0
dbi_dbMirrorId = 00000000-0000-0000-0000-000000000000
dbi_pageUndoLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_pageUndoState
= 0
dbi_disabledSequence = 0
dbi_dbmRedoLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_dbmOldestXactLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_CloneCpuCount
= 0
dbi_CloneMemorySize = 0
dbi_updSysCatalog = 1900-01-01 00:00:00.000
dbi_LogBackupChainOrigin = 15034:5896:37 (0x00003aba:00001708:0025)
dbi_dbccLastKnownGood = 1900-01-01 00:00:00.000
dbi_roleSequence =
0
dbi_dbmHardenedLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_localState = 0
dbi_safety = 0
dbi_modDate = 2013-04-12 12:15:13.890
dbi_verRDB = 184552376
dbi_lazyCommitOption = 0
dbi_svcBrokerGUID = b5fe6d7f-a888-4c3f-af66-3e264784ba17
dbi_svcBrokerOptions = 0x00000000
dbi_dbmLogZeroOutstanding = 0
dbi_dbmLastGoodRoleSequence = 0
dbi_dbmRedoQueue =
0
dbi_dbmRedoQueueType = 0
dbi_rmidRegistryValueDeleted = 0
dbi_dbmConnectionTimeout = 0
dbi_fragmentId = 0
dbi_AuIdNext = 1099511628233
dbi_MinSkipLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_commitTsOfcheckptLSN = 0
dbi_dbEmptyVersionState = 0
dbi_CurrentGeneration = 0
dbi_EncryptionHistory
Scan 0
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
EncryptionScanInfo:ScanId = 0
Scan 1
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
EncryptionScanInfo:ScanId = 0
Scan 2
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
EncryptionScanInfo:ScanId = 0
dbi_latestVersioningUpgradeLSN = 18:81:67 (0x00000012:00000051:0043)
dbi_splitAGE = 0
dbi_PendingRestoreOutcomesId = 00000000-0000-0000-0000-000000000000
dbi_ContianmentState = 0
DBCC execution completed. If DBCC printed error messages, contact your system
administrator.
DBCC TRACEON(3604);
DBCC PAGE(0,1,9,3);
DBCC execution completed. If DBCC printed error messages, contact your system
administrator.
PAGE: (1:9)
BUFFER:
BUF @0x00000002FB1C0000
bpage = 0x00000002FA5DE000
bdbid = 7
bsampleCount = 0
blog = 0x15a9a
bhash = 0x0000000000000000
breferences = 0
bUse1 = 55356
bnext = 0x0000000000000000
bpageno = (1:9)
bcputicks = 0
bstat = 0x10b
m_headerVersion = 1
m_level = 0
m_indexId (AllocUnitId.idInd) = 0
m_type = 13
m_flagBits = 0x0
Metadata:
Metadata: IndexId = 0
Metadata: ObjectId
m_nextPage = (0:0)
m_freeCnt = 6590
m_lsn = (15193:4928:13)
m_ghostRecCnt = 0
pminlen = 0
m_freeData = 1600
m_xactReserved = 0
m_tornBits = -
PAGE HEADER:
Page @0x00000002FA5DE000
m_pageId = (1:9)
m_typeFlagBits = 0x0
m_objId (AllocUnitId.idObj) = 99
AllocUnitId = 6488064
Metadata: PartitionId = 0
= 99
m_prevPage = (0:0)
m_slotCnt = 1
m_reservedCnt = 0
m_xdesId = (0:0)
1057360342
DB Frag ID = 1
Allocation Status
GAM (1:2) = ALLOCATED
SGAM (1:3) = NOT ALLOCATED
PFS (1:1) = 0x64 MIXED_EXT ALLOCATED 100_PCT_FULL
CHANGED
ML (1:7) = NOT MIN_LOGGED
DIFF (1:6) =
Record Attributes =
.................
755c907b
6e002020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
00000000
08170000
00000000
77000000
00000061
dc6b04ce
00000000
6ad4b041
00000000
f3805d55
01006302
00000000
00000000
00000000
00000000
00000000
ba3a0000
00000000
9ea10000
af663e26
00000000
00010000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
u\.{...P.a.w.a.
n.
f7efc900
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
ba3a0000
25000000
00000000
1efd1e00
00000000
00508c39
00000000
911cd42a
00000000
03309b41
00000000
00000400
00000000
00000000
00000000
00000000
08170000
00000000
b80b000b
4784ba17
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
9ea10000
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
0a000000
08170000
593b0000
00000000
00000000
af81d0ce
00000000
00000000
dc6b04ce
00000000
a1ebc1b0
00000000
00000000
00000000
00000000
00000000
00000000
25000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
50006100
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
07006e00
25000000
90100000
593b0000
08f00000
6ad4b041
00000000
00000000
00000000
00000000
59f76d22
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
7f6dfeb5
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
77006100
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
20202020
d0070000
ba3a0000
77000200
90100000
00000000
911cd42a
00000000
af81d0ce
00000000
00000000
14000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
f7efc900
88a83f4c
00000000
c9010000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
......n....
....:......%...:..
....%...Y;......w...
............Y;......
w.................
...a.....jA.*
k..P9............
.................
jA.*k.........
....................
.]U.0AYm"....
..c.................
....................
....................
....................
....................
....................
:......%...........
.................
..........m.?L
f>&G.............
...................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
000000000000049C:
00000000000004B0:
00000000000004C4:
00000000000004D8:
00000000000004EC:
0000000000000500:
0000000000000514:
0000000000000528:
000000000000053C:
0000000000000550:
0000000000000564:
0000000000000578:
000000000000058C:
00000000000005A0:
00000000000005B4:
00000000000005C8:
00000000000005DC:
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
43000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
12000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000
51000000
00000000
00000000
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
................Q...
C...................
....................
....
DBINFO @0x00000000145FA060
dbi_version = 706
dbi_createVersion = 706
dbi_dvSplitPoint = 0:0:0 (0x00000000:00000000:0000)
dbi_dbbackupLSN = 15034:5896:37 (0x00003aba:00001708:0025)
dbi_LastLogBackupTime = 2015-01-22 12:17:21.873
dbi_nextseqnum = 1900-01-01 00:00:00.000
0x00010000
dbi_crdate = 2013-04-12 12:15:13.890dbi_dbname = Pawan
dbi_cmptlevel = 110
dbi_masterfixups = 0
= 2000
dbi_dbbackupLSN = 15034:5896:37 (0x00003aba:00001708:0025)
0
dbi_differentialBaseLSN = 15034:5896:37 (0x00003aba:00001708:0025)
0x0000
dbi_checkptLSN = 15193:4240:119 (0x00003b59:00001090:0077)
dbi_COWLastLSN = 0:0:0 (0x00000000:00000000:0000)
dbi_DirtyPageLSN = 15193:4240:119 (0x00003b59:00001090:0077)
= 0x00000000
dbi_lastxact = 0x1efd1e
dbi_collation = 61448
0x61000000
dbi_familyGUID = ced081af-d46a-41b0-911c-d42adc6b04ce
dbi_maxLogSpaceUsed = 965496832
dbi_SEVersion = 0
dbi_status =
dbi_dbid = 7
dbi_maxDbTimestamp
dbi_RebuildLogs =
dbi_RestoreFlags =
dbi_dbccFlags = 2
dbi_RecoveryFlags
dbi_relstat =
dbi_recoveryForkNameStack
entry 0
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
m_guid = ced081af-d46a-41b0-911c-d42adc6b04ce
entry 1
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
m_guid = 00000000-0000-0000-0000-000000000000
dbi_differentialBaseGuid = 555d80f3-3003-419b-a1eb-c1b059f76d22
dbi_firstSysIndexes = 0001:00000014
dbi_oldestBackupXactLSN = 0:0:0 (0x00000000:00000000:0000)
dbi_versionChangeLSN = 0:0:0 (0x00000000:00000000:0000)
dbi_mdUpgStat =
0x0004
dbi_category = 0x0000000000000000
dbi_safetySequence = 0
dbi_dbMirrorId = 00000000-0000-0000-0000-000000000000
dbi_pageUndoLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_pageUndoState
= 0
dbi_disabledSequence = 0
dbi_dbmRedoLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_dbmOldestXactLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_CloneCpuCount
= 0
dbi_CloneMemorySize = 0
dbi_updSysCatalog = 1900-01-01 00:00:00.000
dbi_LogBackupChainOrigin = 15034:5896:37 (0x00003aba:00001708:0025)
dbi_dbccLastKnownGood = 1900-01-01 00:00:00.000
dbi_roleSequence =
0
dbi_dbmHardenedLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_localState = 0
dbi_safety = 0
dbi_modDate = 2013-04-12 12:15:13.890
dbi_verRDB = 184552376
dbi_lazyCommitOption = 0
dbi_svcBrokerGUID = b5fe6d7f-a888-4c3f-af66-3e264784ba17
dbi_svcBrokerOptions = 0x00000000
dbi_dbmLogZeroOutstanding = 0
dbi_dbmLastGoodRoleSequence = 0
dbi_dbmRedoQueue =
0
dbi_dbmRedoQueueType = 0
dbi_rmidRegistryValueDeleted = 0
dbi_dbmConnectionTimeout = 0
dbi_fragmentId = 0
dbi_AuIdNext = 1099511628233
dbi_MinSkipLsn = 0:0:0 (0x00000000:00000000:0000)
dbi_commitTsOfcheckptLSN = 0
dbi_dbEmptyVersionState = 0
dbi_CurrentGeneration = 0
dbi_EncryptionHistory
Scan 0
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
EncryptionScanInfo:ScanId = 0
Scan 1
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
EncryptionScanInfo:ScanId = 0
Scan 2
hex (dec) = 0x00000000:00000000:0000 (0:0:0)
EncryptionScanInfo:ScanId = 0
dbi_latestVersioningUpgradeLSN = 18:81:67 (0x00000012:00000051:0043)
dbi_PendingRestoreOutcomesId = 00000000-0000-0000-0000-000000000000
dbi_ContianmentState = 0
dbi_splitAGE = 0
DBCC execution completed. If DBCC printed error messages, contact your system
administrator.
Question33. Where do you write business logic in the application (as Ad-hoc SQL / in line query) or in
the database (Stored Procedures)? Why?
Answer
Mostly I used to write stored procedures because they are easier for us to test and fine tune. If you
want to change the stored procedure in future it is easy. You can just change it and deploy on the
server required and test the application. You dont need to open the application, change the query and
deploy it and after that you can test it. You can save lot of time in this case.
Stored Procedures don't provide much advantage in security cases, unless restricting access to rows in
complex manner. They are better to manage and change in future. Sps are better for complex
operations.
So, which one is better to use SPs or ad-hoc SQL? The answer is "it depends."
Question34. Whats the fastest way to insert thousands of records into the database?
Answer-
1. Use BULK INSERT - it is designed for exactly for huge insertions and significantly increases the
speed of inserts.
2. You can also use Batch inserts. That is, only send 1000 rows at a time, rather than one row at a
time, so you hugely reduce round trips/server calls.
3. You can also use SQL BCP utility.
Question35. Whats the difference between a primary key and a clustered index?
Sr.No
Clustered Index
Primary Key
3.
SELECT TOP 10
r.session_id
,
r.start_time
,
TotalElapsedTime_ms = r.total_elapsed_time
,
,
,
,
,
,
,
,
,
,
,
,
r.[status]
r.command
DatabaseName = DB_Name(r.database_id)
r.wait_type
r.last_wait_type
r.wait_resource
r.cpu_time
r.reads
r.writes
r.logical_reads
t.[text] AS [executing batch]
SUBSTRING(
t.[text], r.statement_start_offset / 2,
(
CASE WHEN r.statement_end_offset = -1 THEN DATALENGTH
(t.[text])
ELSE r.statement_end_offset
END - r.statement_start_offset ) / 2
) AS [executing statement]
,
p.query_plan
FROM
sys.dm_exec_requests r
CROSS APPLY
sys.dm_exec_sql_text(r.sql_handle) AS t
CROSS APPLY
sys.dm_exec_query_plan(r.plan_handle) AS p
ORDER BY
r.total_elapsed_time DESC;
Question40. What happens when a transaction runs on SQL server? Lets say simple update statement
Update Table set col1 = value where col2 = value
Update Lock is used in SQL Server when performing an UPDATE statement. When you check the execution
plan, you can see that such a plan always consists of 3 parts:
Reading data
Get New Value
Write data
When SQL Server initially reads the data to be changed in the first part of the query plan, Update Locks are
acquired on the individual records. And finally these Update Locks are converted to Exclusive (X) Locks when
the data is changed in the third part of the query plan. UPDATE Locks are required to avoid deadlock situations
in UPDATE query plans.