Sie sind auf Seite 1von 88

Remove Delete Duplicate Records Or Rows - Sql Server

Posted by amiT jaiN


Remove or Delete duplicate records or rows from ms sql server database table.
In this post i am going to describe different methods of deleting duplicate records or rows from sql
server database table.
I am using Employees table with FirstName and Department columns.
First Method.
Delete duplicate recordsrows b! creati"# ide"tit! colum".
duplicate records in table looks like shown in first image.
First of all we need to create a ide"tit! colum" in our table by usi"# code me"tio"ed below.
nd table will look like image on the left.
!"#E$ #%"E dbo.Employees DD ID IN# IDEN#I#&'!(!)
Now write this quer! to delete duplicate rows.
!DE"E#E F$*+ dbo.Employees
,-.E$E ID N*# IN '/E"E0# +IN'ID)
1F$*+ dbo.Employees 2$*3P %& FirstName(Department)
#his should remove all duplicate records from table.
Seco"d Method.
Delete duplicate records usi"# Row$Number%&
If you do not want to make any changes in table design or don4t want to create identity column on
table then you can remove duplicate records usi"# Row$Number i" sql server '(() o"wards.
for this write below mentioned code and e5ecute.
!-I#. Duplicate$ecords /
,'
1/E"E0# 6(row7number') *8E$'P$#I#I*N %& FirstName(Department *$DE$ %&
9
:FirstName)
;/ $owNumber F$*+ dbo.Employees
<)
=DE"E#E F$*+ Duplicate$ecords -.E$E $owNumber>!
#his should remove all duplicate records from table.
Third Method.
Remove duplicate rowsRecords usi"# temporar! table
3se below mentioned code to delete duplicates by moving them to temporary table using
DI/#IN0#.
!/E"E0# DI/#IN0# 6 IN#* #emp#able F$*+ dbo.Employees
,2$*3P %& FirstName(Department
1.8IN2 0*3N#'FirstName) > !
9
:DE"E#E dbo.Employees -.E$E FirstName
;IN '/E"E0# FirstName F$*+ #emp#able)
<
=IN/E$# dbo.Employees /E"E0# 6 F$*+ #emp#able
?D$*P #%"E #emp#able
nd result will be as shown.
.ave fun.
Query to delete duplicate Records in SQL
/uppose we have the situation to delete some duplicate records in our table. /uppose consider one
table
create table @#est
'
EmpID int(
EmpName varchar':A)
)
BInsert the $ecords into @#est table
insert into @#est values'!(CDayaD)
insert into @#est values'!(CDayaD)
insert into @#est values'!(CDayaD)
Now i have two duplicate records inserted and i want to delete those records. #he following query
will delete the duplicate records
BEuery to Delete Duplicate $ecords
-I#. Emp / '/E"E0# $*-7N3+%E$ ' ) *8E$ ' P$#I#I*N %& EmpID( EmpName *$DE$
%& EmpID ) / $N3+ F$*+ @#est )
DE"E#E F$*+ Emp -.E$E $N3+ > !
Max value among three columns
#he following query will fetch you the ma5 value among three columns
0reate #able @test 'Name 0har'!A)( Ety! IN#( E#&, IN#( E#&1 IN#)
Insert into @#est 'Name( E#&!( E#&,( E#&1) 8alues 'D+onitorC(!,(!1(!!)
Insert into @#est 'Name( E#&!( E#&,( E#&1) 8alues 'DFey%oardC(=(<(;)
Insert into @#est 'Name( E#&!( E#&,( E#&1) 8alues 'D+ouseC(1(,(:)
*+uer! to #et the ma, amo"# three colum"s
select GnameH('select ma5'Ety)
from 'select E#&! as Ety
union all
select E#&, as Ety
union all
select E#&1) as Ety) as +a5i
from @test
-ow to fi"d out rece"tl! ru" queries i" S+. Server '(()/
/elect dm/tats.last7e5ecution7time as D"ast E5ecuted #imeC(dm#e5t.te5t as DE5ecuted EueryC from
sys.dm7e5ec7query7stats as dm/tats 0ross apply sys.dm7e5ec7sql7te5t'dm/tats.sql7handle) as
dm#e5t *rder %ydm/tats.last7e5ecution7time desc
Ru" the followi"# quer! to e,port data from sql server to e,cel
3/E Gdventure-orksH
IN/E$# IN#* *PEN$*-/E# 'D+icrosoft.Iet.*"ED%.9.A( DE5cel
=.AJDatabaseKcLM#est.5lsJC(D/elect 6 from GEmpNHD)
/elect EmployeeID( #itle F$*+ .uman$esources.Employee
+uer! to fi"d Object Ow"er/
/E"E0#
.N+E / G*%IE0#H(
%.N+E / G/0.E+H(
3/E$7N+E'I/N3""'.P$IN0IP"7ID(%.P$IN0IP"7ID)) as G*-NE$H
F$*+
/&/.""7*%IE0#/ INNE$ I*IN /&/./0.E+/ %
*N ./0.E+7ID K %./0.E+7ID
-.E$E .N+E K 0object "ame here1
+uer! to select disti"ct records without duplicate
select EmpId(EmpName from Emp group by EmpID(EmpName having count'6)>!
234OT
select 5 from products
2roduct3
D 2roductName6ear TotalDue
<A, +outain%lack ,AA: !,9:;;
<A1 Pen ,AA: 9:1,!
<A9 2loppy ,AA1 9:9=<:
<A: -atch ,AA1 9:;:=;
<A; Disc ,AA9 9:;:9:;
<A< #ime ,AA9 9:;,!;9
Now !ou wa"t to 7ross-tab !ear based results
select 2roduct3D82roductName8S9M%case The6ear whe" '((: the" TotalDue else ( e"d& as
;'((:<8S9M%case The6ear whe" '((= the" TotalDue else ( e"d& as ;'((:<8S9M%case The6ear
whe" '(() the" TotalDue else ( e"d& as ;'(()<from products#roup b!
2roduct3D82roductName
%or same we ca" achive usi"# 234OT &
*pivot
select 2roduct3D82roductName8;'((:<8;'((=<8;'(()< from products
pivot
%sum%TotalDue& for The6ear i"%;'((:<8;'((=<8;'(()<&& as 24T
*Results
2roduct3
D 2roductName'((: '((= '(()
<A, +outain%lack N3"" N3"" !,9:;;
<A1 Pen N3"" N3"" 9:1,!
<A9 2loppy 9:9=<: N3"" N3""
<A: -atch 9:;:=; N3"" N3""
<A; Disc N3"" 9:;:9:; N3""
<A< #ime N3"" 9:;,!;9 N3""
To Fi"d all depe"de"c! objects a"d its t!pe
select ObjectName > object$"ame%id&8b.T!pe$Desc Object$t!pe8 Depe"dObjectName >
object$"ame%depid&8c.T!pe$Desc Depe"dObject$T!pe from s!s.s!sdepe"ds a i""er joi"
s!s.objects b o" a.id > b.object$id i""er joi" s!s.objects c o" a.depid > c.object$id
Few 3"teresti"# +uestio"s a"d co"cepts
There are : tables Titles8 ?uthors a"d Title-?uthors %chec@ 29AS db&. Brite the quer! to #et
the author "ame a"d the "umber of boo@s writte" b! that author8 the result should start from
the author who has writte" the ma,imum "umber of boo@s a"d e"d with the author who has
writte" the mi"imum "umber of boo@s.
/E"E0# authors.au7lname( 0*3N#'6) / %ooks0ount F$*+ authors INNE$ I*IN titleauthor *N
authors.au7id K titleauthor.au7id INNE$ I*IN titles *N titles.title7id K titleauthor.title7id 2$*3P %&
authors.au7lname *$DE$ %& %ooks0ount DE/0
Brite a S+. +uer! to fi"d first da! of mo"th/
/E"E0# D#EN+E'dw( D#EDD'dd( O D#EP$#'dd( 2E#D#E')) P !( 2E#D#E'))) /
FirstDay
There is a table da!$temp which has three colum"s da!id8 da! a"d temperature. -ow do 3
write a quer! to #et the differe"ce of temperature amo"# each other for seve" da!s of a
wee@/
/E"E0# a.dayid( a.dday( a.tempe( a.tempe O b.tempe / Difference F$*+ day7temp a INNE$
I*IN day7temp b *N a.dayid K b.dayid P !
or this quer!
/elect a.day( a.degreeOb.degree from temperature a( temperature b where a.idKb.idP!
There is a table which co"tai"s the "ames li@e this. aC8 a'8 a:8 a:8 a=8 aC8 aC8 a' a"d their
salaries. Brite a quer! to #et #ra"d total salar!8 a"d total salaries of i"dividual emplo!ees i"
o"e quer!.
/E"E0# empid( /3+'salary) / salaryF$*+ employee2$*3P %& empid -I#. $*""3P
*$DE$ %& empid
9pdate Bith 7ase
EmpI
D EmpName 2ender
! $aQa +ale
, $ani Female
3" the above table usi"# o"e quer! u "eed to cha"#e De"der male to female a"d who is
female "eed to cha"#e male.
3PD#E Emp! /E# 2enderK0/E 2ender -.EN D+aleC #.EN DFemaleC-.EN DfemaleC #.EN
D+aleCENDJ
+uer! to fi"d the ma,imum salar! of a" emplo!ee
/elect 6 from Employee where salary K '/elect ma5'/alary) from Employee)
+uer! to Fi"d the Nth Ma,imum Salar!
/elect 6 From Employee E! -here '1O!) K '/elect 0ount'Distinct'E,./alary)) From Employee E,
-here E,./alary > E!./alary)
+uer! to Fi"d the '"d Ma,imum Salar!
/E"E0# /"$& F$*+ E+P"*&EE-.E$E /"$&K'/E"E0# +R'/"$&) F$*+
E+P"*&EE -.E$E /"$& S> '/E"E0# +R '/"$&) F$*+ E+P"*&EE))
select ma5'salary) as /alary from Emplo where salaryTK'select ma5'salary) from Emplo)
/E"E0# +R'E!.salary) F$*+ emplo E! ( emplo E,-.E$E E!.salaryS E,.salary
7reati"# a forei#"-@e! co"strai"t betwee" colum"s of two tables defi"ed with two differe"t
datat!pes will produce a" error
?"s E 6es
3mporta"t co"cepts
Bhat1s the differe"ce betwee" a primar! @e! a"d a u"ique @e!/
%oth primary key and unique enforce uniqueness of the column on which they are defined. %ut by
default primary key creates a clustered inde5 on the column( where are unique creates a
nonclustered inde5 by default. nother maQor difference is that( primary key doesnCt allow N3""s(
but unique key allows one N3"" only.
Defi"e ca"didate @e!8 alter"ate @e!8 composite @e!.
candidate key is one that can identify each row of a table uniquely. 2enerally a candidate key
becomes the primary key of the table. If the table has more than one candidate key( one of them will
become the primary key( and the rest are called alternate keys. key formed by combining at least
two or more columns is called composite key.
Bhat is a tra"sactio" a"d what are ?73D properties/
transaction is a logical unit of work in which( all the steps must be performed or none. 0ID
stands for tomicity( 0onsistency( Isolation( Durability. #hese are the properties of a transaction.
For more information and e5planation of these properties( see /E" /erver books online or any
$D%+/ fundamentals te5t book. E5plain different isolation levels n isolation level determines the
degree of isolation of data between concurrent transactions. #he default /E" /erver isolation level
is $ead 0ommitted. .ere are the other isolation levels 'in the ascending order of isolation)L $ead
3ncommitted( $ead 0ommitted( $epeatable $ead( /erialiUable. /ee /E" /erver books online for
an e5planation of the isolation levels. %e sure to read about /E# #$N/0#I*N I/*"#I*N
"E8E"( which lets you customiUe the isolation level at the connection level. $ead 0ommitted B
transaction operating at the $ead 0ommitted level cannot see changes made by other transactions
until those transactions are committed. t this level of isolation( dirty reads are not possible but
nonrepeatable reads and phantoms are possible. $ead 3ncommitted B transaction operating at
the $ead 3ncommitted level can see uncommitted changes made by other transactions. t this
level of isolation( dirty reads( nonrepeatable reads( and phantoms are all possible. $epeatable
$ead B transaction operating at the $epeatable $ead level is guaranteed not to see any changes
made by other transactions in values it has already read. t this level of isolation( dirty reads and
nonrepeatable reads are not possible but phantoms are possible. /erialiUable B transaction
operating at the /erialiUable level guarantees that all concurrent transactions interact only in ways
that produce the same effect as if each transaction were entirely e5ecuted one after the other. t
this isolation level( dirty reads( nonrepeatable reads( and phantoms are not possible.
Bhat1s the differe"ce betwee" DF.FTF T?A.F a"d TR9N7?TF T?A.F comma"ds/
DE"E#E #%"E is a logged operation( so the deletion of each row gets logged in the transaction
log( which makes it slow. #$3N0#E #%"E also deletes all the rows in a table( but it wonCt log the
deletion of each row( instead it logs the deallocation of the data pages of the table( which makes it
faster. *f course( #$3N0#E #%"E can be rolled back. #$3N0#E #%"E is functionally
identical to DE"E#E statement with no -.E$E clauseL both remove all rows in the table. %ut
#$3N0#E #%"E is faster and uses fewer system and transaction log resources than DE"E#E.
#he DE"E#E statement removes rows one at a time and records an entry in the transaction log for
each deleted row. #$3N0#E #%"E removes the data by deallocating the data pages used to
store the tableCs data( and only the page deallocations are recorded in the transaction log.
#$3N0#E #%"E removes all rows from a table( but the table structure and its columns(
constraints( inde5es and so on remain. #he counter used by an identity for new rows is reset to the
seed for the column. If you want to retain the identity counter( use DE"E#E instead. If you want to
remove table definition and its data( use the D$*P #%"E statement. &ou cannot use #$3N0#E
#%"E on a table referenced by a F*$EI2N FE& constraintJ instead( use DE"E#E statement
without a -.E$E clause. %ecause #$3N0#E #%"E is not logged( it cannot activate a trigger.
#$3N0#E #%"E may not be used on tables participating in an inde5ed view
Bhat are the steps !ou will ta@e to improve performa"ce of a poor performi"# quer!/
#his is a very open ended question and there could be a lot of reasons behind the poor
performance of a query. %ut some general issues that you could talk about would beL No inde5es(
table scans( missing or out of date statistics( blocking( e5cess recompilations of stored procedures(
procedures and triggers without /E# N*0*3N# *N( poorly written query with unnecessarily
complicated Qoins( too much normaliUation( e5cess usage of cursors and temporary tables. /ome of
the toolsVways that help you troubleshooting performance problems areL /E# /.*-P"N7""
*N( /E# /.*-P"N7#ER# *N( /E# /##I/#I0/ I* *N( /E" /erver Profiler( -indows N# V
,AAA Performance monitor( 2raphical e5ecution plan in Euery nalyUer
Bhat is a deadloc@ a"d what is a live loc@/ -ow will !ou #o about resolvi"# deadloc@s/
Deadlock is a situation when two processes( each having a lock on one piece of data( attempt to
acquire a lock on the otherCs piece. Each process would wait indefinitely for the other to release the
lock( unless one of the user processes is terminated. /E" /erver detects deadlocks and terminates
one userCs process. livelock is one( where a request for an e5clusive lock is repeatedly denied
because a series of overlapping shared locks keeps interfering. /E" /erver detects the situation
after four denials and refuses further shared locks. livelock also occurs when read transactions
monopoliUe a table or page( forcing a write transaction to wait indefinitely. 0heck out /E#
DED"*0F7P$I*$I#& and W+inimiUing DeadlocksX in /E" /erver books online
Bhat are statistics8 u"der what circumsta"ces the! #o out of date8 how do !ou update them/
/tatistics determine the selectivity of the inde5es. If an inde5ed column has unique values then the
selectivity of that inde5 is more( as opposed to an inde5 with nonOunique values. Euery optimiUer
uses these inde5es in determining whether to choose an inde5 or not while e5ecuting a query.
/ome situations under which you should update statisticsL !) If there is significant change in the key
values in the inde5 ,) If a large amount of data in an inde5ed column has been added( changed( or
removed 'that is( if the distribution of key values has changed)( or the table has been truncated
using the #$3N0#E #%"E statement and then repopulated 1) Database is upgraded from a
previous version. "ook up /E" /erver books online for the following commandsL 3PD#E
/##I/#I0/( /##/7D#E( D%00 /.*-7/##I/#I0/( 0$E#E /##I/#I0/( D$*P
/##I/#I0/( sp7autostats( sp7createstats( sp7updatestats
3"de, OptimiGatio" tips
Y Every inde5 increases the time in takes to perform IN/E$#/( 3PD#E/ and DE"E#E/( so the
number of inde5es should not be very much. #ry to use ma5imum 9O: inde5es on one table( not
more. If you have readOonly table( then the number of inde5es may be increased.
Y Feep your inde5es as narrow as possible. #his reduces the siUe of the inde5 and reduces the
number of reads required to read the inde5.
Y #ry to create inde5es on columns that have integer values rather than character values.
Y If you create a composite 'multiOcolumn) inde5( the order of the columns in the key are very
important. #ry to order the columns in the key as to enhance selectivity( with the most selective
columns to the leftmost of the key.
Y If you want to Qoin several tables( try to create surrogate integer keys for this purpose and create
inde5es on their columns.
Y 0reate surrogate integer primary key 'identity for e5ample) if your table will not have many insert
operations.
Y 0lustered inde5es are more preferable than nonclustered( if you need to select by a range of
values or you need to sort results set with 2$*3P %& or *$DE$ %&.
Y If your application will be performing the same query over and over on the same table( consider
creating a covering inde5 on the table.
Y &ou can use the /E" /erver Profiler 0reate #race -iUard with WIdentify /cans of "arge #ablesX
trace to determine which tables in your database may need inde5es. #his trace will show which
tables are being scanned by queries instead of using an inde5.
Y &ou can use sp7+/foreachtable undocumented stored procedure to rebuild all inde5es in your
database. #ry to schedule it to e5ecute during 0P3 idle time and slow production periods.
sp7+/foreachtable Zcommand!KXprint D[C D%00 D%$EINDER 'D[C)X
F,plai" about 7lustered a"d "o" clustered i"de,/ -ow to choose betwee" a 7lustered 3"de,
a"d a No"-7lustered 3"de,/
#here are clustered and nonclustered inde5es. clustered inde5 is a special type of inde5 that
reorders the way records in the table are physically stored. #herefore table can have only one
clustered inde5. #he leaf nodes of a clustered inde5 contain the data pages.
nonclustered inde5 is a special type of inde5 in which the logical order of the inde5 does not
match the physical stored order of the rows on disk. #he leaf nodes of a nonclustered inde5 does
not consist of the data pages. Instead( the leaf nodes contain inde5 rows.
0onsider using a clustered inde5 forL
o 0olumns that contain a large number of distinct values.
o Eueries that return a range of values using operators such as %E#-EEN( >( >K( S( and SK.
o 0olumns that are accessed sequentially.
o Eueries that return large result sets.
NonOclustered inde5es have the same %Otree structure as clustered inde5es( with two significant
differencesL
o #he data rows are not sorted and stored in order based on their nonOclustered keys.
o #he leaf layer of a nonOclustered inde5 does not consist of the data pages. Instead( the leaf nodes
contain inde5 rows. Each inde5 row contains the nonOclustered key value and one or more row
locators that point to the data row 'or rows if the inde5 is not unique) having the key value.
o Per table only ,9? non clustered inde5es
-ow ma"! t!pes of Hoi"s/
Ioins can be categoriUed asL
Y Inner Qoins 'the typical Qoin operation( which uses some comparison operator like K or S>). #hese
include equiOQoins and natural Qoins.
Inner Qoins use a comparison operator to match rows from two tables based on the values in
common columns from each table. For e5ample( retrieving all rows where the student identification
number is the same in both the students and courses tables.
Y *uter Qoins. *uter Qoins can be a left( a right( or full outer Qoin.
*uter Qoins are specified with one of the following sets of keywords when they are specified in the
F$*+ clauseL
Y "EF# I*IN or "EF# *3#E$ I*IN O#he result set of a left outer Qoin includes all the rows from the
left table specified in the "EF# *3#E$ clause( not Qust the ones in which the Qoined columns match.
-hen a row in the left table has no matching rows in the right table( the associated result set row
contains null values for all select list columns coming from the right table.
Y $I2.# I*IN or $I2.# *3#E$ I*IN B right outer Qoin is the reverse of a left outer Qoin. ll rows
from the right table are returned. Null values are returned for the left table any time a right table row
has no matching row in the left table.
Y F3"" I*IN or F3"" *3#E$ I*IN B full outer Qoin returns all rows in both the left and right
tables. ny time a row has no match in the other table( the select list columns from the other table
contain null values. -hen there is a match between the tables( the entire result set row contains
data values from the base tables.
Y 0ross Qoins B 0ross Qoins return all rows from the left table( each row from the left table is
combined with all rows from the right table. 0ross Qoins are also called 0artesian products. '
0artesian Qoin will get you a 0artesian product. 0artesian Qoin is when you Qoin every row of one
table to every row of another table. &ou can also get one by Qoining every row of a table to every
row of itself.
Bhat are the differe"ce betwee" a fu"ctio" a"d a stored procedure/
Functions can be used in a select statement where as procedures cannot
Procedure takes both input and output parameters but Functions takes only input parameters
Functions cannot return values of type te5t( nte5t( image \ timestamps where as procedures can
Functions can be used as user defined datatypes in create table but procedures cannot
666EgLOcreate table Stablename>'name varchar'!A)(salary getsal'name))
.ere getsal is a user defined function which returns a salary type( when table is created no storage
is allotted for salary type( and getsal function is also not e5ecuted( %ut when we are fetching some
values from this table( getsal function getCs e5ecuted and the return
#ype is returned as the result set.
Bhat is the basic fu"ctio"s for master8 msdb8 tempdb databases/
+icrosoft] /E" /erver ,AAA systems have four system databasesL
Y master B #he master database records all of the system level information for a /E" /erver
system. It records all login accounts and all system configuration settings. master is the database
that records the e5istence of all other databases( including the location of the database files.
Y tempdb B tempdb holds all temporary tables and temporary stored procedures. It also fills any
other temporary storage needs such as work tables generated by /E" /erver. tempdb is reOcreated
every time /E" /erver is started so the system starts with a clean copy of the database.
%y default( tempdb autogrows as needed while /E" /erver is running. If the siUe defined for
tempdb is small( part of your system processing load may be taken up with autogrowing tempdb to
the siUe needed to support your workload each time to restart /E" /erver. &ou can avoid this
overhead by using "#E$ D#%/E to increase the siUe of tempdb.
Y model B #he model database is used as the template for all databases created on a system. -hen
a 0$E#E D#%/E statement is issued( the first part of the database is created by copying in
the contents of the model database( then the remainder of the new database is filled with empty
pages. %ecause tempdb is created every time /E" /erver is started( the model database must
always e5ist on a /E" /erver system.
Y msdb B #he msdb database is used by /E" /erver gent for scheduling alerts and Qobs( and
recording operators.
Cst Normal Form %CNF&
DefinitionL table 'relation) is in !NF if
!. #here are no duplicated rows in the table.
,. Each cell is singleOvalued 'i.e.( there are no repeating groups or arrays).
1. Entries in a column 'attribute( field) are of the same kind.
NoteL #he order of the rows is immaterialJ the order of the columns is immaterial.
NoteL #he requirement that there be no duplicated rows in the table means that the table has a key
'although the key might be made up of more than one column^even( possibly( of all the columns).
$ule !L Eliminate $epeating 2roups. +ake a separate table for each set of related attributes( and
give each table a primary key.
'"d Normal Form %'NF&
DefinitionL table is in ,NF if it is in !NF and if all nonOkey attributes are dependent on all of the
key.
NoteL /ince a partial dependency occurs when a nonOkey attribute is dependent on only a part of
the 'composite) key( the definition of ,NF is sometimes phrased as( W table is in ,NF if it is in !NF
and if it has no partial dependencies.X
$ule ,L Eliminate $edundant Data. If an attribute depends on only part of a multiOvalued key(
remove it to a separate table.
:rd Normal Form %:NF&
DefinitionL table is in 1NF if it is in ,NF and if it has no transitive dependencies.
$ule 1L Eliminate 0olumns Not Dependent on Fey. If attributes do not contribute to a description of
the key( remove them to a separate table.
Ao!ce-7odd Normal Form %A7NF&
DefinitionL table is in %0NF if it is in 1NF and if every determinant is a candidate key.
=th Normal Form %=NF&
DefinitionL table is in 9NF if it is in %0NF and if it has no multiOvalued dependencies.
$ule 9L Isolate Independent +ultiple $elationships. No table may contain two or more lLn or nLm
relationships that are not directly related.
)th Normal Form %)NF&
DefinitionL table is in :NF( also called WProQectionOIoin Normal FormX 'PINF)( if it is in 9NF and if
every Qoin dependency in the table is a consequence of the candidate keys of the table.
$ule :L Isolate /emantically $elated +ultiple $elationships. #here may be practical constraints on
information that Qustify separating logically related manyOtoOmany relationships.
Domai"-Ie! Normal Form %DINF&
DefinitionL table is in DFNF if every constraint on the table is a logical consequence of the
definition of keys and domains.
I have an interesting query to find nth +RV+IN /alary etc. It goes like this(
/E"E0# DI/#IN0# 'a./alary) F$*+ Emp! a -.E$E \N K'/E"E0# 0*3N# 'DI/#IN0#
'b./alary)) F$*+ Emp! b -.E$E a./alarySKb./alary)
Enter value for 4\N4
Bhat is the use of 7O?.FS7F i" S+. Server
"et us understand the use of 7O?.FS7F with the help of an e5ample.
In this e5ample( the 7a"didate table is shown to include three columns with information about a
0andidateL
!. 0andidate7id
,. PrimaryEmail
1. /econdaryEmail
7O?.FS7F in the /E"E0# statement below( selects the PrimaryEmail if it is not null. If the
PrimaryEmail is null then /econdaryEmail will be selected. If both PrimaryEmail and
/econdaryEmail is present then only PrimaryEmail is selected. /o( 0*"E/0E returns the first
nonnull column among the list of columns passed. If both PrimaryEmail and /econdaryEmail is
N3""( 0*"E/0E returns N3"".
7O?.FS7F can also be used in Qoins as shown in the e5ample below. If the 0andidate table has a
non null value in the Email column( then the value is selected. If the Email column is null in the
0andidate #able then( 0ompanyEmail from 0andidate0ompany #able is selected.
?dva"ta#es of stored procedures
#his is a very common sql server interview question. #here are several advantages of using stored
procedures over adhoc queries( as listed below.
!. Aetter 2erforma"ce L /tored procedures are precompiled and hence run much faster than
adhoc queries
,. Aetter Securit! L pplications making use of dynamically built adhoc sql queries are highly
susceptible to sql inQection attacks( where as /tored Procedures can avoid /E" inQection attacks
completely.
1. Reduced Networ@ TrafficL /tored procedures can reduce network traffic to a very great e5tent
when compared with adhoc sql queries. -ith stored procedures( you only need to send the name of
the procedure between client and server. Imagine the amount of network bandwith that can be
saved especially if the stored procedure contains !AAA to ,AAA lines of /E".
9. Aetter Mai"tai"a"ce a"d Reusabilit!L /tored procedures can be used any where in the
application. It is easier to maintain a stored procedure that is used on several pages as the
modfifcations Qust need to be changed at one place where the stored procedure is defined. *n the
other hand( maintaining an adhoc sql query that4s used on several pages is tedious and error prone(
as we have to make modifications on each and every page.
S+. Server 3"terview +uestio"s o" tri##ers
Bhat is a Tri##er i" S+. Server/
#rigger is a database obQect that is attached to a table. In many aspects it is similar to a stored
procedure. s a matter of fact( triggers are often referred to as a _special kind of stored procedure._
#he main difference between a trigger and a stored procedure is that the former is attached to a
table and is only fired when an IN/E$#( 3PD#E or DE"E#E occurs.
Bhat are the two t!pes of Tri##ers i" S+. Server/
C. ?fter Tri##ers E Fired after Insert( 3pdate and Delete operations on a table.
'. 3"stead of Tri##ersE Fired instead of Insert( 3pdate and Delete operations on a table.
Bhat are the special tables used b! Tri##ers i" S+. Server/
Tri##ers make use of two special tables called i"serted and deleted. #he i"serted table contains
the data referenced in an IN/E$# before it is actually committed to the database. #he deleted table
contains the data in the underlying table referenced in a DE"E#E before it is actually removed from
the database. -hen an 3PD#E is issued both tables are used. +ore specifically( the new data
referenced in the 3PD#E statement is contained in i"serted table and the data that is being
updated is contained in deleted table.
Dive a real time e,ample for tri##ers usa#e/
It is recomended to avoid triggers in a real time environment. #here is one scenario I can think of
why you may want to use triggers in a real time environment. "et us use an e5ample to understand
this.
I have , tables( tbl2erso" and tblDe"der as shown below. De"der3d is the foriegn key in
tbl2erso" table.
Now create a view based on the above , tables as shown below.
/elect 6 from vB2erso"s will give us the result as shown below.
Now update the view the following query. #his will change the 2ender #e5t to Female in tblDe"der
table for Id K !. #his is not what we have e5pected.
3pdate tbl2ender /et 2enderK4Female4 where IdK!
#he base tables are updated incorrectly. /o( /elect 6 from vB2erso"s will give us the result as
shown below.
#o update the base tables correctly( you can create an 3NSTF?D OF trigger on the view as shown
below.
Now run the query below which will update the underlying base tables correctly.
3pdate v-Persons /et 2enderK4Female4 -here IdK!
/elect 6 from v-Persons( will show the correct result set as shown below. #he 3NSTF?D OF trigger
has correctly updated the 2enderId in tblPerson table.
/o( 3"stead of tri##ers can be used to facilitate updati"# 4iews that are based o" multiple base
tables.
S+. Server 3"terview +uestio"s o" Temporar! Tables
What are the 2 types of Temporary Tables in SQL Server?
1. Local Temporary Tables
2. Global Temporary Tables
What is the difference between Local and Global Temporary Tables?
Local Temporary Tables:
1. Prefixed with a single pound sign (#).
2. Local temporary tables are visible to that session of !L erver which has created it.
. Local temporary tables are automatically dropped" when the session that created the temporary tables is
closed.
Global Temporary Tables:
1. Prefixed with two pound signs (##).
2. Global temporary tables are visible to all the !L server sessions.
. Global temporary tables are also automatically dropped" when the session that created the temporary tables
is closed.
!an yo" create forei#n $ey constraints on temporary tables?
#o
%o yo" have to man"ally delete temporary tables?
#o" temporary tables are automatically dropped" when the session that created the temporary tables is closed.
$ut if you maintain a persistent connection or if connection pooling is enabled" then it is better to explicitly
drop the temporary tables you have created.
%owever" &t is generally considered a good coding practice to explicitly drop every temporary table you
create.
&n which database' the temporary tables #et created?
T'(P)$ database.
(ow can & chec$ for the e)istence of a temporary table?
3sually it is best to create a temp table through the create function.
For instance if you were to check if that temp table e5isted and then dropVcreate a new one and
insert data it would go something like this.
IF obQect7ID'4tempdb..@@temptable4) I/ N*# N3""
D$*P #%"E @@#E+P#%"E
0$E#E #%"E @@#E+P#%"E
IN/E$# @@#E+P#%"E
/E"E0# e.E+P"*&EE
from employee e
where e.employeename K frank
#his would check for the table and drop it if it e5ists then would create a new global temp table
'indicated by the @@) and insert all employees with the name frank into this temp table.
Aasic S+. Server 3"terview +uestio"s
F,plai" DM.8 DD.8 D7. a"d T7. stateme"ts with e,amples/
DM.L D+" stands for Data +anipulation "anguage. D+" is used to retrieve( store( modify( delete(
insert and update data in database.
F,amples of D+" statementsL /E"E0#( 3PD#E( IN/E$#( DE"E#E statements.
DD.L DD" stands for Data Definition "anguage. DD" is used to create and modify the structure of
database obQects.
F,amplesL 0$E#E( "#E$( D$*P statements.
D7.L D0" stands for Data 0ontrol "anguage. D0" is used to create roles( grant and revoke
permissions( establish referential integrity etc.
F,amplesL 2$N#( $E8*FE statements
T7.L #0" stands for #ransactional 0ontrol "anguage. #0" is used to manage transactions within a
database.
F,amplesL 0*++I#( $*""%0F statements
Bhat is the differe"ce betwee" Drop8 Delete a"d Tru"cate stateme"ts i" S+. Server/
Drop8 Delete a"d Tru"cate O ll operations can be rolled back.
Delete is a logged operation( which means deleted rows are written to the transaction log.Tru"cate
is not a logged operation( which means deleted rows are not written to the transaction log.
-e"ce8 tru"cate is a little faster tha" Delete. &ou can have a where clause in Delete statement
where as #runcate statement cannot have a where clause. #runcate will delete all the rows in a
#able( but the structure of the table remains. Drop would delete all the rows including the structure
of the #able.
Please refer to the screen shot below for the differences summary snapshot between Drop( Delete
and #runcate statements in /E" /erver.
Bhat is 7ascadi"# refere"tial i"te#rit! co"strai"t/
7ascadi"# refere"tial i"te#rit! co"strai"ts allow you to define the actions +icrosoft /E" /erver
should take when a user attempts to delete or update a key to which an e5isting foreign keys point.
6ou ca" i"struct S+. Server to do the followi"#E
C. No ?ctio"E #his is the default behaviour. No ction specifies that if an attempt is made to delete
or update a row with a key referenced by foreign keys in e5isting rows in other tables( an error is
raised and the DE"E#E or 3PD#E is rolled back.
'. 7ascadeE /pecifies that if an attempt is made to delete or update a row with a key referenced by
foreign keys in e5isting rows in other tables( all rows containing those foreign keys are also deleted
or updated.
:. Set N9..E /pecifies that if an attempt is made to delete or update a row with a key referenced by
foreign keys in e5isting rows in other tables( all rows containing those foreign keys are set to N3"".
=. Set DefaultE /pecifies that if an attempt is made to delete or update a row with a key referenced
by foreign keys in e5isting rows in other tables( all rows containing those foreign keys are set to
default values.
D3ffere"ce betwee" primar! @e! a"d u"ique @e! i" S+. Server/
!. table can have only one primary key. *n the other hand a table can have more than one
unique key.
,. Primary key column does not accept any null values( where as a unique key column accept one
null value.
what is the importance of inde5 in a table[
$eL Inde5 are only way to make fast retrieve of data.s like in book if we know inde5 Number we
can find page easy./ame way if our table contain millions of records it makes easy and fast
search.#here are two types of inde5es cluster and non cluster.
+ost of the web sites say #runcate cannot be rolled back. #hat is not true. I have tested this on /E"
/erver ,AA=. #runcate can be rolled back. If you want try truncate yourself follow these steps.
/tep !L #runcate the table as part of the transaction( but do not commit.
%egin #ran
#runcate #able tblProduct
/tep ,L Now issue a select statement. &ou will see no rows in the table.
/elect 6 from tblProduct
/tep 1L Now issue a rollback statement( to rollback the truncate operation.
$ollback
/tep 9L Now issue a select statement. &ou will see all the rows in the table. #his proves that
#runcate can be rolled back.
/elect 6 from tblProduct
Bhat is the differe"ce betwee" a 9ser Defi"ed Fu"ctio" %9DF& a"d a Stored 2rocedure %S2&
i" S+. Server
1. Stored 2rocedure support deffered name resolution where as fu"ctio"s do not support
deffered name resolution.
'. 9ser Defi"ed Fu"ctio" can be used in a select statement where as you cannot use a
stored procedure in a select statement.
:. 9DF4s cannot return Image( #e5t where as a Stored2rocedure can return any datatype.
=. In general 9ser Defi"ed Fu"ctio"s are used for computations where as Stored
2rocedures are used for performing business logic.
). 9DF should return a value where as Stored 2rocedure need not.
J. 9ser Defi"ed Fu"ctio"s accept lesser number of input parameters than Stored
2rocedures. 9DF can have upto !A,1 input parameters where as a Stored 2rocedure can
have upto ,!AAA input parameters.
K. #emporary #ables can not be used in a 9DF where as a Stored2rocedure can use
#emporary #ables.
L. 9DF can not E5ecute Dynamic /E" where as a Stored 2rocedure can e5ecute Dynamic
/E".
M. 9ser Defi"ed Fu"ctio" does not support error handling where as Stored 2rocedure
support error handling. $I/EE$$*$ or ZZE$$*$ are not allowed in 9DFs.
&ou can not write P$IN# /tatement in 3DF
&ou can not write ERE0'4any sql statement4) inside 3DF
#he core difference is that function has no side effect which means that it cannot change anything
outside the function body.
Funcation can take only input parameter -here as /tored prcedure can take input and ouput
parameters.
/tored procedures are compiled obQects where as 3DF are not
2E#D#E can be used as the input parameter( but could not be used inside the function itself.
*ther built in /E" functions that cannot be used inside a 3ser Defined Function includeL $ND(
NE-ID( ZZ0*NN0E0#I*N/( ZZ#I+E#I0F/( and ZZP0F7/EN#. ny built in function that
is nonOdeterministic cannot be used inside the function itself.
Functions can be called from procedure whereas procedures cannot be called from function.
S+. Server 3"terview +uestio"s o" 4iews
Bhat is a 4iew i" S+. Server/
&ou can think of a view either as a compiled sql quer! or a virtual table. s a view represents a
virtual table( it does not physically store any data. -hen you query a view( you actually retrieve the
data from the underlying base tables.
Bhat are the adva"ta#es of usi"# views/
*r
Bhe" do !ou usuall! use views/
C. 8iews can be used to implement row level and column level security.
F,ample CE 0onsider the tblFmplo!ee table below. I don4t want some of the users to have access
to the salary column( but they should still be able to access ID( N+E and DEP# columns. If I grant
access to the table( the users will be able to see all the columns. /o( to achieve this( I can create a
view as shown in .isti"# C below. Now( grant access to the view and not the table. /o using views
we can provide colum" level securit!.
tblFmplo!ee
.isti"# C
0reate 8iew v-Employee
s
/elect ID( Name(
Dept
From tblEmployee
F,ample 'E "et us say( we have a few users who should be able to access only 3T emplo!ee
details and not any other dept. #o do this( I can create a view as shown in .isti"# ' below. Now(
grant access only to the view and not the table. /o using views we can provide row level security as
well.
.isti"# '
0reate 8iew v-I#Employees
s
/elect ID( Name( Dept
From tblEmployee
-here Dept K 4I#4
'. /implify the database schema to the users. &ou can create a view based on multiple tables
which Qoin columns from all these multiple tables so that they look like a single table.
:. 8iews can be used to present a##re#ated and summariGed data.
F,ample CE 0onsider the tblFmplo!ee table above. I want to aggregate the data as shown in the
image below. #o do this I can create a view as shown in .isti"# :. Now( you can simply issue a
select query against the view rather than writing a comple5 query every time you want to retrieve
the aggregated data.
.isti"# :
/elect Dept( 0ount'6) s
#otal
From tblEmployee
2roup %y Dept
7a" !ou create a view based o" other views/
6es8 !ou ca" create a view based o" other views. 9suall! we create views based o"
tables8 but it also possible to create views based o" views.
7a" !ou update views/
6es8 views ca" be updated. -owever8 updati"# a view that is based o" multiple tables8
ma! "ot update the u"derl!i"# tables correctl!. To correctl! update a view that is
based o" multiple tables !ou ca" ma@e use 3NSTF?D OF tri##ers i" S+. Server.
Bhat are i"de,ed views/
Or
Bhat are materialiGed views/
? view is a virtual table8 it does "ot co"tai" a"! ph!sical data. ? view is "othi"# more
tha" compiled S+. quer!. Fver! time8 we issue a select quer! a#ai"st a view8 we
actuall! #et the data from the u"derl!i"# base tables a"d "ot from the view8 as the
view itself does "ot co"tai" a"! data.
Bhe" !ou create a" i"de, o" a view8 the data #ets ph!sicall! stored i" the view. So8
whe" we issue a select quer! a#ai"st a" i"de,ed view8 the data is retrieved from the
i"de, without havi"# to #o to the u"derl!i"# table8 which will ma@e the select
stateme"t to wor@ sli#htl! faster. -owever8 the disadva"ta#e is8 3NSFRT8 92D?TF a"d
DF.FTF operatio"s will become a little slow8 because ever! time !ou i"sert or delete a
row from the u"derl!i"# table8 the view i"de, "eeds to be updated. 3"short8 DM.
operatio"s will have "e#ative impact o" performa"ce.
Oracle refers to i"de,ed views as materialiGed views.
O"l! the views created with schema bi"di"#8 ca" have a" 3"de,. Simpl! addi"# B3T-
S7-FM?A3ND3ND to the e"d of the 7RF?TF 43FB stateme"t will accomplish this.
-owever8 the effect is that a"! cha"#es to the u"derl!i"# tables which will impact the
view are "ot allowed. Si"ce the i"de,ed view is stored ph!sicall!8 a"! schema
cha"#es would impact the schema of the stored results set. Therefore8 S+. Server
requires that schema bi"di"# be used to preve"t the viewNs schema %a"d therefore the
u"derl!i"# tables& from cha"#i"#.
The first i"de, for a view must be a 9N3+9F 7.9STFRFD 3NDFO8 after which8 itNs
possible to create "o"-clustered i"de,es a#ai"st the view.
3"de,ed 4iews are heavil! used i" data warehouses a"d reporti"# databases that are
"ot hi#hl! tra"sactio"al.
Bhat are the limitatio"s of a 4iew/
C. 6ou ca""ot pass parameters to a view.
'. Rules a"d Defaults ca""ot be associated with views.
:. The ORDFR A6 clause is i"valid i" views u"less TO2 or FOR OM. is also specified.
=. 4iews ca""ot be based o" temporar! tables.
Aasic S+. Server 3"terview +uestio"s o" Hoi"s
Bhat are the differe"t t!pes of joi"s available i" sql server/
#here are 1 different types of Qoins available in sql server( and they are
C. 0ross Ioin
'. Inner Ioin or Ioin
:. *uter Ioin
Outer Hoi" is a#ai" divided i"to : t!pes as show" below.
C. "eft *uter Ioin or "eft Ioin
'. $ight *uter Ioin or $ight Ioin
:. Full *uter Ioin or Full Ioin
&ou might have heard about self Qoin( but self Qoin is not a different type of Qoin. self Qoin means
Qoining a table with itself. -e can have an inner self Qoin or outer self Qoin. $ead this sql server
interview question( to understand self Qoin in a greater detail.
Bhat is cross joi". F,plai" with a" e,ample/
"et us understand 0ross Ioin with an e5ample. 0reate , tables 7ompa"! and 7a"didate. 3se the
script below to create these tables and populate them. 0ompanyId column in 0andidate #able is a
foreign key referencing 0ompanyId in 0ompany #able.
7RF?TF T?A.F 7ompa"!
%
7ompa"!3d Ti"!3"t 3de"tit! 2rimar! Ie!8
7ompa"!Name Nvarchar%)(& N9..
&
DO
3NSFRT 7ompa"! 4?.9FS%NDF..N&
3NSFRT 7ompa"! 4?.9FS%N-2N&
3NSFRT 7ompa"! 4?.9FS%N3AMN&
3NSFRT 7ompa"! 4?.9FS%NMicrosoftN&
DO
7RF?TF T?A.F 7a"didate
%
7a"didate3d ti"!i"t ide"tit! primar! @e!8
FullName "varchar%)(& N9..8
7ompa"!3d ti"!i"t RFFFRFN7FS 7ompa"!%7ompa"!3d&
&
DO
3NSFRT 7a"didate 4?.9FS%NRo"N8C&
3NSFRT 7a"didate 4?.9FS%N2eteN8'&
3NSFRT 7a"didate 4?.9FS%NSteveN8:&
3NSFRT 7a"didate 4?.9FS%NSteveN8N9..&
3NSFRT 7a"didate 4?.9FS%NRaviN8C&
3NSFRT 7a"didate 4?.9FS%NRajN8:&
3NSFRT 7a"didate 4?.9FS%NIira"N8N9..&
DO
cross Qoin produces the 0artesian product of the tables involved in the Qoin. #he siUe of a
0artesian product result set is the number of rows in the first table multiplied by the number of rows
in the second table. query involving a 0$*// I*IN for the 7a"didate and 7ompa"! #able is
shown below.
SF.F7T 7a"d.7a"didate3d87a"d.FullName87a"d.7ompa"!3d8
7omp.7ompa"!3d87omp.7ompa"!Name
FROM 7a"didate 7a"d
7ROSS HO3N 7ompa"! 7omp
3f we ru" the above quer!8 we produce the result set show" i" the ima#e below.
Ie! 2oi"ts to remember about 7ROSS HO3N.
C. cross Qoin produces the 0artesian product of the tables involved in the Qoin.#his mean every
row in the "eft #able is Qoined to every row in the $ight #able. 7a"didate is "EF# #able and
7ompa"! is $I2.# #able. In our e5ample we have ,= total number of rows in the result set. < rows
in the 0andidate table multiplied by 9 rows in the 0ompany #able.
'. In real time scenarios we rarley use 0$*// I*IN. +ost often we use either INNE$ I*IN or
"EF# *3#E$ I*IN.
:. 0$*// I*IN does not have an *N clause with a Ioin 0ondition. ll the other I*IN/ use *N
clause with a Ioin 0ondition.
=. 3sing an *N clause on a 0$*// I*IN would generate a synta5 error.
Note: 3nderstanding the above key points will help you answer any follow up interview questions
on cross Qoin in sql server.
3""er Hoi" a"d left joi" are the most commonly used Qoins in real time proQects. -e will talk about
left Qoin in a later article. Now( let us understand 3""er joi" with a" e,ample.
0reate , tables 7ompa"! and 7a"didate. 3se the script below to create these tables and populate
them. 0ompanyId column in 0andidate #able is a foreign key referencing 0ompanyId in 0ompany
#able.
7RF?TF T?A.F 7ompa"!
%
7ompa"!3d Ti"!3"t 3de"tit! 2rimar! Ie!8
7ompa"!Name Nvarchar%)(& N9..
&
DO
3NSFRT 7ompa"! 4?.9FS%NDF..N&
3NSFRT 7ompa"! 4?.9FS%N-2N&
3NSFRT 7ompa"! 4?.9FS%N3AMN&
3NSFRT 7ompa"! 4?.9FS%NMicrosoftN&
DO
7RF?TF T?A.F 7a"didate
%
7a"didate3d ti"!i"t ide"tit! primar! @e!8
FullName "varchar%)(& N9..8
7ompa"!3d ti"!i"t RFFFRFN7FS 7ompa"!%7ompa"!3d&
&
DO
3NSFRT 7a"didate 4?.9FS%NRo"N8C&
3NSFRT 7a"didate 4?.9FS%N2eteN8'&
3NSFRT 7a"didate 4?.9FS%NSteveN8:&
3NSFRT 7a"didate 4?.9FS%NSteveN8N9..&
3NSFRT 7a"didate 4?.9FS%NRaviN8C&
3NSFRT 7a"didate 4?.9FS%NRajN8:&
3NSFRT 7a"didate 4?.9FS%NIira"N8N9..&
DO
If you want to select all the rows from the .FFT table'In our e5ample 7a"didate Table) that have a
non null foreign key value'0ompanyId in 7a"didate Table is the foreign key) then we use 3NNFR
HO3N. query involving an 3NNFR HO3N for the 7a"didate a"d 7ompa"! #able is shown below.
SF.F7T 7a"d.7a"didate3d8 7a"d.FullName8 7a"d.7ompa"!3d8 7omp.7ompa"!3d8
7omp.7ompa"!Name
FROM 7a"didate 7a"d
3NNFR HO3N 7ompa"! 7omp
ON 7a"d.7ompa"!3d > 7omp.7ompa"!3d
If we run the above query the output will be as shown in the image below. If you look at the out put(
we only got : rows. -e did not get the , rows which has N3"" value in the 0ompanyId column. /o
an INNE$ I*IN would get all the rows from the "EF# #able that has non null foreign key value.
3""er Hoi" Result
Instead of using 3NNFR HO3N keyword we can Qust use HO3N keyword as shown below. HO3N or
3NNFR HO3N means the same.
SF.F7T 7a"d.7a"didate3d8 7a"d.FullName8 7a"d.7ompa"!3d8 7omp.7ompa"!3d8
7omp.7ompa"!Name
FROM 7a"didate 7a"d
HO3N 7ompa"! 7omp
ON 7a"d.7ompa"!3d > 7omp.7ompa"!3d
&nner *oin and left +oin are the most commonly used *oins in real time pro*ects. +lic, here to read about
&nner -oin in !L erver. #ow" let us understand Left +oin with an e)ample.
+reate . tables !ompany and !andidate. /se the script below to create these tables and populate them.
+ompany&d column in +andidate Table is a foreign ,ey referencing +ompany&d in +ompany Table.
!,-.T- T./L- !ompany
0
!ompany&d Tiny&nt &dentity 1rimary 2ey'
!ompany3ame 3varchar0456 37LL
6
G8
&3S-,T !ompany 9.L7-S0:%-LL:6
&3S-,T !ompany 9.L7-S0:(1:6
&3S-,T !ompany 9.L7-S0:&/;:6
&3S-,T !ompany 9.L7-S0:;icrosoft:6
G8
!,-.T- T./L- !andidate
0
!andidate&d tinyint identity primary $ey'
<"ll3ame nvarchar0456 37LL'
!ompany&d tinyint ,-<-,-3!-S !ompany0!ompany&d6
6
G8
&3S-,T !andidate 9.L7-S0:,on:'16
&3S-,T !andidate 9.L7-S0:1ete:'26
&3S-,T !andidate 9.L7-S0:Steve:'6
&3S-,T !andidate 9.L7-S0:Steve:'37LL6
&3S-,T !andidate 9.L7-S0:,avi:'16
&3S-,T !andidate 9.L7-S0:,a+:'6
&3S-,T !andidate 9.L7-S0:2iran:'37LL6
G8
&f you want to select all the rows from the L-<T table ( &n our example !andidate Table ) including the
rows that have a null foreign ,ey value ( +ompany&d in !andidate Table is the foreign ,ey ) then we use
L-<T 87T-, *8&3. 0 1uery involving a L-<T 87T-, *8&3 for the !andidate and !ompany Table is
shown below.
S-L-!T !and.!andidate&d' !and.<"ll3ame' !and.!ompany&d' !omp.!ompany&d'
!omp.!ompany3ame
<,8; !andidate !and
L-<T 87T-, *8&3 !ompany !omp
83 !and.!ompany&d = !omp.!ompany&d
&f we run the above 1uery the output will be as shown in below. &f you loo, at the out put" we now got all 2
rows ( 0ll the rows from the !andidate Table ) including the row that has a null value for the !ompany&d
column in the !andidate Table. o" L-<T 87T-, *8&3 would get all the rows from the L-<T Table
including the rows that has null foreign ,ey value.
.eft Hoi" Result
Instead of using .FFT O9TFR HO3N keyword we can Qust use .FFT HO3N keyword as shown
below. .FFT O9TFR HO3N or .FFT HO3N means the same.
SF.F7T 7a"d.7a"didate3d8 7a"d.FullName8 7a"d.7ompa"!3d8 7omp.7ompa"!3d8
7omp.7ompa"!Name
FROM 7a"didate 7a"d
.FFT HO3N 7ompa"! 7omp
ON 7a"d.7ompa"!3d > 7omp.7ompa"!3d
Now( let us understand Ri#ht Outer joi" with a" e,ample.
0reate , tables 7ompa"! and 7a"didate. 3se the script below to create these tables and populate
them. 0ompanyId column in 0andidate #able is a foreign key referencing 0ompanyId in 0ompany
#able.
7RF?TF T?A.F 7ompa"!
%
7ompa"!3d Ti"!3"t 3de"tit! 2rimar! Ie!8
7ompa"!Name Nvarchar%)(& N9..
&
DO
3NSFRT 7ompa"! 4?.9FS%NDF..N&
3NSFRT 7ompa"! 4?.9FS%N-2N&
3NSFRT 7ompa"! 4?.9FS%N3AMN&
3NSFRT 7ompa"! 4?.9FS%NMicrosoftN&
DO
7RF?TF T?A.F 7a"didate
%
7a"didate3d ti"!i"t ide"tit! primar! @e!8
FullName "varchar%)(& N9..8
7ompa"!3d ti"!i"t RFFFRFN7FS 7ompa"!%7ompa"!3d&
&
DO
3NSFRT 7a"didate 4?.9FS%NRo"N8C&
3NSFRT 7a"didate 4?.9FS%N2eteN8'&
3NSFRT 7a"didate 4?.9FS%NSteveN8:&
3NSFRT 7a"didate 4?.9FS%NSteveN8N9..&
3NSFRT 7a"didate 4?.9FS%NRaviN8C&
3NSFRT 7a"didate 4?.9FS%NRajN8:&
3NSFRT 7a"didate 4?.9FS%NIira"N8N9..&
DO
If you want to select all the rows from the .FFT Table ' In our e5ample 7a"didate #able) that have
non null foreign key values plus all the rows from the R3D-T table ' In our e5ample 7ompa"!
#able) including the rows that are not referenced in the .FFT Table( then we use R3D-T O9TFR
HO3N. query involving a R3D-T O9TFR HO3N for the 7a"didate and 7ompa"! Table is shown
below.
SF.F7T 7a"d.7a"didate3d8 7a"d.FullName8 7a"d.7ompa"!3d8 7omp.7ompa"!3d8
7omp.7ompa"!Name
FROM 7a"didate 7a"d
R3D-T O9TFR HO3N 7ompa"! 7omp
ON 7a"d.7ompa"!3d > 7omp.7ompa"!3d
If we run the above query the output will be as shown in below. If you look at the out put( we now
got ; rows. ll the rows from the 7a"didate #able that has non null foreign key value plus all the
rows from the 7ompa"! #able including the row that is not referenced in the 7a"didate #able.
Ri#ht Outer Hoi" Results
Instead of using R3D-T O9TFR HO3N keyword we can Qust use R3D-T HO3N keyword as shown
below. R3D-T O9TFR HO3N or R3D-T HO3N means the same.
SF.F7T 7a"d.7a"didate3d8 7a"d.FullName8 7a"d.7ompa"!3d8 7omp.7ompa"!3d8
7omp.7ompa"!Name
FROM 7a"didate 7a"d
R3D-T HO3N 7ompa"! 7omp
ON 7a"d.7ompa"!3d > 7omp.7ompa"!3d
3""er Hoi" a"d left joi" are the most commonly used Qoins in real time proQects. It is very important
that you understand the basics of Qoins before reading this article. Please read the articles below if
you have not done so already.
C. %asics of Ioins in /E" /erver
'. Inner Ioin
:. "eft Ioin
=. $ight Ioin
Now( let us understand Full Outer joi" with a" e,ample.
0reate , tables 7ompa"! and 7a"didate. 3se the script below to create these tables and populate
them. 0ompanyId column in 0andidate #able is a foreign key referencing 0ompanyId in 0ompany
#able.
7RF?TF T?A.F 7ompa"!
%
7ompa"!3d Ti"!3"t 3de"tit! 2rimar! Ie!8
7ompa"!Name Nvarchar%)(& N9..
&
DO
3NSFRT 7ompa"! 4?.9FS%NDF..N&
3NSFRT 7ompa"! 4?.9FS%N-2N&
3NSFRT 7ompa"! 4?.9FS%N3AMN&
3NSFRT 7ompa"! 4?.9FS%NMicrosoftN&
DO
7RF?TF T?A.F 7a"didate
%
7a"didate3d ti"!i"t ide"tit! primar! @e!8
FullName "varchar%)(& N9..8
7ompa"!3d ti"!i"t RFFFRFN7FS 7ompa"!%7ompa"!3d&
&
DO
3NSFRT 7a"didate 4?.9FS%NRo"N8C&
3NSFRT 7a"didate 4?.9FS%N2eteN8'&
3NSFRT 7a"didate 4?.9FS%NSteveN8:&
3NSFRT 7a"didate 4?.9FS%NSteveN8N9..&
3NSFRT 7a"didate 4?.9FS%NRaviN8C&
3NSFRT 7a"didate 4?.9FS%NRajN8:&
3NSFRT 7a"didate 4?.9FS%NIira"N8N9..&
DO
If you want to select all the rows from the .FFT Table ' In our e5ample 7a"didate #able ) plus all
the rows from the R3D-T table ' In our e5ample 7ompa"! #able ) ( then we use F9.. O9TFR
HO3N. query involving a F9.. O9TFR HO3N for the 7a"didate a"d 7ompa"! #able is shown
below.
SF.F7T 7a"d.7a"didate3d8 7a"d.FullName8 7a"d.7ompa"!3d8 7omp.7ompa"!3d8
7omp.7ompa"!Name
FROM 7a"didate 7a"d
F9.. O9TFR HO3N 7ompa"! 7omp
ON 7a"d.7ompa"!3d > 7omp.7ompa"!3d
If we run the above query the output will be as shown in below. If you look at the out put( we now
got = rows. ll the rows from the 7a"didate #able and all the rows from the 7ompa"! #able.
Full Outer Hoi" Result
Instead of using F9.. O9TFR HO3N keyword we can Qust use F9.. HO3N keyword as shown
below. F9.. O9TFR HO3N or F9.. HO3N means the same.
SF.F7T 7a"d.7a"didate3d8 7a"d.FullName8 7a"d.7ompa"!3d8 7omp.7ompa"!3d8
7omp.7ompa"!Name
FROM 7a"didate 7a"d
F9.. HO3N 7ompa"! 7omp
ON 7a"d.7ompa"!3d > 7omp.7ompa"!3d
#here are 1 different types of Qoins available in sql server( and they are
C. 0ross Ioin
'. Inner Ioin or Ioin
:. *uter Ioin
Outer Hoi" is again divided into 1 types as shown below.
C. "eft *uter Ioin or "eft Ioin
'. $ight *uter Ioin or $ight Ioin
:. Full *uter Ioin or Full Ioin
I strongly recomend to learn about the basics and types of Qoins( before reading this article. $ead
the articles below( before proceeding with self Qoin.
C. %asics of Ioins
'. Inner Ioin
:. "eft *uter Ioin
=. $ight *uter Ioin
). Full *uter Ioin
Self joi" is not a different type of Qoin. Self joi" means Qoining a table with itself. -e can have an
i""er self joi" or outer self joi". "et us try to understand with an e,ample.
#o set up the data for the e,ample( use the script below to create Fmplo!ee Table and populate it
with some sample data. -e will be using Fmplo!ee Table to understand Self Hoi".
7RF?TF T?A.F FM2.O6FF
%
;FM2.O6FF3D< 3NT 2R3M?R6 IF68
;N?MF< N4?R7-?R%)(&8
;M?N?DFR3D< 3NT
&
DO
3NSFRT 3NTO FM2.O6FF 4?.9FS%C(C8NMar!N8C('&
3NSFRT 3NTO FM2.O6FF 4?.9FS%C('8NRaviN8N9..&
3NSFRT 3NTO FM2.O6FF 4?.9FS%C(:8NRajN8C('&
3NSFRT 3NTO FM2.O6FF 4?.9FS%C(=8N2eteN8C(:&
3NSFRT 3NTO FM2.O6FF 4?.9FS%C()8N2rasadN8C(:&
3NSFRT 3NTO FM2.O6FF 4?.9FS%C(J8NAe"N8C(:&
DO
-e use Self Hoi"( if we have a table that references itself. For e,ample( In the Fmplo!ee Table
below +N2E$ID column references E+P"*&EEID column. /o the table is said to refere"ci"#
itself. #his is the right scenario where we can use Self Hoi". Now I want to write a query that will
give me the list of all Employee Names and their respective +anager Names. In order to achieve
this I can use /elf Ioin. In the #able below($aQ is the manager for Pete(Prasad and %en. $avi is the
manager for $aQ and +ary. $avi does not have a manager as he is the president of the 0ompany.
#he query below is an e5ample of Self Hoi". %oth E! and E, refer to the same Fmplo!ee #able. In
this query we are Qoining the Fmplo!ee #able with itself.
SF.F7T FC.;N?MF<8F'.;N?MF< ?S ;M?N?DFR N?MF<
FROM FM2.O6FF FC
3NNFR HO3N FM2.O6FF F'
ON F'.FM2.O6FF3D >FC.M?N?DFR3D
If we run the above query we only get : rows out of the ; rows as shown below.
3""er Self Hoi"
#his is because $avi does not have a +anager. +N2E$ID column for $avi is N3"". If we want
to get all the rows then we can use .FFT O9TFR HO3N as shown below.
SF.F7T FC.;N?MF<8F'.;N?MF< ?S ;M?N?DFR N?MF<
FROM FM2.O6FF FC
.FFT O9TFR HO3N FM2.O6FF F'
ON F'.FM2.O6FF3D >FC.M?N?DFR3D
If we e5ecute the above query we get all the rows( including the row that has a null value in the
+N2E$ID column. #he results are shown below. #he +N2E$N+E for ,nd record is N3""
as $avi does not have a +anager.
.eft Outer Self Hoi"
"et us now slightly modify the above query using 7O?.FS7F as shown below. $ead 0*"E/0E
function in /E" /erver to understand 7O?.FS7F in a greater detail.
SF.F7T FC.;N?MF<87O?.FS7F%F'.;N?MF<8NNo Ma"a#erN& ?S ;M?N?DFR N?MF<
FROM FM2.O6FF FC
.FFT HO3N FM2.O6FF F'
ON F'.FM2.O6FF3D >FC.M?N?DFR3D
If we e5ecute the above query the output will be as shown in the image below. #his is how
7O?.FS7F can be used.
.eft Outer Self Hoi" with
7O?.FS7F
3"de, Sca"E
3"de, Sca" scans each and every record in the inde5. Table Sca" is where the table is processed
row by row from beginning to end. If the inde5 is a clustered inde5 then an i"de, sca" is really a
table sca". /ince a scan touches every row in the table whether or not it qualifies( the cost is
proportional to the total number of rows in the table. -e"ce8 a sca" is a" efficie"t strate#! o"l! if
the table is small.
3"de, See@E
/ince a seek only touches rows that qualify and pages that contain these qualifying rows( the cost is
proportional to the number of qualifying rows and pages rather than to the total number of rows in
the table.
F,ample
I have an emplo!ee table as shown in the diagram below. EmployeeId is the primary key. -e have
a clustered inde5 on the employeeId column.
+uer! C L Select 5 from Fmplo!ee where FirstName>NAe"N
+uer! ' L Select 5 from Fmplo!ee where Fmplo!ee3d>'
Euery ! will do an 3"de, sca" '#able /can) to retrieve the record as there is no Inde5 on the
FirstName column.
Euery , will do an 3"de, see@ to retrieve the record as there is an Inde5 on the EmployeeId
column.
/o from this e5ample( you should have understood that( a query will result into an inde5 seek( only
if there is an inde5 on the table to help they query to retrieve the data.
Delete from tables i"volved i" a S+. Hoi"
#his question is not asked that often in an interview( but you may have to write a query to delete
from tables that are involved in a /E" Qoin in your day to day Qob routine as a /E" Developer.
"et me e5plain you the question first. 0onsider the Fmplo!ees and Departme"ts tables below.
I want you to write a query using Qoins which will give me the list of all -R Departme"t emplo!ees.
#he output should be as shown below.
To do this we will write a quer! usi"# joi"s as show" below.
/elect E.Name as GEmployee NameH(D.Name as GDepartment NameH
from Employees E
Inner Ioin Departments D
*n E.DeptId K D.Id
-here D.Name K 4.$4
Now I want you to write a query( that deletes all the -R departme"t emplo!ees. #o do this we
have to Qoin Fmplo!ees and Departme"ts tables and usually we will be tempted to write the query
as shown below( but this query will not e5ecute and will give a synta5 error.
3"correct S+. Delete +uer! to delete from multiple tables i"vloved i" a S+. joi"
Delete From Employees E
Inner Ioin Departments D
*n E.DeptId K D.Id
-here D.Name K 4.$4
The quer! below shows the correct s!"ta, for issui"# a S+. delete that i"volves a S+. joi".
Delete E From 'Employees E
Inner Ioin Departments D
*n E.DeptId K D.Id
and D.Name K 4.$4)
The followi"# s!"ta, is also valid a"d has the same effect.
Delete Employees From
'
Employees Qoin Departments
on Employees.DeptId K Departments.Id
)
where Departments.Name K 4.$4
Advantages and Disadvantages of Stored Procedure
*ctober !9( ,AA: ^ mukund
dvantages of stored proceduresL
the proceduresVfunctions are stored in the database and are( therefore( e5ecuted on the database
server which is likely to me more powerful than the clients which in turn means that stored
procedures should run fasterJ
the code is stored in a preOcompiled form which means that it is syntactically valid and does not
need to be compiled at runOtime( thereby saving resourcesJ
each user of the stored procedureVfunction will use e5actly the same form of queries which means
the queries are reused thereby reducing the parsing overhead and improving the scalability of
applicationsJ
as the proceduresVfunctions are stored in the database there is no need to transfer the code from
the clients to the database server or to transfer intermediate results from the server to the clients.
#his results in much less network traffic and again improves scalabilityJ
when using P"V/E" packages( as soon as one obQect in the package is accessed( the whole
package is loaded into memory which makes subsequent access to obQects in the package much
faster
stored proceduresVfunctions can be compiled into WnativeX machine code making them even faster
'available with *racle ?i and above)
DisadvantagesL
there is an overhead involved in switching from /E" to P"V/E"( this may be significant in terms of
performance but usually this overhead is outweighed by performance advantages of using P"V/E"
more memory may be required when using packages as the whole package is loaded into memory
as soon as any obQect in the package is accessed
native compilation can take twice as long as normal compilation
Despite the advantages listed above( there are some situations where the use of stored procedures
is not recommended or may be infeasible.
Disadva"ta#es
pplications that involve e5tensive business logic and processing could place an e5cessive
load on the server if the logic was implemented entirely in stored procedures. E5amples of
this type of processing include data transfers( data traversals( data transformations and
intensive computational operations. &ou should move this type of processing to business
process or data access logic components( which are a more scalable resource than your
database server.
Do not put all of your business logic into stored procedures. +aintenance and the agility of
your application becomes an issue when you must modify business logic in #O/E". For
e5ample( I/8 applications that support multiple $D%+/ should not need to maintain
separate stored procedures for each system.
-riting and maintaining stored procedures is most often a specialiUed skill set that not all
developers possess. #his situation may introduce bottlenecks in the proQect development
schedule.
/tate transition testing is used where some aspect of the system can be described in what is called
a Wfinite state machineX. #his simply means that the system can be in a 'finite) number of different
states( and the transitions from one state to another are determined by the rules of the WmachineX.
#his is the model on which the system and the tests are based. ny system where you get a
different output for the same input( depending on what has happened before( is a finite state
system.
For e5ample( if you request to withdraw `!AA from a bank #+( you may be given cash. "ater you
may make e5actly the same request but be refused the money 'because your balance is
insufficient). #his later refusal is because the state of your bank account had changed from having
sufficient funds to cover the withdrawal to having insufficient funds. #he transaction that caused
your account to change its state was probably the earlier withdrawal. nother e5ample is a word
processor. If a document is open( you are able to 0lose it. If no document is open( then W0loseX is
not available. fter you choose W0loseX once( you cannot choose it again for the same document
unless you open that document. document thus has two statesL open and closed.
state transition model has four basic partsL
#he states that the software may occupy 'openVclosed or fundedVinsufficient funds)J
#he transitions from one state to another 'not all transitions are allowed)J
#he events that cause a transition 'withdrawing money( closing a file)J
#he actions that result from a transition 'an error message( or being given your cash).
Note that a transition does not need to change to a different stateJ it could stay in the same state. In
fact( trying to input an invalid input would be likely to produce an error message as the action( but
the transition would be back to the same state the system was in before.
Deriving test cases from the state transition model is a black bo5 approach. +easuring how much
you have tested 'covered) is getting close to a white bo5 perspective. .owever( state transition
testing is generally regarded as a black bo5 technique.
&ou can design tests to test every transition shown in the model. If every 'valid) transition is tested(
this is known as WAOswitchX coverage. &ou could also test a series of transitions through more than
one state. If you covered all of the pairs of two valid transitions( you would have W!OswitchX
coverage( covering the sets of 1 transitions would give W,OswitchX coverage( etc.
.owever( deriving tests only from the model may omit the negative tests( where we could try to
generate invalid transitions. In order to see the total number of combinations of states and
transitions( both valid and invalid( a state table can be used.
Five -ays to #hink about %lack %o5 #esting
#o help understand the different ways that software testing can be divided between black bo5 and
white bo5 techniques( ICll use the FiveOFold #esting /ystem. It lays out five dimensions that can be
used for e5amining testingL

!. People 'who does the testing)
,. 0overage 'what gets tested)
1. $isks 'why you are testing)
9. ctivities 'how you are testing)
:. Evaluation 'how you know youCve found a bug)

"etCs use this system to understand and clarify the characteristics of black bo5 and white bo5
testing.

2eopleE Bho does the testi"#/
/ome people know how software works 'developers) and others Qust use it 'users). ccordingly( any
testing by users or other nondevelopers is sometimes called Wblack bo5X testing. Developer testing
is called Wwhite bo5X testing. #he distinction here is based on what the person knows or can
understand.

7overa#eE Bhat is tested/
If we draw the bo5 around the system as a whole( Wblack bo5X testing becomes another name for
system testing. nd testing the units inside the bo5 becomes white bo5 testing. #his is one way to
think about coverage.

nother is to contrast testing that aims to cover all the requirements with testing that aims to cover
all the code. #hese are the two most commonly used coverage criteria. %oth are supported by
e5tensive literature and commercial tools. $equirementsObased testing could be called Wblack bo5X
because it makes sure that all the customer requirements have been verified. 0odeObased testing is
often called Wwhite bo5X because it makes sure that all the code 'the statements( paths( or
decisions) is e5ercised.

Ris@sE Bh! are !ou testi"#/
/ometimes testing is targeted at particular risks. %oundary testing and other attackObased
techniques are targeted at common coding errors. Effective security testing also requires a detailed
understanding of the code and the system architecture. #hus( these techniques might be classified
as Wwhite bo5.X

nother set of risks concerns whether the software will actually provide value to users. 3sability
testing focuses on this risk( and could be termed Wblack bo5.X

?ctivitiesE -ow do !ou test/
common distinction is made between behavioral test design( which defines tests based on
functional requirements( and structural test design( which defines tests based on the code itself.
#hese are two design approaches. /ince behavioral testing is based on e5ternal functional
definition( it is often called Wblack bo5(X while structural testing^based on the code internals^is
called Wwhite bo5.X Indeed( this is probably the most commonly cited definition for black bo5 and
white bo5 testing.

nother activityObased distinction contrasts dynamic test e5ecution with formal code inspection. In
this case( the metaphor maps test e5ecution 'dynamic testing) with black bo5 testing( and maps
code inspection 'static testing) with white bo5 testing.

-e could also focus on the tools used. /ome tool vendors refer to codeOcoverage tools as white
bo5 tools( and tools that facilitate applying inputs and capturing inputs^most notably 23I capture
replay tools^as black bo5 tools. #esting is then categoriUed based on the types of tools used.

Fvaluatio"E -ow do !ou @"ow if !ou1ve fou"d a bu#/
#here are certain kinds of software faults that donCt always lead to obvious failures. #hey may be
masked by fault tolerance or simply luck. +emory leaks and wild pointers are e5amples. 0ertain test
techniques seek to make these kinds of problems more visible. $elated techniques capture code
history and stack information when faults occur( helping with diagnosis. ssertions are another
technique for helping to make problems more visible. ll of these techniques could be considered
white bo5 test techniques( since they use code instrumentation to make the internal workings of the
software more visible. #hese contrast with black bo5 techniques that simply look at the official
outputs of a program.

#o summariUe( black bo5 testing can sometimes describe userObased testing 'people)J system or
requirementsObased testing 'coverage)J usability testing 'risk)J or behavioral testing or capture
replay automation 'activities). -hite bo5 testing( on the other hand( can sometimes describe
developerObased testing 'people)J unit or codeOcoverage testing 'coverage)J boundary or security
testing 'risks)J structural testing( inspection or codeOcoverage automation 'activities)J or testing
based on probes( assertions( and logs 'evaluation).

2uGGles
/o now that weCve e5amined some ways to think about the differences between black bo5 and
white bo5 testing( let me leave you with a few puUUles. "etCs hear what you think.

. programmer tests a class to ensure that it meets its functional requirements. Is this black bo5
or white bo5 testing[

%. &our company develops software under a contract that stipulates that both white bo5 and black
bo5 test techniques will be used. -hat tests are you obliged to e5ecute[

0. nonprogrammer uses a test tool that automatically instruments the code and then generates
tests to ensure that a ma5imal number of lines of code are e5ecuted. #he tests are considered to
pass as long as the software doesnCt crash or hang. Is this black bo5 or white bo5 testing[

D. -hat could it mean to perform Wgray bo5X testing[
In %lack %o5 #esting( the tester tests an application without knowledge of the internal workings of
the functionalities being tested. Data are inputted into the application and the outcome is compared
with the e5pected resultsJ what the program does with the input data or how the program arrives at
the output data is not a concern for the tester performing black bo5 testing. ll that is tested is the
behavior of the functionalities being tested.
#his is why black bo5 testing is also known as functional testing which tests the functionality of a
program. Note we can also have nonOfunctional black bo5 testing( such as performance testing
which is a type of black bo5 testing but instead of verifying the behavior of the system( it tests how
long it takes for a function to respond to userCs inputs and how long it takes to process the data and
generate outputs.
%ecause black bo5 testing is not concerned with the underlying code( then the techniques can be
derived from the requirement documents or design specifications and hence testing can start as
soon as the requirements are written.
/ome %lack %o5 #esting #echniques areL
Equivalence Partitioning
%oundary 8alue nalysis
/tate #ransition #esting
0ause V Effect 2raphing
0lassification #ree +ethod
dvantages of %lack %o5 #esting areL
#he test is unbiased because the designer and the tester are independent of each other
#he tester does not need knowledge of any specific programming languages
#he test is done from the point of view of the user( not the designer
#est cases can be designed as soon as the specifications are complete
Disadvantages of %lack %o5 #esting areL
#he test can be redundant if the software designer has already run a test case
#he test cases are difficult to design
#esting every possible input stream is unrealistic because it would take a inordinate amount
of timeJ therefore( many program paths will go untested
The be"efits of Stored 2rocedures
Posted on /unday( ,9 Iune( ,AA< by 0olin +ackay
#here are a number of ways to access data in /E" /erver( or any enterprise D%+/. #here are lots
of books that discuss getting data in and out of databases and the best ways to do that. +any
advocate the use of stored procedures to ensure the safety of the data.
#he tree main benefits that I see on stored procedures areL
bstraction
/ecurity
Performance
/tored Procedures add an e5tra layer of abstraction in to the design of a software system. #his
means that( so long as the interface on the stored procedure stays the same( then the underlying
table structure can change with no noticable consequence to the application that is using the
database.
For instance( if the database has to be denormalised to get a little e5tra performance in certain
situations then the stored procedures can handle the additional updates and inserts necessary to
ensure the integrity of the data across the tables. -ithout this the each of the callers would have
ensure that these changes had taken place. *f course( the use of stored procedures does not in
anyway grant a waiver from properly designing the data model( but it can help if the perfect
normalised model has to give way for performance improvements.
#his layer of abstraction also helps put up an e5tra barrier to would be intruders. If access to the
data in /E" /erver is only ever permitted via stored procedures then permission does not need to
be e5plicitly set on any of the tables. #herefore none of the tables should ever need to be e5posed
directly to outside applications. For an outside application to modify the database( it must go
through stored procedures.
/tored procedures can be written to validate any input that is sent to them to ensure the integrity of
the data beyond the simple constraints otherwise available on the tables. Parameters can be
checked for valid ranges. Information can be cross checked with data in other tables.
Even if it is thought that someone attempting to crack into a website will never get this far in( from a
security perspective( anything that can reduce the attack surface is beneficial.
Performance can be improved by the use of stored procedures. #hey are precompiled so when they
are run there is no additional lag as the /E" is parsed( compiled( e5ecution plans drawn up
and then run( they Qust run because all that e5tra work is done at the time the 0$E#E
P$*0ED3$E or "#E$ P$*0ED3$E commands are run rather than when procedures
themselves are run.
nother area in which stored procedures improve performance is that is pushes all the work onto
the server in one go. stored procedure can perform a series of queries and return many tables in(
what is to the outside world( one operation. #his saves the calling process from making many
requests and the additional time of several network roundtrips. It also means that( if the contents of
one set of data being returned is dependent on the results of a previous set of data that is being
retrieved through the same stored procedure( that the data only has to flow from the database
server to the application. If stored procedures were not being used it would mean that the data from
the first database call has to get sent back to the database for the second call in order for it to
continue retrieving the information needed by the application.
For instance. "ets say that Northwind traders send out a quarterly statement to its customers( and
that for each statement certain information needs to be e5tracted from the database. #he tables
0ustomer( *rder and *rder Details are used. #his information could be retrieved in several steps by
calling the database for each set of information as it is needed to generate the statements. First with
a /E"E0# 6 F$*+ 0ustomers -.E$E 0ustomerID K Z0ustomerID. #his gets the details for the
head of the statement. #hen a /E"E0# 6 F$*+ *rders -.E$E 0ustomerID K Z0ustomerID ND
*rderDate>KZ/tartDate ND *rderDateSKZEndDate to get the details for each individual order
by that customer. nd finally a series of calls 'one for each of the *rder records that were
retrieved) like /E"E0# 6 F$*+ G*rder DetailsH -.E$E *rderID K Z*rderID
ssuming that the customer in question is W$attlesnake 0anyon 2roceryX and the period for the
statement is E! !??= then that is : roundtrips to the database and : times the database has to
parse some /E". #his could be done by a single stored procedure that takes only one trip to the
database and is precompiled.

0$E#E P$*0ED3$E 2etEuarterly/tatement
Z0ustomerID nvarchar':)(
Z/tartDate datetime(
ZEndDate datetime
/
/E"E0# 6 F$*+ 0ustomers
-.E$E 0ustomerIDKZ0ustomerID
/E"E0# 6 F$*+ *rders
-.E$E 0ustomerIDKZ0ustomerID
ND *rderDate>KZ/tartDate
ND *rderDateSKZEndDate
*$DE$ %& *rderDate DE/0
/E"E0# G*rder DetailsH.6 F$*+ G*rder DetailsH
INNE$ I*IN *rders *N G*rder DetailsH.*rderID K *rders.*rderID
-.E$E 0ustomerIDKZ0ustomerID
ND *rderDate>KZ/tartDate
ND *rderDateSKZEndDate
*$DE$ %& *rderDate DE/0
2*
SQL SERVER Stored Procedures Advantages and Best Advantage
0pril 34" .552 by pinaldave
There are many advantages of tored Procedures. & was once as,ed what do & thin, is the most important
feature of tored Procedure6 & have to pic, only 83-. &t is tough 1uestion.
& answered 7 'xecution Plan Retention and Reuse (P are compiled and their execution plan is cached and
used again to when the same P is executed again)
#ot to mentioned & received the second 1uestion following my answer 7 Why? $ecause all the other
advantage ,nown (they are mentioned below) of P can be achieved without using P. Though 'xecution
Plan 8etention and 8euse can only be achieved using tored Procedure only.
'xecution plan retention and reuse
!uery auto9parameteri:ation
'ncapsulation of business rules and policies
0pplication modulari:ation
haring of application logic between applications
0ccess to database ob*ects that is both secure and uniform
+onsistent" safe data modification
#etwor, bandwidth conservation
upport for automatic execution at system start9up
'nhanced hardware and software capabilities
&mproved security
8educed development cost and increased reliability
+entrali:ed security" administration" and maintenance for common routines
tored procedures offer several distinct advantages over embedding 1ueries in your Graphical /ser &nterface
(G/&). ;our first thought may be7 <=hy tolerate the added development overhead6< 0fter seeing the
advantages" you may change your mind.
.dvanta#e 17 tored procedures are modular. This is a good thing from a maintenance standpoint. =hen
1uery trouble arises in your application" you would li,ely agree that it is much easier to troubleshoot a stored
procedure than an embedded 1uery buried within many lines of G/& code.
.dvanta#e 27 tored procedures are tunable. $y having procedures that handle the database wor, for your
interface" you eliminate the need to modify the G/& source code to improve a 1uery>s performance. +hanges
can be made to the stored procedures99in terms of *oin methods" differing tables" etc.99that are transparent to
the front9end interface.
.dvanta#e 7 tored procedures abstract or separate server9side functions from the client9side. &t is much
easier to code a G/& application to call a procedure than to build a 1uery through the G/& code.
.dvanta#e >7 tored procedures are usually written by database developers?administrators. Persons holding
these roles are usually more experienced in writing efficient 1ueries and !L statements. This frees the G/&
application developers to utili:e their s,ills on the functional and graphical presentation pieces of the
application.
What is a Trigger in SQL Server?
A Trigger is a database object that is attached to a table. In many aspects it is similar to a stored
procedure. As a matter of fact, triggers are often referred to as a "special kind of stored procedure."
The main difference between a trigger and a stored procedure is that the former is attached to a
table and is only fired when an INS!T, "#$AT or $%T occurs.
What are the two types of Triggers in SQL Server?
1. After Triggers : &ired after Insert, "pdate and $elete operations on a table.
2. Instead of Triggers: &ired instead of Insert, "pdate and $elete operations on a table.
What are the special tales !sed y Triggers in SQL Server?
Triggers make use of two special tables called inserted and deleted. The inserted table contains
the data referenced in an INS!T before it is actually committed to the database. The deleted table
contains the data in the underlying table referenced in a $%T before it is actually remo'ed from
the database. (hen an "#$AT is issued both tables are used. )ore specifically, the new data
referenced in the "#$AT statement is contained in inserted table and the data that is being
updated is contained in deleted table.
"ive a real ti#e e$a#ple for triggers !sage?
It is recomended to a'oid triggers in a real time en'ironment. There is one scenario I can think of
why you may want to use triggers in a real time en'ironment. %et us use an e*ample to understand
this.
I ha'e + tables, tl%erson and tl"ender as shown below. "enderId is the foriegn key in
tl%erson table.
Now create a 'iew based on the abo'e + tables as shown below.
Select , from vW%ersons will gi'e us the result as shown below.
Now update the 'iew the following -uery. This will change the .ender Te*t to &e#ale in tl"ender
table for Id / 0. This is not what we ha'e e*pected.
"pdate tbl.ender Set .ender/1&emale1 where Id/0
The base tables are updated incorrectly. So, Select , from vW%ersons will gi'e us the result as
shown below.
To update the base tables correctly, you can create an I'ST(A) *& trigger on the 'iew as shown
below.
Now run the -uery below which will update the underlying base tables correctly.
"pdate '(#ersons Set .ender/1&emale1 (here Id/0
Select , from '(#ersons, will show the correct result set as shown below. The I'ST(A) *& trigger
has correctly updated the .enderId in tbl#erson table.
So, Instead of triggers can be used to facilitate !pdating +iews that are ased on #!ltiple ase
tales.
SQL T"nin# or SQL 8ptimi?ation
1l tatements are used to retrieve data from the database. =e can get same results by writing different s1l
1ueries. $ut use of the best 1uery is important when performance is considered. o you need to s1l 1uery
tuning based on the re1uirement. %ere is the list of 1ueries which we use re1ularly and how these s1l 1ueries
can be optimi:ed for better performance.
SQL T"nin#@SQL 8ptimi?ation TechniA"es:
16 The s1l 1uery becomes faster if you use the actual columns names in 'L'+T statement instead of than >@>.
<or -)ample: =rite the 1uery as
SELECT id, first_name, last_name, age, subject FROM student_details;
&nstead of7
SELECT * FROM student_details;

26 %0A&#G clause is used to filter the rows after all the rows are selected. &t is *ust li,e a filter. )o not use
%0A&#G clause for any other purposes.
<or -)ample: =rite the 1uery as
SELECT subject, cunt!subject"
FROM student_details
#$ERE subject %& 'Science'
()* subject %& 'Mat+s'
,RO-. /0 subject;
&nstead of7
SELECT subject, cunt!subject"
FROM student_details
,RO-. /0 subject
$(12), subject%& '1ancu3er' ()* subject%& 'Trnt';

6 ometimes you may have more than one sub1ueries in your main 1uery. Try to minimi:e the number of
sub1uery bloc, in your 1uery.
<or -)ample: =rite the 1uery as
SELECT name
FROM em4l5ee
#$ERE !salar5, age " & !SELECT M(6 !salar5", M(6 !age"
FROM em4l5ee_details"
()* de4t & 'Electrnics';
&nstead of7
SELECT name
FROM em4l5ee
#$ERE salar5 & !SELECT M(6!salar5" FROM em4l5ee_details"
()* age & !SELECT M(6!age" FROM em4l5ee_details"
()* em4_de4t & 'Electrnics';

>6 /se operator 'B&T" &# and table *oins appropriately in your 1uery.
a6 /sually &# has the slowest performance.
b6 &# is efficient when most of the filter criteria is in the sub91uery.
c6 'B&T is efficient when most of the filter criteria is in the main 1uery.
<or -)ample: =rite the 1uery as
Select * frm 4rduct 4
7+ere E62STS !select * frm rder_items
7+ere 84rduct_id & 484rduct_id"
&nstead of7
Select * frm 4rduct 4
7+ere 4rduct_id 2)
!select 4rduct_id frm rder_items

46 /se 'B&T instead of )&T&#+T when using *oins which involves tables having one9to9many
relationship.
<or -)ample: =rite the 1uery as
SELECT d8de4t_id, d8de4t
FROM de4t d
#$ERE E62STS ! SELECT '6' FROM em4l5ee e #$ERE e8de4t & d8de4t";
&nstead of7
SELECT *2ST2)CT d8de4t_id, d8de4t
FROM de4t d,em4l5ee e
#$ERE e8de4t & e8de4t;

B6 Try to use /#&C# 0LL in place of /#&C#.
<or -)ample: =rite the 1uery as
SELECT id, first_name
FROM student_details_class9:
-)2O) (LL
SELECT id, first_name
FROM s4rts_team;
&nstead of7
SELECT id, first_name, subject
FROM student_details_class9:
-)2O)
SELECT id, first_name
FROM s4rts_team;

C6 $e careful while using conditions in =%'8' clause.
<or -)ample: =rite the 1uery as
SELECT id, first_name, age FROM student_details #$ERE age ; 9:;
&nstead of7
SELECT id, first_name, age FROM student_details #$ERE age %& 9:;
=rite the 1uery as
SELECT id, first_name, age
FROM student_details
#$ERE first_name L2<E 'C+an=';
&nstead of7
SELECT id, first_name, age
FROM student_details
#$ERE S-/STR!first_name,9,>" & 'C+a';
=rite the 1uery as
SELECT id, first_name, age
FROM student_details
#$ERE first_name L2<E )1L ! ?name, '='";
&nstead of7
SELECT id, first_name, age
FROM student_details
#$ERE first_name & )1L ! ?name, first_name";
=rite the 1uery as
SELECT 4rduct_id, 4rduct_name
FROM 4rduct
#$ERE unit_4rice /ET#EE) M(6!unit_4rice" and M2)!unit_4rice"
&nstead of7
SELECT 4rduct_id, 4rduct_name
FROM 4rduct
#$ERE unit_4rice ;& M(6!unit_4rice"
and unit_4rice @& M2)!unit_4rice"
=rite the 1uery as
SELECT id, name, salar5
FROM em4l5ee
#$ERE de4t & 'Electrnics'
()* lcatin & '/angalre';
&nstead of7
SELECT id, name, salar5
FROM em4l5ee
#$ERE de4t AA lcatin& 'Electrnics/angalre';
/se non9column expression on one side of the 1uery because it will be processed earlier.
=rite the 1uery as
SELECT id, name, salar5
FROM em4l5ee
#$ERE salar5 @ BC:::;
&nstead of7
SELECT id, name, salar5
FROM em4l5ee
#$ERE salar5 D 9:::: @ >C:::;
=rite the 1uery as
SELECT id, first_name, age
FROM student_details
#$ERE age ; 9:;
&nstead of7
SELECT id, first_name, age
FROM student_details
#$ERE age )OT & 9:;
D6 /se )'+C)' to avoid the scanning of same rows or *oining the same table repetitively. )'+C)' can
also be made used in place of G8C/P $; or C8)'8 $; clause.
<or -)ample: =rite the 1uery as
SELECT id FROM em4l5ee
#$ERE name L2<E 'Rames+='
and lcatin & '/angalre';
&nstead of7
SELECT *ECO*E!lcatin,'/angalre',id,)-LL" id FROM em4l5ee
#$ERE name L2<E 'Rames+=';
E6 To store large binary ob*ects" first place them in the file system and add the file path in the database.
156 To write 1ueries which provide efficient performance follow the general !L standard rules.
a6 /se single case for all !L verbs
b6 $egin all !L verbs on a new line
c6 eparate all words with a single space
d6 8ight or left aligning verbs within the initial !L verb
Important Microsoft SQL Server Queries
%ere i am going to tell you all the important 1ueries used in (icrosoft !L erver. -ust go through this page
and you will become master in (icrosoft !L erver because all the 1ueries used in daily programming are
briefly explained here.
To create own database
create database demostart
To view the database details
spDhelpdb demostart
To open database
use demostart
To create table in the database
create table emp
(
eno int"
ename varchar(35)"
hiredate datetime"
salary int
)
To see the table information
spDhelp emp
spFhelp:G
&t is ystem defined stored procedure which gives us the information about a table.
To insert data in a table
insert into emp values (355"E,ingE"E359may95FG"H555)
insert into emp values(.55"EddE"E.59april95IG"J455)
insert into emp values (35."EeeE"getdate()"K255) L default print date M time
To insert val"es in a partic"lar col"mn
insert into emp(eno"ename) values (455"ExyxE)
To see all the records
select @from emp
To delete table
drop table emp
To "pdate ename with space where eno=155
update emp set enameNE O where enoN355
To add additional col"mn 0address and phno6 in a table
alter table emp add address varchar(45)"phno varchar(3H)
To see all the records
select @from emp
To modify col"mn si?e
alter table emp alter column address varchar(JH)
To see the table information
spDhelp emp
To modify col"mn name0or rename6
spDrename Oemp.enoE">empnoE
LLLP (old name)9(new name)
To rename table
spDrename OempE">employeeE
To rename of database name
spDrenamedb OdemostartE">demoversionE
%rop table col"mn
alter table employee drop column address"phno
To see all the records
select @from employee
To "pdate ename with HamirI where salary is 37LL
update employee set enameNEamirE where salary is #/LL
To add val"e 1555 in salary field 0addin# temporarly6
select salaryQ3555" salary from employee where empnoN355
To add val"e 1555 in salary field 0addin# permanent6
update employee set salaryN salaryQ3555 where empnoN355
Joperator in sAl serverJ
16.rithmatic :
Q"9"?"@
26comparison :
N"R"S"RN"SN"RS"li,e"between"in" is null.
6lo#ical :
not"and"or
!omparison operator
To see the list those employee whoIs empno is eA"al to 155
select @from employee where empnoN355
To see the list those employee whoIs empno is notGeA"al to 155
select @from employee where empnoRS355
To insert one more record
insert into employee values(353"Eanu*E"E539*an935G".H55)
To see all the records
select @from employee
List of those employee whose salary is less than B555
select @from employee where salary R K555
in operator to show only 155 and 55 record not show in between
select @from employee where empno in(355"455)
in 7we can search for the data based upon the values that are specified in the brac,ets.
the data will be retrieved if the employee number are 355 or 455)
between operator
The data is retrieved from the table based on a certain range of values starting from
the lowerbound to the upperbound.
select @from employee where empno between 355 and .55
li$e operator
used for pattern matching.
'xample79 names starting with a particular character or ending with a particular character.
select @from employee where ename li,e OTrE PErE should be the last char. of ename
select @from employee where ename li,e OaTE PEaE should be the first char. of ename
pattern matchin# with e)act no. of characters
use D (underscore operator)
one D sign means exactly 3 character.
select @from employee where ename li,e OaDDDE
Lo#ical operators:G
To show the list of all employeea whose empno is not e1ual to 355
select @from employee where not empnoN355
To show the list of all employees whose empno is 255 or ename eA"al to amir
select @from employee where empnoN.55 or enameNEamirE
To show the list of all employeea whose empno is 55 and ename eA"al to amir
select @from employee where empnoN455 and enameNEamirE
&dentity col"mn
These are those column which are used for autogetneration of interger values in a particular se1uence.
'x. we can use identity columns to autogenrate the &)Es in the categoryid column of the category table.
There can only be 3 identity column per table.
create table categories
(
catid int identity(3"3)" Pfirst 3 7 starting value
catname varchar(.5)" P.nd 3 7 increamenting value
description varchar(.5)
)
To insert records
insert into categories values(ObeveragesE">teas and coffeesE)
insert into categories values(Ocold drin,sE">fanta pepsiE)
To see all the records
select @from categories
&nsert randomly.
set identityDinsert categories on L when we identityDinsert set is on then we cannot insert dublicate records in
a table.
set identityDinsert categories off L when we identityDinsert set is off then we can insert dublicate records in a
table.
To $now how many datatypes
select @from systypes
To view the names of the "ser defined tables in a database
select name from sysob*ects where xtypeNEuE
!onstraints
These are the ob*ects used to validate the data 'ntry in tables columns.
Type of constraints 79

16 primary $ey :G
chec,s for dublicate and null values.
primary ,ey can be defined for single or composite columns.
one primary per table.

26 "niA"e $eys :G
chec,s for dublicate values. one null value is allowed.

6 chec$s :G
The data must obey the rules of comparison opeators(N"R"S"RN"SN"in"between"li,e).

>6 ,"les :G
They are li,e the chec,s constraints but have certains differences.

%ifference b@w chec$ and ,"les
+hec, constraints are applied with the column definitons.
8ules are created separately and then can be attached with different columns of different tables.
chec,s constraints chec, for existing data.
8ules do not chec, for the existing data.

46 3ot 3"ll :G
we have to 'nter the values on the columns where not null constraints is defined.

B6 <orei#n $ey :G
used for 8eferential integrity.
if we insert a particular data in a table column" then matching data should be inserted
in the column where the foreign ,ey is defined. The foreign ,ey will chec, for data by
referencing the column where data is inserted. The 8eferenced column have primary ,ey or
uni1ue ,ey associated with it.
constraints can be created using the create table or alter table clause.
To define !onstraints :G
create table consdemo
(
cno int primary ,ey"
cname varchar(35) uni1ue"
balance int chec,(balance SH555)
)
insert records
insert consdemo values (355"EabcE"J555) Pcannot be accepted co: applied chec, i.e balanceSH555.
insert consdemo values (355"EabcE"K555) L accepted
insert consdemo values (353"EabcE"2555) Pnot accepted co: cno is primary ,ey and cname applied" uni1ue (i.e
dublicate value not allowed)
To view the names of constraints define on a table
spDhelpconstraint consdemo
To drop the !onstraints
alter table consdemo drop constraint L not run
insert records
insert consdemo values (35."Exy:E"HJ) L not run
p"t chec$ constraint
alter table consdemo add constraint ch, chec,(balanceSH5) Pnot run
"se of forei#n $ey
create table publishers
(
pubid int primary ,ey"
pubname varchar(.5)
)
insert publishers values(3"Eboo, ba:arE)
insert publishers values(."Ewiley 'asternE)
select @from publishers
create table author
(
authid int primary ,ey"
pubid int references publishers(pubid)"
authorname varchar(.5)
)
insert author values(3"."E$ill 'v*enE)
select @from publishers
select @from author
insert author values(."."E$ill 'v*enE)
insert author values(4"3"E$ill 'v*enE)
creatin# constraints by #ivin# "ser defined names :J
create table consdd
(
cno int constraint p, primary ,ey"
cname varchar(35) constraint u, uni1ue"
salary int constraint ch,3 chec,(salarySH555)
)
To view the names of constraints define on a table
spDhelpconstraint consdd
To drop the constraint ch$ in the table of consdd
alter table consdd drop constraint ch,3
To view the names of constraints define on a table
spDhelpconstraint consdd
,7L-S:J
create K .pply ,7L-J
create rule xy: as UaSH555
L Ua 7 &t denotes a variable in s1l server ,nown as a.
To .pply the ,"leJ
spDbindrule xy:"Econsdd.salaryE
P#ote 7 we assign a rule i.e(UaSH555)" so we cannot insert salaryRH555)
select @from consdd
insert consdd values(353">op,3>"K355)99 accepted
insert consdd values(35.">op,.>"355) 99not accepted(not follow the cond. i.e UaSH555)
spDhelpconstraint consdd
To "nbind the r"le
spDunbindrule Oconsdd.salaryE
insert consdd values(35."Eop,.G"355)P after unbind the rule" then the 1uery will be accepted.
To drop the ,"le
drop rule xy:
To view the names of constraints define on a table
spDhelpconstraint consdd
P0nother 'xample of create and applying 8ule
create rule adb as Ua between OaE and OdE
L OaE and OdE is the ist char of cname.
spDbindrule adb" Oconsdd.cnameE
insert consdd values(J55"EedfE"4555)P not accepted co: starting char should a and d.
insert consdd values(J55"EdafE"4555)P not accepted co: starting char should a and d.
insert consdd values(H55"EaefE"4555)P accepted
insert consdd values(455"EadfE"4555)P accepted
insert consdd values(K55"EbrfE"4555)P accepted
insert consdd values(255"EcefE"4555)P accepted
select @from consdd
To "nbind the r"le
spDunbindrule Oconsdd.cnameE
insert consdd values(J55"EedfE"4555)Paccepted (unbind rule)
To drop the ,"le
drop rule adb
composite primary $eyJ
L &t chec,s that the particular row that contains a set of values (ex9S 355"abc)cannot be created again.
create table com,ey
(
cno int"
cname varchar(35)"
address varchar(J5)"
constraint p,, primary ,ey(cno"cname)
)
To chan#e the table name0i.e rename6
spDrename Ocom,eyE" Ocomp,eyE
select @from comp,ey
insert comp,ey values(355"EabdE"E.4?sdsE)
insert comp,ey values(353"EabdE"EJH?dfE)
select @from comp,ey
insert comp,ey values(353"EbdE"EJH?dfE)
insert comp,ey values(355"EabdE"EJH?dfE)
P#ote7 when we use composite ,ey79 you cannot insert the same record at a time.
Pex. we put the record cnoN355 and cnameNabd at ist time it will be accepted but
L .nd time cannot be accepted. but we put cnoN355 and cnameNxy:(i.e cname is different)
L it will be accepted" or we put cnoN.55 (i"e cno is diff. value) and cname is same i.e cnameNabd
L it will be accepted.
%rop primary $ey
alter table comp,ey drop constraint p,,
on delete cascade cla"seJ
L &t is used on foreign ,eys when we are assigning the foreign ,ey on a particular column.
L &t automatically deletes the values from the foreign ,ey cloumn if the primary ,ey value is deleted.
P'x. &f 355 is there in primary ,ey column and also there in the foreign ,ey column" then if 355 is
Pdeleted on primary ,ey column then 355 is automatically deleted from foreign ,ey column.
create table casededemo
(
sno int constraint p,m primary ,ey"
sname varchar(35)
)
create table cascdata
(
sno int constraint f, foreign ,ey references casededemo(sno) on delete cascade"
sales int
)
Pnote7 Oon deleteE used for automatically deleted.
insert into casededemo values(.55"EfghE)
insert into casededemo values(355"Exy:E)
select @from casededemo
insert into cascdata values(.55"K555)
insert into cascdata values(355"J555)
select @from cascdata
delete from casededemo where snoN355 P#ote 7 delete 355 from both table.
select @from cascdata
select @from casededemo
"se of order by and #ro"p by cla"seL
PC8)'8 $; 79 &t is used to sort data either in ascending or descending order.
select @from consdemo
Pinsert two records more in consdemo table
insert into consdemo values(35J"ExxxE"2555)
insert into consdemo values(35."EsssE"I555)
insert into consdemo values(354"EbbbE"2K55)
insert into consdemo values(353"EcccE"2K55)
insert into consdemo values(35H"EdddE"2K55)
insert into consdemo values(35K"EeeeE"2K55)
select @from consdemo
To apply 8,%-, /M in desc order.
select @from consdemo order by cno desc
G,871 /ML
L &t is used to display the data from the aggregate function as well as the data from the table.
To co"nt total balance
select balance"count(balance) from consdemo group by balance
PTo count total cno with own column name i.e O count of cnoE
select cno"count(cno) as Vcount of cnoW from consdemo group by cno
,-ST,&!T&83 8< G,871 /M !L.7S-S J
J(.9&3G cla"seJ
select balance"count(balance)as VresultW from consdemo group by balance having count(balance)S3
J"se the top $eyword in sAl A"eriesJ
PTop ,eyword is used to display the data either from the begining or from the end or from any
L given position in a table.
P'x79 &f we want to view the first 4 records or the last 4 records or the details of records
L in a given range.
PTo print the details of employee who earn the three highest salaries"we can use
PTop ,eyword.
select @from consdemo
Pshow top . recordsP
select top . @from consdemo
Pshow last . record
select top . @from consdemo order by cno desc
JSet operators in sAl serverJ
L These are used to combine the result of . or more 1ueries in a single output.
P'x7 &f we want to view to the details of a column ,nown as salary from first table and also from the
L .nd table" we can use the set operators.
J Two "nion operators:G
3) union 79 0ll the union values are displayed in the result.
.) union 0ll 79 The different values (uni1ue or non uni1ue) are displayed in the result.
J To "se the set operators:G
P3))ata type must be same for the columns mentioned in the 1uery.
P.)The number of columns mentioned in the 1uery.
create table salesdetails
(
sno int"
salary int
)
insert salesdetails values(455"H555)
select @from salesdetails
P #ow create another table which is a copy of the salesdetails table.
create table salesunion
(
sno int"
salary int
)
insert salesunion values(.55"3555)
select @ into salesDunion from salesdetails
select @from salesunion
select @from salesdetails
JTo copy records from another table
select @into salesDdetails from salesdetails
select @from salesDdetails
PTo show salary of salesdetails and sno of salesunion
select salary from salesdetails union select sno from salesunion
PTo show salary of salesdetails and cno of consdemo
select salary from salesdetails union select cno from consdemo
Ptemporary tablesP
create table #emp
(
eno int"
ename varchar(35)
)
insert #emp values(355"EabcE)
select @from #emp
spDhelp #emp
JS7/Q7-,&-SJ
PThese are the s1l statements which are 'mbedded inside another s1l statements.
P'x7 3) To find the details of the person who earn the maximum salary or 4rd highest salary
Pwe have to use the sub1ueries.
Psub1ueries always written in parenthesis.
Psub1ueries evaluate a particular data which can then be used as the input to the main 1uery.
Psub1ueries evaluate first.
Psub1ueries can be nested .3 times.
PT;P' CX /$!/'8&' P
P3) ingle row sub1ueries.
P.) (ultiple 8ow sub1ueries.
P4) sub1ueries using the exist operator.
Ponly 3 row is returned by the sub1uery.
J;7LT&1L- ,8W S7/Q7-,&-SJ
Psub1ueriesPin a single rowL
select @from salesdetails where salaryN(select max(salary) from salesdetails)
Psub1ueriesPin a multiple rowL
select @from salesdetails where salary in(select salary from salesDdetails)
insert salesDdetails values(455"4555)
select @from salesDdetails
Lsub1uery using exits operator
select @from salesdetails where exists(select salary from salesunion where snoN355)
select @from salesdetails where not exists(select salary from salesunion where snoN3K55)
L+oinsL
create table table3
(
sno int"
salary int
)
insert table3 values(355".555)
insert table3 values(.55"J555)
insert table3 values(455"H555)
insert table3 values(J55"K555)
insert table3 values(H55"2555)
select @from table3
create table table.
(
sno int"
salary int
)
insert table. values(K55"2555)
insert table. values(355".555)
insert table. values(.55"J555)
insert table. values(455"H555)
select @from table.
P+8C -C&#P
select @from table3 cross *oin table.
P&##'8 -C&#L
select s.sno"s.salary"t.sno"t.salary from table3 s inner *oin table. t on s.snoNt.sno
Pouter *oinP
select s.sno"s.salary"t.sno"t.salary from table3 s left outer *oin table3 t on s.snoNt.sno
Pright outer *oinP
select s.sno"s.salary"t.sno"t.salary from table3 s right outer *oin table. t on s.snoNt.sno
Pfull outer *oinP
select s.sno"s.salary"t.sno"t.salary from table3 s full outer *oin table. t on s.snoNt.sno
Pself *oinP
alter table table3 add sname varchar(35)
update table. set salaryN455 where salaryN.555
update table3 set snameNEddyE where salaryN455
select @from table3
select @from table.
P1uery of self *oin
select s.sno"t.salary"s.sname from table3 s inner *oin table. t on s.snoNt.salary
JviewsJ
select @from salesdetails
alter table salesdetails add sname varchar(35)
insert salesdetails values(JHK"I55"EffgE)
update salesdetails set snameNEddyE where snoN455
create view vm as select @from salesdetails where snoN355
select @from vm
insert vm values(JHK"I55"EffgE)
Pnot allowed to add record in salesdetails
alter view vm as select @from salesdetails where snoN355 with chec, option
insert vm values(JHK"I55"EffgE)
spDhelptext vm
drop view vm
PP08T&T&C# A&'=P
create view vm as select sno"salary from salesdetails union all select @from salesunion
select @from vm
P8'0)C#L; A&'=P
create view vwd as select count(@) as VcountWfrom salesdetails
select @from vwd
insert vwd values (.4) PcanEt be insert co: itEs read only
Lshow all database views
select @from sysob*ects where xtypeNEvE
Pto show view in one table
spDdepends salesdetails
JST8,-% 1,8!-%7,-J
P3)
create procedure proce
as
select @from emp
proce
P.)
create procedure demo(Ua int"Ub int)
as
declare
Uc int
set UcNUaQUb
print OsumNEQ convert(varchar(35)" Uc)
demo ."4
drop procedure demo
P4)
create procedure 1ues3(Ua int "Ub int)
as
declare
Uc int
set UcNUaQUb
print Uc
1ues3 . "4
spDhelptext demo
PJ)
create procedure 1ues.(Ua varchar(35))
as
declare
Ub varchar(35)
set UbNUa
print ObN OQUb
1ues. Ohello proE
PH)area of circle
create procedure 1ues4(Upi float "Ur float )
as
declare
Uarea float
set UareaNUpi@Ur@Ur
print Oarea of cirNEQconvert(varchar(35)"Uarea)
1ues4 4.3J".
PK)area of triangle
create procedure 1uesJ(Ub int "Uh int)
as
declare
Uarea int
set UareaN(Ub@Uh)?.
print Oarea of triNEQconvert(varchar(35)"Uarea)
1uesJ 4"H
drop procedure 1uesJ
spDhelptext 1uesJ
J&< -LS-J
P3)w.a.proc to find the greatest b?w two nos.
create procedure 1uesH(Ua int"Ub int)
as
if UaSUb
print convert(varchar(H)"Ua)QE a is greaterE
else
print convert(varchar(H)"Ub)QE b is greaterE
1uesH 4"H
P.)w.a.proc to find the greatest b?w three nos.
create procedure 1uesK(Ua int "Ub int "Uc int)
as
if UaSUb
if UaSUc
print O a is gE
else
print Oc is gE
else
if UbSUc
print Ob is gE
else
print Oc is gE
1uesK ."J"4
P4)extracting to database
create procedure 1ues2(Ua int)
as
declare
Unm varchar(35)
select UnmN ename from emp where enoNUa
print Unm
1ues2 353
select @from emp
drop procedure 1ues2
PJ)extracting to database
create procedure 1uesI(Ua varchar(35))
as
declare
Unm varchar(35)
select UnmN ename from emp where enameNUa
if UnmNUa
printEfoundE
else
printEnot foundE
1uesI Oradhi,aE
LL881&3GL
P3)while loop
create procedure whloop (Ua int)
as
while UaR.5
begin
set UaNUaQ3
print Ua
end
whloop 35
99.)print rev order
create procedure whloop3(Uno int)
as
declare
Urev int"Urem int
set UrevN5
while UnoS5
begin
set UremNUnoT35
set UrevNUrev@35QUrem
set UnoNUno?35
end
print Urev
whloop3 3.4J drop procedure whloop3
P4)#'T') P8C+')/8'P
create procedure first
as
print Ofirst procedureE
create procedure second
as
print E.nd procedureE
exec first
second
PX8'' T'BT '08+%&#G
create table ftextsearch
(
fno int primary ,ey"
ename varchar(.5)"
address varchar(J5)
)
select @from ftextsearch
insert ftextsearch values(H5"ExxE"E59.L#E)
select @from ftextsearch where contains (address"E59.L#E)
Pselect address from ftextsearch where addressNE59.L#E
spDhelp ftextsearch
drop table ftextsearch
& want an SQL A"ery G select top 15 records e)cept
for the top 15 records.
0s,ed by7 -erryDPang
have some theory" i thin, it should wor," i havnt figure it out yet. & couldnt get my s1l running.
& *ust need a !L statement that
'L'+T TCP 35 records
X8C( table
=%'8' records #CT ('L'+T TCP 35 from table)
its not wor,ing and it wont run as i expect it.
select top 35 @ employees
from employees
where #CT employeeDid &# (select top 35 employeeDid from employee)
no views pls. *ust s1l statement.
basically the 1uery means select the next 35 records after the first top 35 records.
What is normali?ation? -)plain different levels of normali?ation?
+hec, out the article !35534F from (icrosoft ,nowledge base and of course" there>s much more information
available in the net. &t will be a good idea to get a hold of any 8)$( fundamentals text boo," especially the
one by +. -. )ate. (ost of the times" it will be o,ay if you can explain till third normal form.
What is deGnormali?ation and when wo"ld yo" #o for it?
0s the name indicates" de9normali:ation is the reverse process of normali:ation. &t is the controlled
introduction of redundancy in to the database design. &t helps improve the 1uery performance as the number
of *oins could be reduced.
(ow do yo" implement oneGtoGone' oneGtoGmany and manyGtoGmany relationships while desi#nin#
tables?
Cne9to9Cne relationship can be implemented as a single table and rarely as two tables with primary and
foreign ,ey relationships. Cne9to9(any relationships are implemented by splitting the data into two tables
with primary ,ey and foreign ,ey relationships. (any9to9(any relationships are implemented using a
*unction table with the ,eys from both the tables forming the composite primary ,ey of the *unction table.
&t will be a good idea to read up a database designing fundamentals text boo,.
What:s the difference between a primary $ey and a "niA"e $ey?
$oth primary ,ey and uni1ue enforce uni1ueness of the column on which they are defined. $ut by default
primary ,ey creates a clustered index on the column" where as uni1ue creates a non9clustered index by
default. 0nother ma*or difference is that" primary ,ey does not allow )-LLs" but uni1ue ,ey allows one )-LL
only.
What are "ser defined data types and when yo" sho"ld #o for them?
/ser defined data types let you extend the base !L erver data types by providing a descriptive name" and
format to the database. Ta,e for example" in your database" there is a column called Flig+t_)um which
appears in many tables. &n all these tables it should be 3arc+ar!E". &n this case you could create a user
defined data type called Flig+t_num_t54e of 3arc+ar!E" and use it across all your tables.
ee s4_addt54e" s4_dr4t54e in boo,s online.
What is bit data type and what:s the information that can be stored inside a bit col"mn?
$it data type is used to store $oolean information li,e 3 or 5 (true or false). /ntil !L erver K.H bit data
type could hold either a 3 or 5 and there was no support for )-LL. $ut from !L erver 2.5 onwards" bit data
type can represent a third state" which is )-LL.
%efine candidate $ey' alternate $ey' composite $ey.
0 candidate Fe5 is one that can identify each row of a table uni1uely. Generally a candidate ,ey becomes
the primary ,ey of the table. &f the table has more than one candidate ,ey" one of them will become the
primary ,ey" and the rest are called alternate Fe5s.
0 ,ey formed by combining at least two or more columns is called cm4site Fe5.
What are defa"lts? &s there a col"mn to which a defa"lt cannot be bo"nd?
0 default is a value that will be used by a column" if no value is supplied to that column while inserting data.
2*E)T2T0 columns and timestamp columns can>t have defaults bound to them. ee CRE(TE *EF(-LT in boo,s
online.
What is a transaction and what are .!&% properties?
0 transaction is a logical unit of wor, in which" all the steps must be performed or none. (C2* stands for
0tomicity" +onsistency" &solation" )urability. These are the properties of a transaction. Xor more information
and explanation of these properties" see !L erver boo,s online or any R*/MS fundamentals text boo,.
-)plain different isolation levels
0n isolation level determines the degree of isolation of data between concurrent transactions. The default
!L erver isolation level is 8ead +ommitted. %ere are the other isolation levels (in the ascending order of
isolation)7 8ead /ncommitted" 8ead +ommitted" 8epeatable 8ead" eriali:able. ee !L erver boo,s online
for an explanation of the isolation levels. $e sure to read about SET TR()S(CT2O) 2SOL(T2O) LE1EL" which
lets you customi:e the isolation level at the connection level.
CRE(TE 2)*E6 m52ndeG O) m5Table !m5Clumn"
What type of &nde) will #et created after e)ec"tin# the above statement?
#on9clustered index. &mportant thing to note7 $y default a clustered index gets created on the primary ,ey"
unless specified otherwise.
What is the ma)im"m si?e of a row?
I5K5 bytes. )o not be surprised with 1uestions li,e >=hat is the maximum number of columns per table>.
+hec, out !L erver boo,s online for the page titled7 <(aximum +apacity pecifications<.
-)plain .ctive@.ctive and .ctive@1assive cl"ster confi#"rations
%opefully you have experience setting up cluster servers. $ut if you do not" at least be familiar with the way
clustering wor,s and the two clustering configurations 0ctive?0ctive and 0ctive?Passive. !L erver boo,s
online has enough information on this topic and there is a good white paper available on (icrosoft site.
-)plain the architect"re of SQL Server
This is a very important 1uestion and you better be able to answer it if consider yourself a )$0. !L erver
boo,s online is the best place to read about !L erver architecture. 8ead up the chapter dedicated to !L
erver 0rchitecture.
What is Loc$ -scalation?
Loc, escalation is the process of converting a lot of low level loc,s (li,e row loc,s" page loc,s) into higher
level loc,s (li,e table loc,s). 'very loc, is a memory structure too many loc,s would mean" more memory
being occupied by loc,s. To prevent this from happening" !L erver escalates the many fine9grain loc,s to
fewer coarse9grain loc,s. Loc, escalation threshold was definable in !L erver K.H" but from !L erver
2.5 onwards it>s dynamically managed by !L erver.
What:s the difference between %-L-T- T./L- and T,73!.T- T./L- commands?
*ELETE T(/LE is a logged operation" so the deletion of each row gets logged in the transaction log" which
ma,es it slow. TR-)C(TE T(/LE also deletes all the rows in a table" but it will not log the deletion of each
row" instead it logs the de9allocation of the data pages of the table" which ma,es it faster. Cf course" TR-)C(TE
T(/LE can be rolled bac,.
-)plain the stora#e models of 8L.1
+hec, out MOL(." ROL(. and $OL(. in !L erver boo,s online for more information.
=hat are the new features introduced in !L erver .555 (or the latest release of !L erver at the time of
your interview)6 =hat changed between the previous version of !L erver and the current version6
This 1uestion is generally as,ed to see how current is your ,nowledge. Generally there is a section in the
beginning of the boo,s online titled <=hat>s #ew<" which has all such information. Cf course" reading *ust
that is not enough" you should have tried those things to better answer the 1uestions. 0lso chec, out the
section titled <$ac,ward +ompatibility< in boo,s online which tal,s about the changes that have ta,en place
in the new version.
What are constraints? -)plain different types of constraints.
+onstraints enable the 8)$( enforce the integrity of the database automatically" without needing you to
create triggers" rule or defaults.
Types of constraints7 )OT )-LL, C$EC<, -)2H-E, .R2M(R0 <E0, FORE2,) <E0
Xor an explanation of these constraints see boo,s online for the pages titled7 <Cnstraints< and <CRE(TE
T(/LE<" <(LTER T(/LE<
What is an inde)? What are the types of inde)es? (ow many cl"stered inde)es can be created on a
table? & create a separate inde) on each col"mn of a table. what are the advanta#es and disadvanta#es
of this approach?
&ndexes in !L erver are similar to the indexes in boo,s. They help !L erver retrieve the data 1uic,er.
&ndexes are of two types. +lustered indexes and non9clustered indexes. =hen you create a clustered index on
a table" all the rows in the table are stored in the order of the clustered index ,ey. o" there can be only one
clustered index per table. #on9clustered indexes have their own storage separate from the table data storage.
#on9clustered indexes are stored as $9tree structures (so do clustered indexes)" with the leaf level nodes
having the index ,ey and it>s row locater. The row located could be the 8&) or the +lustered index ,ey"
depending up on the absence or presence of clustered index on the table.
&f you create an index on each column of a table" it improves the 1uery performance" as the 1uery optimi:er
can choose from all the existing indexes to come up with an efficient execution plan. 0t the same time" data
modification operations (such as 2)SERT, -.*(TE, *ELETE) will become slow" as every time data changes in
the table" all the indexes need to be updated. 0nother disadvantage is that" indexes need dis, space" the more
indexes you have" more dis, space is used.
What is ,.&% and what are different types of ,.&% confi#"rations?
R(2* stands for Redundant (rra5 f 2neG4ensi3e *isFs" used to provide fault tolerance to database
servers. There are six R(2* levels 5 through H offering different levels of performance" fault tolerance. ()#
has some information about R(2* levels and for detailed information" chec, out the 80&) advisory board>s
homepage
What are the steps yo" will ta$e to improve performance of a poor performin# A"ery?
This is a very open ended 1uestion and there could be a lot of reasons behind the poor performance of a 1uery.
$ut some general issues that you could tal, about would be7 #o indexes" table scans" missing or out of date
statistics" bloc,ing" excess recompilations of stored procedures" procedures and triggers without SET )OCO-)T
O)" poorly written 1uery with unnecessarily complicated *oins" too much normali:ation" excess usage of
cursors and temporary tables.
ome of the tools?ways that help you troubleshooting performance problems are7
SET S$O#.L()_(LL O),
SET S$O#.L()_TE6T O),
SET ST(T2ST2CS 2O O),
!L erver Profiler"
=indows #T ?.555 Performance monitor"
Graphical execution plan in !uery 0naly:er.
)ownload the white paper on performance tuning !L erver from (icrosoft web site.
What are the steps yo" will ta$e' if yo" are tas$ed with sec"rin# an SQL Server?
0gain this is another open ended 1uestion. %ere are some things you could tal, about7 Preferring #T
authentication" using server" database and application roles to control access to the data" securing the physical
database files using )TFS permissions" using an unguessable S( password" restricting physical access to the
!L erver" renaming the 0dministrator account on the !L erver computer" disabling the Guest account"
enabling auditing" using multi9protocol encryption" setting up SSL" setting up firewalls" isolating !L erver
from the web server etc.
8ead the white paper on !L erver security from (icrosoft website. 0lso chec, out (y !L erver
security best practices
What is a deadloc$ and what is a live loc$? (ow will yo" #o abo"t resolvin# deadloc$s?
)eadloc, is a situation when two processes" each having a loc, on one piece of data" attempt to ac1uire a loc,
on the other>s piece. 'ach process would wait indefinitely for the other to release the loc," unless one of the
user processes is terminated. !L erver detects deadloc,s and terminates one user>s process.
0 liveloc, is one" where a re1uest for an exclusive loc, is repeatedly denied because a series of overlapping
shared loc,s ,eeps interfering. !L erver detects the situation after four denials and refuses further shared
loc,s. 0 liveloc, also occurs when read transactions monopoli:e a table or page" forcing a write transaction to
wait indefinitely.
+hec, out SET *E(*LOC<_.R2OR2T0 and <MinimiIing *eadlcFs< in !L erver boo,s online. 0lso
chec, out the article !3KFFK5 from (icrosoft ,nowledge base.
What is bloc$in# and how wo"ld yo" tro"bleshoot it?
$loc,ing happens when one connection from an application holds a loc, and a second connection re1uires a
conflicting loc, type. This forces the second connection to wait" bloc,ed on the first.
8ead up the following topics in !L erver boo,s online7 /nderstanding and avoiding bloc,ing" +oding
efficient transactions.
-)plain !,-.T- %.T./.S- synta)
(any of us are used to creating databases from the 'nterprise (anager or by *ust issuing the command7
CRE(TE *(T(/(SE M5*/.
$ut what if you have to create a database with two file groups" one on drive + and the other on drive ) with
log on drive ' with an initial si:e of K55 ($ and with a growth factor of 3HT6 That>s why being a )$0 you
should be familiar with the CRE(TE *(T(/(SE syntax. +hec, out !L erver boo,s online for more
information.
(ow to restart SQL Server in sin#le "ser mode? (ow to start SQL Server in minimal confi#"ration
mode?
!L erver can be started from command line" using the SHLSER1R8E6E. This 'B' has some very important
parameters with which a )$0 should be familiar with. 9m is used for starting !L erver in single user mode
and Jf is used to start the !L erver in minimal configuration mode. +hec, out !L erver boo,s online
for more parameters and their explanations.
.s a part of yo"r +ob' what are the %/!! commands that yo" commonly "se for database
maintenance?
*/CC C$EC<*/,
*/CC C$EC<T(/LE,
*/CC C$EC<C(T(LO,,
*/CC C$EC<(LLOC,
*/CC S$O#CO)T2,,
*/CC S$R2)<*(T(/(SE,
*/CC S$R2)<F2LE etc.
$ut there are a whole load of )$++ commands which are very useful for )$0s. +hec, out !L erver
boo,s online for more information.
What are statistics' "nder what circ"mstances they #o o"t of date' how do yo" "pdate them?
tatistics determine the selectivity of the indexes. &f an indexed column has uni1ue values then the selectivity
of that index is more" as opposed to an index with non9uni1ue values. !uery optimi:er uses these indexes in
determining whether to choose an index or not while executing a 1uery.
ome situations under which you should update statistics7
3. &f there is significant change in the ,ey values in the index
.. &f a large amount of data in an indexed column has been added" changed" or removed (that is" if the
distribution of ,ey values has changed)" or the table has been truncated using the T8/#+0T'
T0$L' statement and then repopulated
4. )atabase is upgraded from a previous version
Loo, up !L erver boo,s online for the following commands7
-.*(TE ST(T2ST2CS,
ST(TS_*(TE,
*/CC S$O#_ST(T2ST2CS,
CRE(TE ST(T2ST2CS,
*RO. ST(T2ST2CS,
s4_autstats,
s4_createstats,
s4_u4datestats
What are the different ways of movin# data@databases between servers and databases in SQL Server?
There are lots of options available" you have to choose your option depending upon your re1uirements. ome
of the options you have are7
/(C<-.KRESTORE"
*etac+ing and attac+ing databases,
Re4licatin,
*TS,
/C.,
lgs+i44ing"
2)SERT888SELECT,
SELECT8882)TO"
creating 2)SERT scripts to generate data.
-)plain different types of /.!271s available in SQL Server? Given a partic"lar scenario' how wo"ld
yo" #o abo"t choosin# a bac$"p plan?
Types of bac,ups you can create in !L ever 2.5Q are Xull database bac,up" differential database bac,up"
transaction log bac,up" filegroup bac,up. +hec, out the /(C<-. and RESTORE commands in !L erver
boo,s online. $e prepared to write the commands in your interview. $oo,s online also has information on
detailed bac,up?restore architecture and when one should go for a particular ,ind of bac,up.
What is database replication? What are the different types of replication yo" can set "p in SQL Server?
8eplication is the process of copying?moving data between databases on the same or different servers. !L
erver supports the following types of replication scenarios7
@ napshot replication
@ Transactional replication (with immediate updating subscribers" with 1ueued updating subscribers)
@ (erge replication
ee !L erver boo,s online for in9depth coverage on replication. $e prepared to explain how different
replication agents function" what are the main system tables used in replication etc.
(ow to determine the service pac$ c"rrently installed on SQL Server?
The global variable LL1ersin stores the build number of the sMlser3r8eGe" which is used to determine the
service pac, installed. To ,now more about this process visit !L erver service pac,s and versions.
What are c"rsors? -)plain different types of c"rsors. What are the disadvanta#es of c"rsors? (ow can
yo" avoid c"rsors?
+ursors allow row9by9row processing of the resultsets.
Types of cursors7
Static,
*5namic,
Fr7ardJnl5,
<e5setJdri3en8
ee boo,s online for more information.
)isadvantages of cursors7 'ach time you fetch a row from the cursor" it results in a networ, roundtrip" where
as a normal SELECT 1uery ma,es only one round trip" however large the resultset is. +ursors are also costly
because they re1uire more resources and temporary storage (results in more &C operations). Xurther" there are
restrictions on the SELECT statements that can be used with some types of cursors.
(ost of the times" set based operations can be used instead of cursors. %ere is an example7
&f you have to give a flat hi,e to your employees using the following criteria7
Salar5 bet7een >:::: and N:::: JJ C::: +iFe
Salar5 bet7een N:::: and CC::: JJ O::: +iFe
Salar5 bet7een CC::: and PC::: JJ Q::: +iFe
&n this situation many developers tend to use a cursor" determine each employee>s salary and update his salary
according to the above formula. $ut the same can be achieved by multiple update statements or can be
combined in a single -.*(TE statement as shown below7
-.*(TE tbl_em4 SET salar5 &
C(SE #$E) salar5 /ET#EE) >:::: ()* N:::: T$E) salar5 D C:::
#$E) salar5 /ET#EE) N:::: ()* CC::: T$E) salar5 D O:::
#$E) salar5 /ET#EE) CC::: ()* PC::: T$E) salar5 D 9::::
E)*
0nother situation in which developers tend to use cursors7 ;ou need to call a stored procedure when a column
in a particular row meets certain condition. ;ou don>t have to use cursors for this. This can be achieved using
#$2LE loop" as long as there is a uni1ue ,ey to identify each row.
Write down the #eneral synta) for a S-L-!T statements coverin# all the options.
%ere>s the basic syntax7 (0lso chec,out SELECT in boo,s online for advanced syntax).
SELECT select_list
R2)TO ne7_table_S
FROM table_surce
R#$ERE searc+_cnditinS
R,RO-. /0 gru4_b5__eG4ressinS
R$(12), searc+_cnditinS
ROR*ER /0 rder__eG4ressin R(SC A *ESCS S
What is a +oin and e)plain different types of +oins?
-oins are used in 1ueries to explain how different tables are related. -oins also let you select data from a table
depending upon data from another table.
Types of *oins7
2))ER TO2)s,
O-TER TO2)s,
CROSS TO2)s
O-TER TO2)s are further classified as
LEFT O-TER TO2)S,
R2,$T O-TER TO2)S and
F-LL O-TER TO2)S8
Xor more information see pages from boo,s online titled7 <Join Fundamentals< and <Using Joins<.
!an yo" have a nested transaction?
;es" very much. +hec, out /E,2) TR(), COMM2T, ROLL/(C<, S(1E TR() and LLTR()CO-)T
What is an e)tended stored proced"re? !an yo" instantiate a !8; ob+ect by "sin# TGSQL?
0n extended stored procedure is a function within a )LL (written in a programming language li,e +" +QQ
using Cpen )ata ervices (C)) 0P&) that can be called from T9!L" *ust the way we call normal stored
procedures using the E6EC statement. ee boo,s online to learn how to create extended stored procedures and
how to add them to !L erver.
;es" you can instantiate a +C( (written in languages li,e A$" A+QQ) ob*ect from T9!L by using
s4_O(Create stored procedure.
0lso see boo,s online for s4_O(Met+d" s4_O(,et.r4ert5" s4_O(Set.r4ert5" s4_O(*estr5.
What is the system f"nction to #et the c"rrent "ser:s "ser id?
-SER_2*!"8 0lso chec, out other system functions li,e
-SER_)(ME!",
S0STEM_-SER,
SESS2O)_-SER,
C-RRE)T_-SER,
-SER,
S-SER_S2*!",
$OST_)(ME!"8
What are tri##ers? (ow many tri##ers yo" can have on a table? (ow to invo$e a tri##er on demand?
Triggers are special ,ind of stored procedures that get executed automatically when an 2)SERT, -.*(TE or
*ELETE operation ta,es place on a table.
&n !L erver K.H you could define only 4 triggers per table" one for 2)SERT" one for -.*(TE and one for
*ELETE. Xrom !L erver 2.5 onwards" this restriction is gone" and you could create multiple triggers per
each action. $ut in 2.5 there>s no way to control the order in which the triggers fire. &n !L erver .555 you
could specify which trigger fires first or fires last using s4_settriggerrder
Triggers cannot be invo,ed on demand. They get triggered only when an associated action (2)SERT,
-.*(TE, *ELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules" auditing. Triggers can also be used to extend the
referential integrity chec,s" but wherever possible" use constraints for this purpose" instead of triggers" as
constraints are much faster.
Till !L erver 2.5" triggers fire only after the data modification operation happens. o in a way" they are
called post triggers. $ut in !L erver .555 you could create pre triggers also. earch !L erver .555
boo,s online for 2)STE(* OF triggers.
0lso chec, out boo,s online for >inserted table>" >deleted table> and COL-M)S_-.*(TE*!"
There is a trigger defined for 2)SERT operations on a table" in an OLT. system. The trigger is written to
instantiate a COM ob*ect and pass the newly inserted rows to it for some custom processing.
What do yo" thin$ of this implementation? !an this be implemented better?
&nstantiating COM ob*ects is a time consuming process and since you are doing it from within a trigger" it slows
down the data insertion process. ame is the case with sending emails from triggers. This scenario can be
better implemented by logging all the necessary data into a separate table" and have a *ob which periodically
chec,s this table and does the needful.

.ds

What is a self +oin? -)plain it with an e)ample.
elf *oin is *ust li,e any other *oin" except that two instances of the same table will be *oined in the 1uery.
%ere is an example7 'mployees table which contains rows for normal employees as well as managers. o" to
find out the managers of all the employees" you need a self *oin.
CRE(TE T(/LE em4
!
em4id int,
mgrid int,
em4name c+ar!9:"
"
2)SERT em4 SELECT 9,B,'15as'
2)SERT em4 SELECT B,>,'M+an'
2)SERT em4 SELECT >,)-LL,'S+b+a'
2)SERT em4 SELECT N,B,'S+rid+ar'
2)SERT em4 SELECT C,B,'Surab+'
SELECT t98em4name REm4l5eeS, tB8em4name RManagerS
FROM em4 t9, em4 tB
#$ERE t98mgrid & tB8em4id
%ere is an advanced 1uery using a LEFT O-TER TO2) that even returns the employees without managers
(super bosses)
SELECT t98em4name REm4l5eeS, CO(LESCE!tB8em4name, ') manager'" RManagerS
FROM em4 t9
LEFT O-TER TO2)
em4 tB
O)
t98mgrid & tB8em4id

Das könnte Ihnen auch gefallen