You are on page 1of 182

System Databases in SQL Server

System databases are an integral part of the SQL Server product as it depends on the System
Databases to function. Having a good knowledge of System Databases will help the Database
Administrator to perform day-to-day tasks effectively.
System Database in SQL Server !!" # !!$ %ersions
Master Database
&he 'aster database basically consists of two physical files( namely master.mdf )data file* and
mastlog.ldf )log file*. +y default when you are installing SQL Server !!$ the master database
related data and log file are installed in the following folder location Drive,-.rogram
/iles-'icrosoft SQL Server-'SSQL0!.'SSQLS12%12-'SSQL-DA&A-. 3f master database is
corrupted or if it is not available then the SQL Server Service will not start.
Model Database
&he 'odel database basically consists of two physical files namely 'odel.mdf )data file* and
'odelLog.ldf )log file*.
.hysical .ath---- Drive,-.rogram /iles-'icrosoft SQL
Server-'SSQL0!.'SSQLS12%12-'SSQL-DA&A-. 3f the 'odel database is damaged or
corrupted then SQL Server Service will not start up as it will not be able to create the tempdb
database.
MSDB Database

&he 'SD+ database basically consists of two physical files namely 'SD+Data.mdf )data file*
and 'SD+Log.ldf )log file*. +y default when you are installing SQL Server !!$ the 'SD+
database related data and log file are created in the following folder location Drive,-.rogram
/iles-'icrosoft SQL Server-'SSQL0!.'SSQLS12%12-'SSQL-DA&A-. 3f the 'SD+
database is corrupted or damaged then scheduling information used by SQL Server Agent will be
lost.
TempDB Database
&he &empD+ database basically consists of two physical files namely tempdb.mdf )data file*
and templog.ldf )log file*. +y default when you are installing SQL Server !!$ the &empD+
database related data and log file are created in the following folder location Drive,-.rogram
/iles-'icrosoft SQL Server-'SSQL0!.'SSQLS12%12-'SSQL-DA&A-.
Resource Database
&he physical file names of 2esource database is mss4lsystemresource.mdf and
mss4lsystemresource.ldf.
Drive,-.rogram /iles-'icrosoft SQL Server-'SSQL0!.'SSQLS12%12-'SSQL-+inn
ReportServer
&he 2eportServer database is created when a user installs SQL Server 2eporting Service. &his
database basically stores all the metadata and ob5ect related information which is used by
reporting services.
&he 2eportServer database basically consists of two physical files namely 2eportServer.mdf
)data file* and 2eportServer6log.ldf )log file*. +y default when you are installing SQL Server
!!$ 2eporting Services the 2eportServer database related data and log file are created in the
following folder location Drive,-.rogram /iles-'icrosoft SQL
Server-'SSQL0!.'SSQLS12%12-'SSQL-DA&A-.
ReportServerTempDB
&he 2eportServer&empD+ database basically consists of two physical files namely
2eportServer&empD+.mdf )data file* and 2eportServer&empD+6log.ldf )log file*. +y default
when you are installing SQL Server !!$ 2eporting Services the 2eportServer database related
data and log file are created in the following folder location Drive,-.rogram /iles-'icrosoft SQL
Server-'SSQL0!.'SSQLS12%12-'SSQL-DA&A-.
Distribution
&he distribution database basically consists of two physical files namely distribution.mdf )data
file* and distribution6log.ldf )log file*. +y default when you are configuring replication the
distribution database related data and log file are created in the following folder location
Drive,-.rogram /iles-'icrosoft SQL Server-'SSQL0!.'SSQLS12%12-'SSQL-DA&A-.
Create Database Command:
7reates a new database and the files used to store the database( or attaches a database from the
files of a previously created database.
A ma8imum of 9(:;: databases can be specified on a server.
&here are three types of files used to store a database,
&he primary file contains the startup information for the database. &he primary file is also
used to store data. 1very database has one primary file.
Secondary files hold all of the data that does not fit in the primary data file. Databases
need not have any secondary data files if the primary file is large enough to hold all of the
data in the database. <ther databases may be large enough to need multiple secondary
data files( or they may use secondary files on separate disk drives to spread the data
across multiple disks.
&ransaction log files hold the log information used to recover the database. &here must be
at least one transaction log file for each database( although there may be more than one.
&he minimum si=e for a transaction log file is "0 >+.
1very database has at least two files( a primary file and a transaction log file.
File type File name extension
.rimary data file .mdf
Secondary data file .ndf
&ransaction log file .ldf
Note &he master database should be backed up when a user database is created.
/ractions cannot be specified in the S3?1( 'A@S3?1( and /3L1A2<B&H parameters. &o
specify a fraction of a megabyte in S3?1 parameters( convert to kilobytes by multiplying the
number by 0(!C. /or e8ample( specify 0("9; >+ instead of 0." '+ )0." multiplied by 0(!C
e4uals 0("9;*.
Bhen a simple 721A&1 DA&A+AS1 database_name statement is specified with no additional
parameters( the database is made the same si=e as the model database.
! Create a database t"at speci#ies t"e data and transaction lo$ #iles
&his e8ample creates a database called Sales. +ecause the keyword .23'A2D is not used( the
first file )Sales%dat* becomes the primary file. +ecause neither '+ or >+ is specified in the
S3?1 parameter for the Sales%dat file( it defaults to '+ and is allocated in megabytes. &he
Sales%lo$ file is allocated in megabytes because the '+ suffi8 is e8plicitly stated in the S3?1
parameter.
USE master
GO
CREATE DATABASE Sales
ON
( NAME = Sales_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\saledat.mdf',
SIE = !",
MA#SIE = $",
FILE%&'()* = $ +
LOG ON
( NAME = 'Sales_log',
FILENAME = 'c:\program files\microsoft sql server\mssql\data\salelog.ldf',
SIE = $M,,
MA#SIE = -$M,,
FILE%&'()* = $M, +
GO
B! Create a database speci#yin$ multiple data and transaction lo$ #iles
&his e8ample creates a database called rc"ive with three 0!!-'+ data files and two 0!!-'+
transaction log files. &he primary file is the first file in the list and is e8plicitly specified with the
.23'A2D keyword. &he transaction log files are specified following the L<A <E keywords.
Eote the e8tensions used for the files in the /3L1EA'1 option, .mdf is used for primary data
files( .ndf is used for the secondary data files( and .ldf is used for transaction log files.
USE master
GO
CREATE DATABASE Arc!"e
ON
#R$MAR% ( NAME = Arc&,
FILENAME = 'c:\program files\microsoft sql
server\mssql\data\arc.dat!.mdf',
SIE = !""M,,
MA#SIE = -"",
FILE%&'()* = -"+,
( NAME = Arc',
FILENAME = 'c:\program files\microsoft sql server\mssql\data\arc.dat-./df',
SIE = !""M,,
MA#SIE = -"",
FILE%&'()* = -"+,
( NAME = Arc(,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\arc.dat0./df',
SIE = !""M,,
MA#SIE = -"",
FILE%&'()* = -"+
LOG ON
( NAME = Arclog&,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\arc.log!.ldf',
SIE = !""M,,
MA#SIE = -"",
FILE%&'()* = -"+,
( NAME = Arclog',
FILENAME = 'c:\program files\microsoft sql server\mssql\data\arc.log-.ldf',
SIE = !""M,,
MA#SIE = -"",
FILE%&'()* = -"+
GO
C! Create a simple database
&his e8ample creates a database called &roducts and specifies a single file. &he file specified
becomes the primary file( and a 0-'+ transaction log file is automatically created. +ecause
neither '+ or >+ is specified in the S'() parameter for the primary file( the primary file is
allocated in megabytes. +ecause there is no FfilespecG for the transaction log file( the transaction
log file has no 'A@S3?1 and can grow to fill all available disk space.
USE master
GO
CREATE DATABASE #rod)cts
ON
( NAME = *rods_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\prods.mdf',
SIE = 1,
MA#SIE = !",
FILE%&'()* = ! +
GO
D! Create a database *it"out speci#yin$ #iles
&his e8ample creates a database named mytest and creates a corresponding primary and
transaction log file. +ecause the statement has no FfilespecG items( the primary database file is
the si=e of the model database primary file. &he si=e of the transaction log is the larger of these
values,." '+ or " percent of the sum of the si=es of all the data files for the database. +ecause
'A@S3?1 is not specified( the files can grow to fill all available disk space.
CREATE DATABASE +!deoRe,talS-stem
)! Create a database *it"out speci#yin$ S'()
&his e8ample creates a database named products+. &he file prods+%dat becomes the primary
file with a si=e e4ual to the si=e of the primary file in the model database. &he transaction log file
is created automatically and is " percent of the si=e of the primary file( or "0 >+( whichever is
larger. +ecause 'A@S3?1 is not specified( the files can grow to fill all available disk space.
USE master
GO
CREATE DATABASE #rod)cts'
ON
( NAME = *rods'_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\prods-.mdf' +
GO
All databases have at least a primary filegroup. All system tables are allocated in
the primary filegroup. A database can also have user-defined filegroups. 3f an
ob5ect is created with an <E filegroup clause specifying a user-defined filegroup(
then all the pages for the ob5ect are allocated from the specified filegroup.
F! Create a database *it" #ile$roups
&his e8ample creates a database named sales with three filegroups,
&he primary filegroup with the files Spri,%dat and Spri+%dat. &he /3L1A2<B&H
increments for these files is specified as 0" percent.
A filegroup named Sales-roup, with the files S-rp,Fi, and S-rp,Fi+.
A filegroup named Sales-roup+ with the files S-rp+Fi, and S-rp+Fi+.
CREATE DATABASE Sales
ON #R$MAR%
( NAME = S#r!&_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\S2ri!dat.mdf',
SIE = !",
MA#SIE = $",
FILE%&'()* = !$3 +,
( NAME = S#r!'_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\S2ri-dt./df',
SIE = !",
MA#SIE = $",
FILE%&'()* = !$3 +,
.$LEGROU# SalesGro)*&
( NAME = SGr*&.!&_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\S%!Fi!dt./df',
SIE = !",
MA#SIE = $",
FILE%&'()* = $ +,
( NAME = SGr*&.!'_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\S%!Fi-dt./df',
SIE = !",
MA#SIE = $",
FILE%&'()* = $ +,
.$LEGROU# SalesGro)*'
( NAME = SGr*'.!&_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\S%-Fi!dt./df',
SIE = !",
MA#SIE = $",
FILE%&'()* = $ +,
( NAME = SGr*'.!'_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\S%-Fi-dt./df',
SIE = !",
MA#SIE = $",
FILE%&'()* = $ +
LOG ON
( NAME = 'Sales_log',
FILENAME = 'c:\program files\microsoft sql server\mssql\data\salelog.ldf',
SIE = $M,,
MA#SIE = -$M,,
FILE%&'()* = $M, +
GO
SQL Server Datatypes
Data types in SQL Server are organi=ed into the following categories,
18act numerics Hnicode character strings
Appro8imate numerics +inary strings
Date and time <ther data types
7haracter strings
3n SQL Server( based on their storage characteristics( some data types are
designated as belonging to the following groups,
Large value data types, varchar)ma8*( nvarchar)ma8*( and varbinary)ma8*
Large ob5ect data types, te8t( nte8t( image( varchar)ma8*( nvarchar)ma8*(
varbinary)ma8*( and 8ml
)xact Numerics
'nte$ers
bigint
3nteger )whole number* data from -I;9 )-J(9(9:(!9;($"C(::"($!$* through
I;9-0 )J(9(9:(!9;($"C(::"($!:*.
int
3nteger )whole number* data from -I90 )-(0C:(C$9(;C$* through I90 - 0
)(0C:(C$9(;C:*.
smallint
3nteger data from -I0" )-9(:;$* through I0" - 0 )9(:;:*.
tinyint
3nteger data from ! through "".
bit
3nteger data with either a 0 or ! value.
decimal
/i8ed precision and scale numeric data from -0!I9$ K0 through 0!I9$ L0.
numeric
/unctionally e4uivalent to decimal!
money
'onetary data values from -I;9 )-J(99:(!9(;$"(C::."$!$* through I;9 - 0
)KJ(99:(!9(;$"(C::."$!:*( with accuracy to a ten-thousandth of a monetary
unit.
smallmoney
'onetary data values from -0C(:C$.9;C$ through K0C(:C$.9;C:( with accuracy
to a ten-thousandth of a monetary unit.
pproximate Numerics
float
/loating precision number data with the following valid values, -0.:J1 K 9!$
through -.91 - 9!$( ! and .91 K 9!$ through 0.:J1 K 9!$.
real
/loating precision number data with the following valid values, -9.C!1 K 9$
through -0.0$1 - 9$( ! and 0.0$1 - 9$ through 9.C!1 K 9$.
datetime and smalldatetime
datetime
Date and time data from Manuary 0( 0:"9( through December 90( JJJJ( with an
accuracy of three-hundredths of a second( or 9.99 milliseconds.
smalldatetime
Date and time data from Manuary 0( 0J!!( through Mune ;( !:J( with an accuracy
of one minute.
C"aracter Strin$s
char
/i8ed-length non-Hnicode character data with a ma8imum length of $(!!!
characters.
varchar
%ariable-length non-Hnicode data with a ma8imum of $(!!! characters.
te8t
%ariable-length non-Hnicode data with a ma8imum length of I90 - 0
)(0C:(C$9(;C:* characters.
.nicode C"aracter Strin$s
nchar
/i8ed-length Hnicode data with a ma8imum length of C(!!! characters.
nvarchar
%ariable-length Hnicode data with a ma8imum length of C(!!! characters.
sysname is a system-supplied user-defined data type that is functionally e4uivalent
to nvarc"ar/,+01 and is used to reference database ob5ect names.
nte8t
%ariable-length Hnicode data with a ma8imum length of I9! - 0 )0(!:9(:C0($9*
characters.
Binary Strin$s
binary
/i8ed-length binary data with a ma8imum length of $(!!! bytes.
varbinary
%ariable-length binary data with a ma8imum length of $(!!! bytes.
image
%ariable-length binary data with a ma8imum length of I90 - 0 )(0C:(C$9(;C:*
bytes.
2t"er Data Types
cursor
A reference to a cursor.
s4l6variant
A data type that stores values of various SQL Server-supported data types( e8cept
text( ntext( timestamp( and s3l%variant.
table
A special data type used to store a result set for later processing .
timestamp
A database-wide uni4ue number that gets updated every time a row gets updated.
uni4ueidentifier
A globally uni4ue identifier )AH3D*.
Data type precedences,
Bhen an operator combines two e8pressions of different data types( the rules for
data type precedence specify that the data type with the lower precedence is
converted to the data type with the higher precedence. 3f the conversion is not a
supported implicit conversion( an error is returned. Bhen both operand e8pressions
have the same data type( the result of the operation has that data type.
SQL Server uses the following precedence order for data types,
0. user-defined data types )highest*
. s3l%variant
9. xml
C. datetimeo##set
". datetime+
;. datetime
:. smalldatetime
$. date
J. time
0!. #loat
00.real
0. decimal
09. money
0C. smallmoney
0". bi$int
0;. int
0:. smallint
0$. tinyint
0J. bit
!. ntext
0. text
. ima$e
9. timestamp
C. uni3ueidenti#ier
". nvarc"ar )including nvarchar)ma8* *
;. nc"ar
:. varc"ar )including varchar)ma8* *
$. c"ar
J. varbinary )including varbinary)ma8* *
9!. binary )lowest*
&ype Storage in bytes
bigint $
3nt C
Smallint
&inyint 0
+it 0 bit
Decimal and numeric precision 0-J "
Decimal and numeric precision 0!-0J J
Decimal and numeric precision !-$ 09
Decimal and numeric precision J-9$ 0:
'oney $
Smallmoney C
/loat : digit precision C
/loat 0" digit precision $
2eal C
Datetime &wo C byte integers
Smalldatetime &wo byte integers
7har )AS733 coding system*(varchar 1ach char occupies 0 byte
Echar)HE37<D1 system*(nvarchar 1ach nchar occupies bytes
Create Table Command:
Syntax,
CR)T) TBL) table%name /col,4name data4type/*idt" i# any1
C2NSTR'NT constraint4name 5a constraint li6e &R'MR7
8)79.N'Q.)9 N2T N.LL9 C:)C8 etc;9 col+4name data4type/*idt" i# any1
C2NSTR'NT constraint4name <!!!!!!!!!!1

721A&1 &A+L1 7ustomer)
7ustomer3d int .23'A2D >1D(
/Eame nvarchar)9!*(
LEame nvarchar)9!*(
.hone char)09* HE3QH1(
Street nvarchar)9!*(
7ity nvarchar)!* E<& EHLL(
?ip7ode char)0!* E<& EHLL*
A<
'nsertin$ Records into a Table:
Synta8,
3ES12& 3E&< table-name )col0(col(col9(...*%ALH1S)val0(val(val9(......*
insert into 7ustomer values
)!!00(NMakeN(N>lineN(N)$0C*9:-;$:0N(N9" $th AvenueN(NLAN(N0;CCC-!";N*(
)!!99C(NAbigailN(N+rownN(N)$0C*9:-90!N(N0C Eorth LandN(NLAN(N0;CCC-!90N*(
)!!09(N2eginaldN(NSmythN(null(N..<.+o8 !!N(NEDN(N0"C9-!!0N*(
)0!(NSteveN(NHaagN(N)C0!*C0;-::JJN(N09: 3vanhoeN(N7hicagoN(N0!!-"""N*
go
7reate &able 2ental
)7ustomer3d int references 7ustomer(
%ideoEumber char);* references %ideo)%ideoEum*(
Date2ented datetime not null(
Date2eturned datetime*
go
3nsert into 2ental values)
!!99C(NC9:0-0N(N!JOO!;N(null*
go
7reate &able %ideo
)%ideoEum char);* primary key(
%&itle nvarchar)9!* not null(
%&ype nvarchar)!* not null(
DistEum int references Distributor)DistributorEum*(
.rice decimal)"(* not null check).rice between 0 and "*
*
go
insert into %ideo values
)N0000-0N(NAone with the bree=eN(NDramaN(J$;(9*(
)N0000-N(NAone with the bree=eN(NDramaN(J$;(9*(
)N9"0-;N(NAttack of killer tomatoesN(NHorrorN(9$0(0."*(
)NC9:0-0N(NAlien SurferN(NSci-/iN(C":(*(
)NC:$!-0N(N&hree Stooges in Las %egasN(N7omedyN(9"(*(
)NC:::-0N(NAods 'ust be cra=yN(N7omedyN(9"("*
go
7reate &able Distributor
)DistributorEum int primary key(
DistributorEame nvarchar)9!* not null(
.hone char)09* not null*
go
insert into Distributor values
)9"(NDisney StudiosN(N)$!!*C9-!!!!N*(
)J$;(NHniversal StudiosN(N)$!!*";"-!!!!N*(
)C":(N.aramount .icturesN(N)$!!*9-""""N*(
)9$0(N&ri-Star .roductionsN(N)$!!*;;"-$JJ$N*
go
'NT)-R'T7 C2NSTR'NTS
Nullability Rules =it"in a Table De#inition
&he nullability of a column determines whether or not that column can allow a null value
)EHLL* as the data in that column. EHLL is not =ero or blank, it means no entry was made or an
e8plicit EHLL was supplied( and it usually implies that the value is either unknown or not
applicable.
&R'MR7 8)7 Constraints
A table can contain only one .23'A2D >1D constraint.
&he inde8 generated by a .23'A2D >1D constraint cannot cause the number of inde8es
on the table to e8ceed CJ nonclustered inde8es and 0 clustered inde8.
3f 7LHS&121D or E<E7LHS&121D is not specified for a .23'A2D >1D constraint(
7LHS&121D is used if there are no clustered inde8es specified for HE3QH1 constraints.
All columns defined within a .23'A2D >1D constraint must be defined as E<& EHLL.
3f nullability is not specified( all columns participating in a .23'A2D >1D constraint
have their nullability set to E<& EHLL.
.N'Q.) Constraints
3f 7LHS&121D or E<E7LHS&121D is not specified for a HE3QH1 constraint(
E<E7LHS&121D is used by default.
1ach HE3QH1 constraint generates an inde8. &he number of HE3QH1 constraints cannot
cause the number of inde8es on the table to e8ceed CJ nonclustered inde8es and 0
clustered inde8.
F2R)'-N 8)7 Constraints
Bhen a value other than EHLL is entered into the column of a /<213AE >1D
constraint( the value must e8ist in the referenced columnP otherwise( a foreign key
violation error message is returned.
/<213AE >1D constraints are applied to the preceding column unless source columns
are specified.
/<213AE >1D constraints can reference only tables within the same database on the
same server. 7ross-database referential integrity must be implemented through triggers.
/<213AE >1D constraints can reference another column in the same table )a self-
reference*.
&he 21/121E71S clause of a column-level /<213AE >1D constraint can list only one
reference column( which must have the same data type as the column on which the
constraint is defined.
&he 21/121E71S clause of a table-level /<213AE >1D constraint must have the
same number of reference columns as the number of columns in the constraint column
list. &he data type of each reference column must also be the same as the corresponding
column in the column list.

A table can contain a ma8imum of "9 /<213AE >1D constraints.


/<213AE >1D constraints are not enforced on temporary tables.
A table can reference a ma8imum of "9 different tables in its /<213AE >1D
constraints.
/<213AE >1D constraints can reference only columns in .23'A2D >1D or HE3QH1
constraints in the referenced table or in a HE3QH1 3ED1@ on the referenced table.
use videorentalsystem
go
721A&1 &A+L1 Dept)
deptno int primary key(
dname nvarchar)!* not null(
loc nvarchar)!* not null*
go
721A&1 &A+L1 1mp)
empid int primary key(
ename nvarchar)!* not null(
5ob nvarchar)!* not null(
salary int not null(
deptno int references Dept)deptno**
go
-------------------------------------Q
721A&1 &A+L1 1mp)
empid int primary key(
ename nvarchar)!* not null(
5ob nvarchar)!* not null(
salary int not null(
deptno int(
foreign key)deptno*references Dept)deptno**
go
-------------------------------------Q
7reate table &@
)col08 int(
col8 int(
col98 nvarchar)0!*(
primary key)col08(col8**
go
7reate table &D
)
col0y int(
coly int(
col9y int(
7onstraint &D6fk /oreign >ey )col0y(coly*
references &@)col08(col8**
go
-------------------------------------Q
7reate table AA)
col0 int primary key(
col nvarchar)0!*(
col9 int uni4ue*
go
7reate table ++)
col0 nvarchar)!*(
col int references AA*
go
----------------------------------------Q
7reate table 77)
col0 nvarchar)!*(
col int references AA)col9**
go
------------------Q
D)F.LT De#initions
A column can have only one D1/AHL& definition.
A D1/AHL& definition can contain constant values( functions( SQL-J niladic functions(
or EHLL. &he table shows the niladic functions and the values they return for the default
during an 3ES12& statement.
SQL4>+ niladic #unction ?alue returned
7H221E&6&3'1S&A'. 7urrent date and time.
7H221E&6HS12 Eame of user performing insert.
S1SS3<E6HS12 Eame of user performing insert.
SDS&1'6HS12 Eame of user performing insert.
HS12 Eame of user performing insert.

constant_expression in a D1/AHL& definition cannot refer to another column in the


table( or to other tables( views( or stored procedures.
D1/AHL& definitions cannot be created on columns with a timestamp data type or
columns with an 3D1E&3&D property.
D1/AHL& definitions cannot be created for columns with user-defined data types if the
user-defined data type is bound to a default ob5ect.
Defaults supply a value )with the 3ES12& and H.DA&1 statements* when no
value is supplied. /or e8ample( the AdventureBorks!!$2 database could
include a lookup table listing the different 5obs employees can fill in the company.
Hnder a column that describes each 5ob( a character string default could supply a
description when an actual description is not entered e8plicitly.

4EFA5L) 'Ne6 2ositio/ 7 title /ot formali8ed 9et'
3n addition to constants( D1/AHL& definitions can include functions. Hse the following e8ample
to get the current date for an entry.
4EFA5L) :getdate:++
A niladic-function scan can also improve data integrity. &o keep track of the user that inserted a
row( use the niladic-function for HS12. Do not enclose the niladic-functions with parentheses.
4EFA5L) 5SE&
C:)C8 Constraints
A column can have any number of 7H17> constraints( and the condition can include
multiple logical e8pressions combined with AED and <2. 'ultiple 7H17> constraints
for a column are validated in the order created.
&he search condition must evaluate to a +oolean e8pression and cannot reference another
table.
A column-level 7H17> constraint can reference only the constrained column( and a
table-level 7H17> constraint can reference only columns in the same table.
7H17> 7<ES&2A3E&S and rules serve the same function of validating the data during
3ES12& and D1L1&1 statements.
Bhen a rule and one or more 7H17> constraints e8ist for a column or columns( all
restrictions are evaluated.
use videorentalsystem
go
create table &:)
col0 int primary key (
col nvarchar)0!*(
col9 int check)col9 GR 0! And col9 FR 0!!*
*
go
use videorentalsystem
go
create table &$)
col0 int primary key (
col nvarchar)0!*(
col9 int constraint t:6col96chk check)col9 GR 0! And col9 FR 0!!*
*
go
----------------------------Q
&his e8ample shows a named constraint with a pattern restriction on the character
data entered into a column of a table.
;'NS)&AIN) ;<=emp=id ;*E;< :emp=id LI<E
'>A7?>A7?>A7?>!7@?>"7@?>"7@?>"7@?>"7@?>FM?'
'& emp=id LI<E '>A7?7>A7?>!7@?>"7@?>"7@?>"7@?>"7@?>FM?'+
&his e8ample specifies that the values must be within a specific list or follow a specified pattern.
;*E;< :emp=id IN :'!0A@', '"B0C', '"ABB', '!C--', '!B$C'+
'& emp=id LI<E '@@>"7@?>"7@?'+
dditional Constraint 'n#ormation
7onstraint names must follow the rules for identifiers( e8cept that the name cannot begin
with a number sign )S*. 3f constraint_name is not supplied( a system-generated name is
assigned to the constraint. &he constraint name appears in any error message about
constraint violations.
Bhen a constraint is violated in an 3ES12&( H.DA&1( or D1L1&1 statement( the
statement is terminated. However( the transaction )if the statement is part of an e8plicit
transaction* continues to be processed. Dou can use the 2<LL+A7> &2AESA7&3<E
statement with the transaction definition by checking the @@122<2 system function.
7omposite .rimary >ey,
721A&1 &A+L1 1mp6Hrs)
1mp3d int(
DeptEo int(
HrsBkd int(
.23'A2D >1D)1mp3d(DeptEo**
A<
D2<. &A+L1 1mp6Hrs
A<
Difference between 7lustered and Eon-7lustered 3nde8es,
I am eDplai/i/g 9oE 6it. a/ eDample, ).e )elep.o/e
4irector9 is a fi/e eDample of ;lEstered I/deD as data
a/d
i/deD are at t.e same page, 6.ereas i/deD i/ t.e FacG
side
of t.e FooG is a fi/e eDample of /o/7clEstered i/deD
a/d
/o/7clEstered i/deD is a fast ,7tree strEctEre as i/deD
HEst poi/ts to t.e data page. Also o/l9 o/e clEstered
i/deD
is possiFle per taFle a/d -1@ /o/7clEstered i/deD per
taFle.
;lEstered i/deD is E/iqEe for a/9
give/ taFle a/d 6e ca/ .ave o/l9 o/e clEstered i/deD o/
a
taFle. ).e leaf level of a clEstered i/deD is t.e
actEal
data a/d t.e data is resorted i/ case of clEstered
i/deD.
(.ereas i/ case of /o/7clEstered i/deD t.e leaf level
is
actEall9 a poi/ter to t.e data i/ ro6s so 6e ca/ .ave
as
ma/9 /o/7clEstered i/deDes as 6e ca/ o/ t.e dF.
.sin$ Clustered 'ndexes
.23'A2D >1D constraint creates clustered inde8
automatically( if no clustered inde8 already e8ists on the
table and a nonclustered inde8 is not specified while
imposing the .23'A2D >1D constraint.
+efore creating clustered inde8es( understand how your data will be accessed.
7onsider using a clustered inde8 for,
7olumns that contain a large number of distinct values.
Queries that return a range of values using operators such as +1&B11E( G( GR( F( and
FR.
7olumns that are accessed se4uentially.
Queries that return large result sets.
7olumns that are fre4uently accessed by 4ueries involving 5oin or A2<H. +D clausesP
typically these are foreign key columns. An inde8 on the column)s* specified in the
<2D12 +D or A2<H. +D clause eliminates the need for SQL Server to sort the data
because the rows are already sorted. &his improves 4uery performance.

7lustered inde8es are not a good choice for,


7olumns that undergo fre4uent changes
&his results in the entire row moving )because SQL Server must keep the data values of a
row in physical order*. &his is an important consideration in high-volume transaction
processing systems where data tends to be volatile.
Bide keys
use videorentalsystem
go
create table &0)
col0 int primary key clustered(
col nvarchar)0!*(
col9 int uni4ue*
go
------------------------------------------Q
use videorentalsystem
go
create table &)
col0 int primary key clustered(
col nvarchar)0!*(
col9 int uni4ue clustered*
go
'sg $00( Level 0;( State !( Line
7annot add more than one clustered inde8 for constraints on table N&N.
------------------------------------------------Q
use videorentalsystem
go
create table &9)
col0 int primary key (
col nvarchar)0!*(
col9 int uni4ue clustered*
go
--------------------------------------------Q
use videorentalsystem
go
create table &C)
col0 int (
col nvarchar)0!*(
col9 int uni4ue (
primary key clustered)col0(col* *
go
-------------------------------------------Q
use videorentalsystem
go
create table &")
col0 int primary key(
col nvarchar)0!*(
col9 int (
uni4ue clustered)col(col9* *
go
--------------------------------------------Q
use videorentalsystem
go
create table &;)
col0 int primary key nonclustered(
col nvarchar)0!*(
col9 int (
*
go
---------------------------------------Q
721A&1 &A+L1 Stars
)Star3D int .23'A2D >1D E<E7LHS&121D(
StarEame varchar)"!* Hni4ue(
Solar'ass decimal)0!(* 7H17>)Solar'ass G !*(
Star&ype varchar)"!* D1/AHL& N<range AiantN*P
A<
721A&1 7LHS&121D 3ED1@ 386Star6Eame
<E Stars)StarEame*
A<
721A&1 E<E7LHS&121D 3ED1@ 386Star6&ype
<E Stars )Star&ype*
A<
-----------------------------------------------------------------Q
AL&12 &A+L1 7ommand,
! ddin$ a ne* column
&he following e8ample adds a column that allows null values and has no values provided
through a D1/AHL& definition. 3n the new column( each row will have EHLL.

use videorentalsystem
go
721A&1 &A+L1 doc6e8a )column6a 3E&* P
A<
AL&12 &A+L1 doc6e8a ADD column6b %A27HA2)!* EHLL P
A<
1@17 sp6help doc6e8a P
A<
D2<. &A+L1 doc6e8a P
A<
B! Droppin$ a column
&he following e8ample modifies a table to remove a column.
use videorentalsystem
go
721A&1 &A+L1 doc6e8b )column6a 3E&( column6b %A27HA2)!* EHLL* P
A<
AL&12 &A+L1 doc6e8b D2<. 7<LH'E column6b P
A<
1@17 sp6help doc6e8b P
A<
D2<. &A+L1 doc6e8b P
A<
C! C"an$in$ t"e data type o# a column
&he following e8ample changes a column of a table from 3E& to D173'AL.
use videorentalsystem
go
721A&1 &A+L1 doc6e8y )column6a 3E& * P
A<
3ES12& 3E&< doc6e8y )column6a* %ALH1S )0!* P
A<
Select Q from doc6e8y
go
e8ec sp6help doc6e8y
go
AL&12 &A+L1 doc6e8y AL&12 7<LH'E column6a D173'AL )"( * P
A<
D2<. &A+L1 doc6e8y P
A<
D! ddin$ a column *it" a constraint
&he following e8ample adds a new column with a HE3QH1 constraint.
Hse %ideo2entalSystem
go
721A&1 &A+L1 doc6e8c )column6a 3E&* P
A<
AL&12 &A+L1 doc6e8c ADD column6b %A27HA2)!* EHLL
7<ES&2A3E& e8b6uni4ue HE3QH1 P
A<
1@17 sp6help doc6e8c P
A<
D2<. &A+L1 doc6e8c P
A<
)! ddin$ an unveri#ied C:)C8 constraint to an existin$ column
&he following e8ample adds a constraint to an e8isting column in the table. &he column has a
value that violates the constraint. &herefore( B3&H E<7H17> is used to prevent the constraint
from being validated against e8isting rows( and to allow for the constraint to be added.
Hse %ideo2entalSystem
go
721A&1 &A+L1 doc6e8d ) column6a 3E&* P
A<
3ES12& 3E&< doc6e8d %ALH1S )-0* P
A<
AL&12 &A+L1 doc6e8d B3&H E<7H17>
ADD 7<ES&2A3E& e8d6check 7H17> )column6a G 0* P
A<
Select Q from doc6e8d
go
1@17 sp6help doc6e8d P
A<
D2<. &A+L1 doc6e8d P
A<
F! ddin$ a D)F.LT constraint to an existin$ column
&he following e8ample creates a table with two columns and inserts a value into the first column(
and the other column remains EHLL. A D1/AHL& constraint is then added to the second
column. &o verify that the default is applied( another value is inserted into the first column( and
the table is 4ueried.
721A&1 &A+L1 doc6e8= ) column6a 3E&( column6b 3E&* P
A<
3ES12& 3E&< doc6e8= )column6a*%ALH1S ) : * P
A<
AL&12 &A+L1 doc6e8=
ADD 7<ES&2A3E& col6b6def
D1/AHL& "! /<2 column6b P
A<
3ES12& 3E&< doc6e8= )column6a* %ALH1S ) 0! * P
A<
S1L17& Q /2<' doc6e8= P
A<
D2<. &A+L1 doc6e8= P
A<
-! ddin$ several columns *it" constraints
&he following e8ample adds several columns with constraints defined with the new column. &he
first new column has an 3D1E&3&D property. 1ach row in the table has new incremental values
in the identity column.
Hse %ideo2entalSystem
go
721A&1 &A+L1 doc6e8e ) column6a 3E& 7<ES&2A3E& column6a6un
HE3QH1* P
A<
AL&12 &A+L1 doc6e8e ADD
-- Add a .23'A2D >1D identity column.
column6b 3E& 3D1E&3&D
7<ES&2A3E& column6b6pk .23'A2D >1D(
-- Add a column that references another column in the same table.
column6c 3E& EHLL
7<ES&2A3E& column6c6fk
21/121E71S doc6e8e)column6a*(
-- Add a column with a constraint to enforce that
-- nonnull data is in a valid telephone number format.
column6d %A27HA2)0;* EHLL
7<ES&2A3E& column6d6chk
7H17>
)column6d L3>1 NT!-JUT!-JUT!-JU-T!-JUT!-JUT!-JUT!-JUN <2
column6d L3>1
N)T!-JUT!-JUT!-JU* T!-JUT!-JUT!-JU-T!-JUT!-JUT!-JUT!-JUN*(
-- Add a nonnull column with a default.
column6e D173'AL)9(9*
7<ES&2A3E& column6e6default
D1/AHL& .!$0 P
A<
1@17 sp6help doc6e8e P
A<
D2<. &A+L1 doc6e8e P
A<
:! ddin$ a nullable column *it" de#ault values
&he following e8ample adds a nullable column with a D1/AHL& definition( and uses B3&H
%ALH1S to provide values for each e8isting row in the table. 3f B3&H %ALH1S is not used(
each row has the value EHLL in the new column.
Hse %ideo2entalSystem
go
721A&1 &A+L1 doc6e8f ) column6a 3E&* P
A<
3ES12& 3E&< doc6e8f %ALH1S )0* P
A<
AL&12 &A+L1 doc6e8f
ADD AddDate smalldatetime EHLL
7<ES&2A3E& AddDateDflt
D1/AHL& A1&DA&1)* B3&H %ALH1S P
A<
S1L17& Q /2<' doc6e8f
go
D2<. &A+L1 doc6e8f P
A<
'! Disablin$ and re4enablin$ a constraint
&he following e8ample disables a constraint that limits the salaries accepted in the data.
E<7H17> 7<ES&2A3E& is used with AL&12 &A+L1 to disable the constraint and allow for
an insert that would typically violate the constraint. 7H17> 7<ES&2A3E& re-enables the
constraint.
use %ideo2entalSystem
go
721A&1 &A+L1 cnst6e8ample
)id 3E& E<& EHLL(
name %A27HA2)0!* E<& EHLL(
salary '<E1D E<& EHLL
7<ES&2A3E& salary6cap 7H17> )salary F 0!!!!!*
*P
-- %alid inserts
3ES12& 3E&< cnst6e8ample %ALH1S )0(NMoe +rownN(;"!!!*P
3ES12& 3E&< cnst6e8ample %ALH1S )(N'ary SmithN(:"!!!*P
-- &his insert violates the constraint.
3ES12& 3E&< cnst6e8ample %ALH1S )9(N.at MonesN(0!"!!!*P
-- Disable the constraint and try again.
AL&12 &A+L1 cnst6e8ample E<7H17> 7<ES&2A3E& salary6capP
3ES12& 3E&< cnst6e8ample %ALH1S )9(N.at MonesN(0!"!!!*P
-- 2e-enable the constraint and try another insertP this will fail.
AL&12 &A+L1 cnst6e8ample 7H17> 7<ES&2A3E& salary6capP
3ES12& 3E&< cnst6e8ample %ALH1S )C(N1ric MamesN(00!!!!* P
A! Droppin$ a constraint
&he following e8ample removes a HE3QH1 constraint from a table.
Hse %ideo2entalSystem
go
721A&1 &A+L1 doc6e8c ) column6a 3E&
7<ES&2A3E& my6constraint HE3QH1* P
A<
AL&12 &A+L1 doc6e8c D2<. 7<ES&2A3E& my6constraint P
A<
D2<. &A+L1 doc6e8c P
A<
M! Creatin$ a &R'MR7 8)7 constraint *it" index options
&he following e8ample creates the .23'A2D >1D constraint
.>6&ransactionHistoryArchive6&ransaction3D and sets the options /3LL/A7&<2( <EL3E1(
and .AD63ED1@. &he resulting clustered inde8 will have the same name as the constraint.
5SE Adve/tEre(orGs-""A&-I
%'
AL)E& )A,LE 2rodEctio/.)ra/sactio/*istor9Arc.ive (I)* N';*E;<
A44 ;'NS)&AIN) 2<=)ra/sactio/*istor9Arc.ive=)ra/sactio/I4 2&IMA&J <EJ
;L5S)E&E4 :)ra/sactio/I4+
(I)* :FILLFA;)'& = B$, 'NLINE = 'N, 2A4=IN4E# = 'N+I
%'
N! Droppin$ a &R'MR7 8)7 constraint in t"e 2NL'N) mode
&he following e8ample deletes a .23'A2D >1D constraint with the <EL3E1 option set to <E.
5SE Adve/tEre(orGs-""A&-I
%'
AL)E& )A,LE )ra/sactio/*istor9Arc.ive
4&'2 ;'NS)&AIN) 2<=)ra/sactio/*istor9Arc.ive=)ra/sactio/I4
(I)* :'NLINE = 'N+I
%'
2! ddin$ and droppin$ a F2R)'-N 8)7 constraint
&he following e8ample creates the table 7ontact+ackup( and then alters the table( first by adding
a /<213AE >1D constraint that references the table .erson( then by dropping the /<213AE
>1D constraint.
5SE Adve/tEre(orGs-""A&- I
%'
;&EA)E )A,LE ;o/tact,acGEp
:;o/tactI4 i/t+ I
%'
AL)E& )A,LE ;o/tact,acGEp
A44 ;'NS)&AIN) F<=;o/tact,acEp=;o/tact F'&EI%N <EJ :;o/tactI4+
&EFE&EN;ES 2erso/ :,Esi/essE/tit9I4+ I
AL)E& )A,LE ;o/tact,acGEp
4&'2 ;'NS)&AIN) F<=;o/tact,acEp=;o/tact I
%'
4&'2 )A,LE ;o/tact,acGEp I
&! C"an$in$ t"e siBe o# a column
&he following e8ample increases the si=e of a varchar column and the precision and scale of a
decimal column. +ecause the columns contain data( the column si=e can only be increased. Also
notice that col6a is defined in a uni4ue inde8. &he si=e of col6a can still be increased because the
data type is a varchar and the inde8 is not the result of a .23'A2D >1D constraint.
5avascript,7odeSnippet67opy7ode)N7odeSnippet7ontainer7ode0$N*P
IF ',KE;)=I4 : 'dFo.doc=eD9', '5' + IS N') N5LL
4&'2 )A,LE dFo.doc=eD9I
%'
77 ;reate a t6o7colEm/ taFle 6it. a E/iqEe i/deD o/ t.e varc.ar colEm/.
;&EA)E )A,LE doc=eD9 : col=a varc.ar:$+ 5NIL5E N') N5LL, col=F decimal :1,-++I
%'
INSE&) IN)' doc=eD9 MAL5ES :')est', @@.@@+I
%'
77 Merif9 t.e cErre/t colEm/ si8e.
SELE;) /ame, )J2E=NAME:s9stem=t9pe=id+, maD=le/gt., precisio/, scale
F&'M s9s.colEm/s (*E&E oFHect=id = ',KE;)=I4:N'dFo.doc=eD9'+I
%'
77 I/crease t.e si8e of t.e varc.ar colEm/.
AL)E& )A,LE doc=eD9 AL)E& ;'L5MN col=a varc.ar:-$+I
%'
77 I/crease t.e scale a/d precisio/ of t.e decimal colEm/.
AL)E& )A,LE doc=eD9 AL)E& ;'L5MN col=F decimal :!",1+I
%'
77 I/sert a /e6 ro6.
INSE&) IN)' doc=eD9 MAL5ES :'M9Ne6;olEm/Si8e', @@@@@.@@@@+ I
%'
77 Merif9 t.e cErre/t colEm/ si8e.
SELE;) /ame, )J2E=NAME:s9stem=t9pe=id+, maD=le/gt., precisio/, scale
F&'M s9s.colEm/s (*E&E oFHect=id = ',KE;)=I4:N'dFo.doc=eD9'+I
3nsert 7ommand
Hse %ideo2entalSystem
go
e8ec sp6help t0
go
3ES12& 3E&< &0)col0( col(col9*
S1L17& 0(N/irstN (0
HE3<E ALL
S1L17& (NSecondN (
HE3<E ALL
S1L17& 9(N&hirdN (9
HE3<E ALL
S1L17& C( N/ourthN (C
HE3<E ALL
S1L17& "(N/ifthN ("
A<
Select Q from &0
go
------------------------------------Q
3ES12& 3E&< &0)col0( col(col9*
%ALH1S) 0(N/irstN (0*(
)(NSecondN (*(
) 9(N&hirdN (9*(
) C( N/ourthN (C*(
)"(N/ifthN ("*
A<
2enaming column and table,
&he script for renaming any column ,
18ec sp=&ENAME ')aFleName.>'ld;olEm/Name?' ,
'>Ne6;olEm/Name?', ';'L5MN'
&he script for renaming any ob5ect )table( sp etc* ,
18ec sp=&ENAME '>'ld)aFleName?' , '>Ne6)aFleName?'
2enaming a database,
1@17 sp6renamedb NoldEameN( NnewEameN
7<''3&,
'arks the end of a successful implicit or e8plicit transaction. 3f
VV&2AE7<HE& is 0( 7<''3& &2AESA7&3<E makes all data modifications
performed since the start of the transaction a permanent part of the database( frees
the resources held by the transaction( and decrements VV&2AE7<HE& to !. 3f
VV&2AE7<HE& is greater than 0( 7<''3& &2AESA7&3<E decrements
VV&2AE7<HE& only by 0 and the transaction stays active.
! Committin$ a transaction
&he following e8ample deletes a 5ob candidate.
7opy
5SE Adve/tEre(orGs-""A&-I
%'
,E%IN )&ANSA;)I'NI
%'
4ELE)E F&'M *Ema/&esoErces.KoF;a/didate
(*E&E KoF;a/didateI4 = !0I
%'
;'MMI) )&ANSA;)I'NI
%'
B! Committin$ a nested transaction
&he following e8ample creates a table( generates three levels of nested transactions( and then
commits the nested transaction. Although each 7<''3& &2AESA7&3<E statement has a
transaction6name parameter( there is no relationship between the 7<''3& &2AESA7&3<E
and +1A3E &2AESA7&3<E statements. &he transaction6name parameters are simply
readability aids to help the programmer ensure that the proper number of commits are coded to
decrement VV&2AE7<HE& to ! and thereby commit the outer transaction.
5SE Adve/tEre(orGs-""A&-I
%'
IF ',KE;)=I4:N')est)ra/',N'5'+ IS N') N5LL
4&'2 )A,LE )est)ra/I
%'
;&EA)E )A,LE )est)ra/ :;ola i/t 2&IMA&J <EJ, ;olF c.ar:0++I
%'
77 ).is stateme/t sets NN)&AN;'5N) to !.
,E%IN )&ANSA;)I'N 'Eter)ra/I
%'
2&IN) N')ra/sactio/ coE/t after ,E%IN 'Eter)ra/ = '
O ;AS):NN)&AN;'5N) AS /varc.ar:!"++I
%'
INSE&) IN)' )est)ra/ MAL5ES :!, 'aaa'+I
%'
77 ).is stateme/t sets NN)&AN;'5N) to -.
,E%IN )&ANSA;)I'N I//er!I
%'
2&IN) N')ra/sactio/ coE/t after ,E%IN I//er! = '
O ;AS):NN)&AN;'5N) AS /varc.ar:!"++I
%'
INSE&) IN)' )est)ra/ MAL5ES :-, 'FFF'+I
%'
77 ).is stateme/t sets NN)&AN;'5N) to 0.
,E%IN )&ANSA;)I'N I//er-I
%'
2&IN) N')ra/sactio/ coE/t after ,E%IN I//er- = '
O ;AS):NN)&AN;'5N) AS /varc.ar:!"++I
%'
INSE&) IN)' )est)ra/ MAL5ES :0, 'ccc'+I
%'
77 ).is stateme/t decreme/ts NN)&AN;'5N) to -.
77 Not.i/g is committed.
;'MMI) )&ANSA;)I'N I//er-I
%'
2&IN) N')ra/sactio/ coE/t after ;'MMI) I//er- = '
O ;AS):NN)&AN;'5N) AS /varc.ar:!"++I
%'
77 ).is stateme/t decreme/ts NN)&AN;'5N) to !.
77 Not.i/g is committed.
;'MMI) )&ANSA;)I'N I//er!I
%'
2&IN) N')ra/sactio/ coE/t after ;'MMI) I//er! = '
O ;AS):NN)&AN;'5N) AS /varc.ar:!"++I
%'
77 ).is stateme/t decreme/ts NN)&AN;'5N) to " a/d
77 commits oEter tra/sactio/ 'Eter)ra/.
;'MMI) )&ANSA;)I'N 'Eter)ra/I
%'
2&IN) N')ra/sactio/ coE/t after ;'MMI) 'Eter)ra/ = '
O ;AS):NN)&AN;'5N) AS /varc.ar:!"++I
%'
2<LL+A7>,
2<LL+A7> &2AESA7&3<E erases all data modifications made from the start of
the transaction or to a savepoint. 3t also frees resources held by the transaction.
2<LL+A7> &2AESA7&3<E without a savepoint6name or transaction6name rolls back to the
beginning of the transaction. Bhen nesting transactions( this same statement rolls back all inner
transactions to the outermost +1A3E &2AESA7&3<E statement. 3n both cases( 2<LL+A7>
&2AESA7&3<E decrements the VV&2AE7<HE& system function to !. 2<LL+A7>
&2AESA7&3<E savepoint6name does not decrement VV&2AE7<HE&.
HS1 &empD+P
A<
721A&1 &A+L1 %alue&able )TvalueU int*
A<
D17LA21 V&ransactionEame varchar)!* R N&ransaction0NP
--&hese statements start a named transaction(
--insert a two records( and then roll back
--the transaction named in the variable
--V&ransactionEame.
+1A3E &2AE V&ransactionEame
3ES12& 3E&< %alue&able %ALH1S)0*
3ES12& 3E&< %alue&able %ALH1S)*
2<LL+A7> &2AE V&ransactionEame
3ES12& 3E&< %alue&able %ALH1S)9*
3ES12& 3E&< %alue&able %ALH1S)C*
S1L17& Q /2<' %alue&able
4&'2 )A,LE MalEe)aFle
77&esElts
77valEe
7777777777777
770
771
Bhenever you e8ecute a 7<''3& &2AESA7&3<E statement( any transaction
name after the statement is ignored. &he only thing a 7<''3& &2AESA7&3<E
statement does is reduce the VVtrancount variable by 0. 3f this makes
VVtrancount R !( then all database modifications are committed.
721A&1 &A+L1 &est&ran )7ola 3E& .23'A2D >1D( 7olb 7HA2)9**
A<
+1A3E &2AESA7&3<E <uter&ran L VV&2AE7<HE& set to 0.
A<
3ES12& 3E&< &est&ran %ALH1S )0( WaaaX*
A<
+1A3E &2AESA7&3<E 3nner0 L VV&2AE7<HE& set to .
A<
3ES12& 3E&< &est&ran %ALH1S )( WbbbX*
A<
+1A3E &2AESA7&3<E 3nner L VV&2AE7<HE& set to 9.
A<
3ES12& 3E&< &est&ran %ALH1S )9( WcccX*
A<
7<''3& &2AESA7&3<E 3nner L Decrements VV&2AE7<HE& to .
L Eothing committed.
L 2<LL+A7> &2AESA7&3<E 3nner0
A<
7<''3& &2AESA7&3<E 3nner0 L Decrements VV&2AE7<HE& to 0.
L Eothing committed.
A<
7<''3& &2AESA7&3<E <uter&ran L Decrements VV&2AE7<HE& to !.
L 7ommits outer transaction <uter&ran.
A<
D2<. &A+L1 &est&ran
&he only transaction name that SQL Server cares about is 2uterTran. 3tXs fine to label 3nner0
and 3nner transactions for other developers( but SQL Server does not use them.
Also( the 7<''3& &2AESA7&3<E statement does not use the transaction name.
<nly a 2<LL+A7> uses the transaction name( and only the outermost transaction
name. /or e8ample( trying to do 2<LL+A7> &2AESA7&3<E 3nner0 where it is
commented out in the code snippet above would not work.
7ommitting inner transactions is ignored by 'icrosoftY SQL ServerZ. &he
transaction is either committed or rolled back based on the action taken at the end
of the outermost transaction. 3f the outer transaction is committed( the inner nested
transactions are also committed. 3f the outer transaction is rolled back( then all
inner transactions are also rolled back( regardless of whether or not the inner
transactions were individually committed.
&o List all the databases on the server,
1@17 sp=dataFases
&o list fields in a table ,
sp=.elp taFle/ame
Eg:
sp=.elp stEde/t)aFle
<r
SELE;) taFle/ame
F&'M 4,Name.s9s.taFlesI
&o the get the &ables count in the D+
SELE;) ;oE/t:P+
F&'M 4,Name.s9s.taFlesI
+y default we can find the created date of all tables also
SELE;) /ame,;reate=4ate
F&'M 4,Name.s9s.taFlesI
3nserting 2ecords 3nto &able containing Self-reference
HS1 %ideo2entalSystem
go
721A&1 &A+L1 1mp
)
1mp3D int .23'A2D >1D(
1mpEame varchar)9!*(
'gr3D int /<213AE >1D 21/121E71S 1mp)1mp3D*
*
A<
3ES12& dbo.1mp %ALH1S) 0( N.residentN( EHLL*
go
3ES12& dbo.1mp %alues)( N%ice .residentN( 0*
go
3ES12& dbo.1mp values) 9( N71<N( *
go
3ES12& dbo.1mp values) C( N7&<N( *
go
3ES12& dbo.1mp values) "( NAroup .ro5ect 'anagerN( C*
go
T"e .&DT) command
H.DA&1 tableEame S1& /ield0R Nval0N( /ield R val( /ield9 R val9
BH121 /ieldC R valC
T"e D)L)T) command
Delete /rom &able-name --G Deletes all the records
Delete /rom &able-name where condition --G Deletes only those records that
meet the criteria
.sin$ 2.T&.T clause *it" insert9update
and delete commands:
Hse 'ycompany
go
--Select Q from customer
--go
insert into 'y7ompany.dbo.customer
output inserted.7ust3d(inserted.7ustEame(inserted.7ust7ity
values
)C!!(NMohnN(N7hennaiN*
go
update customer set 7ustEameRN88888N(7ust7ityRNyyyyN
output inserted.7ustEame(inserted.7ust7ity where 7ust3dR9!!
go
update customer set 7ustEameRN88888N(7ust7ityRNyyyyN
output inserted.Q where 7ust3dR9!!
go
delete from customer output deleted.Q where 7ust3d GR 9!!
go
Queries:
List All the distributors
Select Q from Distributor
go
Show number and phone belonging to all distributors
Select DistributorEum(.hone from Distributor
go
Show 3d(/irst name and Last name of all customers
Select 7ustomer3d(/name(Lname from 7ustomer
Ao
Show /irst Eame( 3d and Last Eame of all customers
Select /Eame(7ustomer3d(LEame from 7ustomer
Ao
Display 3d and 7ity of all customers
Select 7ustomer3d(7ity from 7ustomer
go
Show all the details of all the customers,
Select 7ustomer3d(/Eame(LEame(.hone(Street(7ity(?ip7ode from customer
go
--Select Q from 7ustomer
--go
7oulmn-aliasing,
Show all the details of all the distributors. 3n the report( change first and second
filed names as Distributor Eumber and &itle respecitvely
Select DistributorEum as TDistributor EumberU(DistributorEame as T&itleU(.hone
from Distributor
go
.refi8ing 7olumn name with &able name
Select Distributor.DistributorEum(Distributor.DistributorEame(Distributor..hone
from Distributor
&able aliasing,
Select Dist.DistributorEum(Dist.DistributorEame(Dist..hone
from Distributor Dist
7onditional 2etrieval,
List the details of all those customers who live in LA
Select Q from 7ustomer where 7ityRNLAN
go
Show /irst name and Last name of that customer whose id is !!99C
Select /Eame(LEame from 7ustomer where 7ustomer3dR!!99C
go
Show number(title(distributor number and price of all those videos whose prices
are greater than or e4ual to 9.!
Select %ideoEum(%title( DistEum( .rice from %ideo where .rice GR 9.!
go
Select %ideoEum(%title( DistEum( .rice from %ideo where .rice GR 0.! and .rice
FR 9.!
go
Some 'ore Sample &ables and Queries,
721A&1 &A+L1 D1.A2&'1E&S
)D1.&E< EH'1237)* .23'A2D >1D(
DEA'1 %A27HA2)0C*(
L<7 %A27HA2)09* *
3ES12& 3E&< D1.A2&'1E&S %ALH1S )0!( NA77<HE&3EAN( NE1B D<2>N*(
)!( N21S1A27HN( NDALLASN*(
)9!( NSAL1SN( N7H37AA<N*(
)C!( N<.12A&3<ESN( N+<S&<EN*P
A<
721A&1 &A+L1 1'.L<D11
)1'.E< EH'1237)C* .23'A2D >1D(
1EA'1 %A27HA2)0!* E<& EHLL(
M<+ %A27HA2)J* E<& EHLL(
'A2 EH'1237)C* EHLL(
H321DA&1 DA&1&3'1 E<& EHLL(
SAL EH'1237):( * E<& EHLL 7H17>)SAL FR 0!!!!*(
7<'' EH'1237):( * EHLL(
D1.&E< EH'1237)* 21/121E71S Departments)D1.&E<**
3ES12& 3E&< 1'.L<D11 %ALH1S
):9;J( NS'3&HN( N7L12>N( :J!( N0:-D17-0J$!N( $!!( EHLL( !*(
):CJJ( NALL1EN( NSAL1S'AEN( :;J$( N!-/1+-0J$0N( 0;!!( 9!!( 9!*(
):"0( NBA2DN( NSAL1S'AEN( :;J$( N-/1+-0J$0N( 0"!( "!!( 9!*(
):";;( NM<E1SN( N'AEAA12N( :$9J( N-A.2-0J$0N( J:"( EHLL( !*(
):;"C( N'A2&3EN( NSAL1S'AEN( :;J$( N$-S1.-0J$0N( 0"!( 0C!!( 9!*(
):;J$( N+LA>1N( N'AEAA12N( :$9J( N0-'AD-0J$0N( $"!( EHLL( 9!*(
)::$( N7LA2>N( N'AEAA12N( :$9J( NJ-MHE-0J$0N( C"!( EHLL( 0!*(
)::$$( NS7<&&N( NAEALDS&N( :";;( N!J-D17-0J$N( 9!!!( EHLL( !*(
):$9J( N>3EAN( N.21S3D1E&N( EHLL( N0:-E<%-0J$0N( "!!!( EHLL( 0!*(
):$CC( N&H2E12N( NSAL1S'AEN( :;J$( N$-S1.-0J$0N( 0"!!( !( 9!*(
):$:;( NADA'SN( N7L12>N( ::$$( N0-MAE-0J$9N( 00!!( EHLL( !*(
):J!!( NMA'1SN( N7L12>N( :;J$( N9-D17-0J$0N( J"!( EHLL( 9!*(
):J!( N/<2DN( NAEALDS&N( :";;( N9-D17-0J$0N( 9!!!( EHLL( !*(
):J9C( N'3LL12N( N7L12>N( ::$( N9-MAE-0J$N( 09!!( EHLL( 0!*P
A<
721A&1 &A+L1 SALA2AD1
)A2AD1 EH'1237(
L<SAL EH'1237(
H3SAL EH'1237*
3ES12& 3E&< SALA2AD1 %ALH1S )0( :!!( 0!!*(
)( 0!0( 0C!!*(
)9( 0C!0( !!!*(
)C( !!0( 9!!!*(
)"( 9!!0( JJJJ*P
<perators in SQLServer,
An operator is a symbol specifying an action that is performed on one or more
e8pressions. &he following tables lists the operator categories that SQL Server
uses.
Arithmetic <perators Logical <perators
Assignment <perator Scope 2esolution <perator
+itwise <perators Set <perators
7omparison <perators String 7oncatenation <perator
7ompound <perators Hnary <perators
<perators have the precedence levels shown in the following table. An operator on
higher levels is evaluated before an operator on a lower level.
Lev
el
2perators
0 [ )+itwise E<&*
Q )'ultiply*( O )Division*( \ )'odulo*
9
K ).ositive*( - )Eegative*( K )Add*(
)K 7oncatenate*( - )Subtract*( # )+itwise AED*(
I )+itwise 18clusive <2*( ] )+itwise <2*
C R( G( F( GR( FR( FG( ^R( ^G( ^F )7omparison operators*
" E<& )Logical*
; AED )Logical*
: ALL( AED( +1&B11E( 3E( L3>1( <2( 1@3S&S( S<'1 )Logical*
$ R )Assignment*
Eote,
&he plus )K* and minus )-* operators can also be used to perform arithmetic
operations on datetime and smalldatetime values.
SQL Server provides the following set operators also. Set operators combine
results from two or more 4ueries into a single result set.
E#;E2)
IN)E&SE;)
5NI'N
&he scope resolution operator ,, provides access to static members of a compound
data type. A compound data type is one that contains multiple simple data types
and methods.
7ompound operators e8ecute some operation and set an original value to the result
of the operation. /or e8ample( if a variable V8 e4uals 9"( then V8 KR takes the
original value of V8( add and sets V8 to that new value )9:*.
select Q from employee where Sal GR !!! AED Sal FR C"!!
select Q from employee where Sal +1&B11E !!! AED C"!!
select Q from employee where Sal not between !!! and C"!!
select Q from employee where hiredate between N0J$!-0-0:N and N0J$0-0-!9N
select Q from employee where hiredate between N0:-D17-0J$!N and N9-D17-0J$0N
select Q from employee where deptno R 0! or deptno R !P
select Q from employee where deptno in)0!(!*P
select Q from employee where deptno E<& in)0!(!*P
select Q from employee where comm is null
select empno(ename from employee order by empno
select ename(Sal from employee order by sal
select ename(Sal from employee order by sal(ename
select Q from employee order by deptno(5ob
wrong, for displaying records of those employees who are managers and working
in 0! or !
select Q from employee where 5obRN'AEAA12N and deptnoR0! or deptnoR!
order by deptno
select Q from employee where deptnoR0! or deptnoR! AED 5obRN'AEAA12N
order by deptno
7orrect,
select Q from employee where 5obRN'AEAA12N and )deptnoR0! or deptnoR!*
order by deptno
select Q from employee where enameRN7LA2>N
select ename from 1'.L<D11 where 1EA'1RNmartinN
S1L17& ename /2<' employee
BH121 ename 7<LLA&1 Latin06Aeneral67S6AS R NmartinN
="at is collationC
7ollation refers to a set of rules that determine how
data is sorted and compared. 7haracter data is sorted
according to rules that define the correct character se4uence.
721A&1 &A+L1 mytable
)
mycolumn %A27HA2)0!*
*
A<
3ES12& mytable %ALH1S)N7aseN*
A<

S1L17& mycolumn /2<' mytable BH121 mycolumnRN7aseN
S1L17& mycolumn /2<' mytable BH121 mycolumnRNcaS1N
S1L17& mycolumn /2<' mytable BH121 mycolumnRNcaseN
Dou can alter your 4uery by forcing collation at the column level,
S1L17& my7olumn /2<' my&able
BH121 my7olumn 7<LLA&1 Latin06Aeneral67S6AS R NcaS1N

S1L17& my7olumn /2<' my&able
BH121 my7olumn 7<LLA&1 Latin06Aeneral67S6AS R NcaseN

S1L17& my7olumn /2<' my&able
BH121 my7olumn 7<LLA&1 Latin06Aeneral67S6AS R N7aseN

-- if my7olumn has an inde8( you will likely benefit by adding
-- AED my7olumn R NcaseN
AL&12 &A+L1 mytable
AL&12 7<LH'E mycolumn %A27HA2)0!*
7<LLA&1 Latin06Aeneral67S6AS
A<
3ES12& mytable %ALH1S)N7aseN*
S1L17& mycolumn /2<' mytable BH121 mycolumnRN7aseN
S1L17& mycolumn /2<' mytable BH121 mycolumnRNcaS1N
S1L17& mycolumn /2<' mytable BH121 mycolumnRNcaseN
721A&1 &A+L1 mytable
)
mycolumn %A27HA2)0!*7<LLA&1 Latin06Aeneral67S6AS
*
A<
Ese master
go
create dataFase ,IN collate Lati/!=%e/eral=,IN
go
create dataFase ;I=AI=<S collate Lati/!=%e/eral=;I=AI=<S
go
create dataFase ;S=AS=<S=(S collate Lati/!=%e/eral=;S=AS=<S=(S
go
4ELE)E F&'M TableName
'5)25) 4ELE)E4.Columns
(*E&E Condition(s)
ppendix : Collation Su##ixes
Su##ix Meanin$
6+3E binary sort
6736A3 case-insensitive( accent-insensitive( 6anatype4insensitive( *idt"4insensitive
6736A36BS case-insensitive( accent-insensitive( 6anatype4insensitive( width-sensitive
6736A36>S case-insensitive( accent-insensitive( kanatype-sensitive( *idt"4insensitive
6736A36>S6BS case-insensitive( accent-insensitive( kanatype-sensitive( width-sensitive
6736AS case-insensitive( accent-sensitive( 6anatype4insensitive( *idt"4insensitive
6736AS6BS case-insensitive( accent-sensitive( 6anatype4insensitive( width-sensitive
6736AS6>S case-insensitive( accent-sensitive( kanatype-sensitive( *idt"4insensitive
6736AS6>S6BS case-insensitive( accent-sensitive( kanatype-sensitive( width-sensitive
67S6A3 case-sensitive( accent-insensitive( 6anatype4insensitive( *idt"4insensitive
67S6A36BS case-sensitive( accent-insensitive( 6anatype4insensitive( width-sensitive
67S6A36>S case-sensitive( accent-insensitive( kanatype-sensitive( *idt"4insensitive
67S6A36>S6BS case-sensitive( accent-insensitive( kanatype-sensitive( width-sensitive
67S6AS case-sensitive( accent-sensitive( 6anatype4insensitive( *idt"4insensitive
67S6AS6BS case-sensitive( accent-sensitive( 6anatype4insensitive( width-sensitive
67S6AS6>S case-sensitive( accent-sensitive( kanatype-sensitive( *idt"4insensitive
67S6AS6>S6BS case-sensitive( accent-sensitive( kanatype-sensitive( width-sensitive
Note >ana sensitivity is set by default to insensitive. 3n other words( by default(
katakana and hiragana are treated as the same. Bidth sensitivity is also insensitive by
default. 3n other words( by default( full-width and half-width characters are treated as
the same.
select langid( alias( lcid( msglangid from sys.syslanguages
A collation is a set of rules defining a character set and its sorting rules. SQL
Server support a large number of built-in collations. /or e8ample,
Albanian6736A36>S6BS - Albanian( case-insensitive )73*( accent-insensitive )A3*(
kanatype-sensitive )>S*( width-sensitive )BS*.
Arabic6736AS6>S6BS - Arabic( case-insensitive( accent-sensitive( kanatype-sensitive(
width-sensitive.
/rench6736A3 - /rench( case-insensitive( accent-insensitive( kanatype-insensitive( width-
insensitive.
>orean6Bansung6+3E - >orean-Bansung( binary sort.
SQL6Latin06Aeneral67.0"!6736AS - Latin0-Aeneral( case-insensitive( accent-
sensitive( kanatype-insensitive( width-insensitive.
S1L17& Q /2<' fn6helpcollations)*
A<
SQL Server /unctions L Arouping 2ecords L
<rdering 2ecords - .artitioning 2ecords
&o support determinism and non-determinism( &ransact-SQL provides two broad categories of
functions. A function that always returns the same or known value is referred to as deterministic.
A function whose returned value may depend on a condition is referred to as non-deterministic.
7ast /unction,
3n most cases( a value the user submits to your database is primarily considered a string. &his is
convenient if thatNs what you are e8pecting. 3f the value the user provides must be treated as
something other than a string( for e8ample( if the user provides a number( before using such a
value( you should first convert it to the appropriate type( that is( from a string to the e8pected
type.
;AS):Expression AS DataType+
&he Expression is the value that needs to be cast.
&he DataType factor is the type of value we want to convert the Expression to.
.rint 7ast)N00N As int*
.rint 7ast)N09CN As Decimal);(**
7onvert /unction,
Like CST/1( the C2N?)RT/1 function is used to convert a value.
Hnlike CST/1( C2N?)RT/1 can be used to convert a value from its original
type into a non-similar type.
/or e8ample( you can use C2N?)RT to cast a number into a string
and vice-versa.
&he synta8 of the C2N?)RT/1 function is,
;'NME&):DataType > : le/gt. + ? , Expression+
.rint 7onvert)int(0".;;*P
String based functions,
&o get the length of a string( you can use the L)N/1 function.
3ts synta8 is,
i/t LEN:String+
select L1E)Nhello worldN*
print len)Nhello worldN*
3f you have a string( to get the AS733 code of its leftmost character(
you can use the SC''/1 function. 3ts synta8 is,
i/t AS;II:String+
&his function takes a string as argument and returns the
AS733 code of the first )the left* character of the string.
print Ascii)NallenN*
3f you have the AS733 code of a character and want to find its actual character( you
can use the C:R/1 function. 3ts synta8 is,
c.ar ;*A&:i/t value+
&his function takes an integer value as argument
and returns the AS733 e4uivalent of that number.
print 7har);"*
Bhen you receive a string( if you want to convert all of its characters to lowercase(
you can use the L2=)R/1 function. 3ts synta8 is,
varc.ar L'(E&:Stri/g+
&his function takes as argument a string. Any lowercase letter that is part of the string would not
change. Any letter that is part of the string would be converted to lowercase. Any other character
or symbol would be kept _as is_. After conversion( the L2=)R/1 function returns a new string.
print lower)NH1LL< worldJ\N*
A sub-string is a section gotten from a string. &he idea is to isolate one or a group
of characters for any necessary reason.
A left sub-string is one or a group of characters retrieved from the left side of a known string. &o
get the left sub-string of a string( you can use the L)FT/1 function. 3ts synta8 is,
varc.ar LEF):String, NumberOfCharacters+
&his function takes two arguments.
&he first argument specifies the original string.
&he second argument specifies the number of characters from
the most-left that will constitute the sub-string.
After the operation( the L)FT/1 function returns a new
string made of the left character K the NumberOfCharacters
on its right from the String.
print left)NsystemN(9*
varc.ar &I%*):String, NumberOfCharacters+
print right)NsystemN(9*
&o replace one character or a sub-string from a string( you can use the
R)&LC)/1 function. 3ts synta8 is,
varc.ar &E2LA;E:String, FindString, eplace!ith+
print replace)NsystemN(NsysN(N8888N*
&etEr/s part of a c.aracter, Fi/ar9, teDt, or image eDpressio/.
For more i/formatio/ aFoEt t.e valid MicrosoftQ SLL ServerR data
t9pes t.at ca/ Fe Esed 6it. t.is fE/ctio/, see 4ata )9pes.
S9/taD
SUBSTR$NG ( e/*ress!o, , start , le,gt 0
ArgEme/ts
eDpressio/
Is a c.aracter stri/g, Fi/ar9 stri/g, teDt, image, a colEm/, or
a/ eDpressio/ t.at i/clEdes a colEm/. 4o /ot Ese eDpressio/s
t.at i/clEde aggregate fE/ctio/s.
start
Is a/ i/teger t.at specifies 6.ere t.e sEFstri/g Fegi/s.
le/gt.
Is a positive i/teger t.at specifies .o6 ma/9 c.aracters or
F9tes of t.e eDpressio/ 6ill Fe retEr/ed. If le/gt. is /egative,
a/ error is retEr/ed.
).is eDample s.o6s .o6 to retEr/ o/l9 a portio/ of a c.aracter
stri/g. From t.e aEt.ors taFle, t.is qEer9 retEr/s t.e last /ame
i/ o/e colEm/ 6it. o/l9 t.e first i/itial i/ t.e seco/d colEm/.
5SE pEFs
SELE;) aE=l/ame, S5,S)&IN%:aE=f/ame, !, !+
F&'M aEt.ors
'&4E& ,J aE=l/ame
*ere is .o6 to displa9 t.e seco/d, t.ird, a/d foErt. c.aracters
of t.e stri/g co/sta/t aFcdef.
SELE;) D = S5,S)&IN%:'aFcdef', -, 0+
*ere is t.e resElt set:
D
7777777777
Fcd
:! ro6:s+ affected+
Arithmetic /unctions,
SI%N:Expression+
print sign)0"*
print sign)-0"*
print sign)null*
&o get the absolute value of a number( you can use the BS/1 function. 3ts synta8
is,
A,S:Expression+
print abs)-0";:.:::$J*
print abs)N-0."N*
&he ceiling of a number is the closest
integer that is greater than the
number which is specified as argument.
&he ceiling of 0.0"" is 09 because 09
is the closest integer greater than or e4ual to 0.0"".
&he ceiling of LC.!; is LC.
&o get the ceiling of a number( &ransact-SQL provides the C)'L'N-/1 function. 3ts synta8 is,
;EILIN%:Expression+
&his function takes as argument a number or an e8pression that can evaluate to a number. After
the conversion( if the function succeeds( it returns a double-precision number that is greater than
or e4ual to Expression.
print ceiling)0.C";*
print ceiling)-C.!;*
7onsider two decimal numbers such as
0$.CC and -9;.:. &he number 0$.CC is
between 0$ and 0J with 0$ being the lower.
&he number L9;.: is between L9: and L9; with L9:
being the lower.
&he lowest but closest integer value of a number
Bhich is given as argument to it. +ased on this( the floor of 0$.CC is 0$. &he
floor of L9;.: is L9:.
&o support finding the floor of a number( &ransact-SQL provides the FL22R/1 function. 3ts
synta8 is,
FL''&:Expression+
&he FL22R/1 function takes as argument a numeric
value or an e8pression that can be evaluated to a number.
print floor)0$.CC*
print floor)-9;.:*
&o calculate the e8ponential value of a number( &ransact-SQL provides the )D&/1
function. 3ts synta8 is,
E#2:Expression+
&his function takes one argument as a number or an e8pression that can be evaluated to a
number.
print e8p);.C$*
&he power of a number is the value of that number when raised to another number.
&his is done using the following formula,
&etEr/MalEe = D
9
&o support finding the power of a number( &ransact-SQL provides the &2=)R/1 function. 3ts
synta8 is,
2'(E&:D, 9+
&his function takes two re4uired arguments. &he first argument( 8( is used as the base number to
be evaluated. &he second argument( y( also called the e8ponent( will raise 8 to this value.
print power)"(*
print power)"(.0*
print power).;;:($*
&o assist with finding the natural logarithm of a number( &ransact-SQL provides
the L2-/1 function. 3ts synta8 is,
L'%:Expression+
&his function takes one argument as a number or an e8pression that can evaluate to a number.
After the calculation( it returns the natural logarithm of the argument.
print log)0!*
print log)C$.0;*
&o calculate the base 0! logarithm of a number( &ransact-SQL provides the
L2-,E/1 function. 3ts synta8 is,
L'%!":Expression+
&he number to be evaluated is passed as the argument @. &he function returns the logarithm on
base 0! using the formula,
9 = log!"D
which is e4uivalent to
D = !"
9
print log0!)0!*
print log0!)C$.0;*
&o support the calculation of a s4uare root( &ransact-SQL provides the SQRT/1
function. 3ts synta8 is,
SL&):Expression+
&his function takes one argument as a positive decimal number. 3f the number is positive( after
the calculation( the function returns the s4uare root of 8.
print s4rt)"*
print s4rt):.JJJ*
'easure based function,
&he letter `( also written as .3( is a number used in various mathematical
calculations. 3ts appro8imate value is 9.0C0"J;"9"$J:J9. &he calculator of
'icrosoft Bindows represents it as 9.0C0"J;"9"$J:J99$C;;C99$9:J". &o
get the value of .3( &ransact-SQL provides the &'/1 function. 3ts synta8 is simply,
2I:+
print .3)*
3f you know the value of an angle in degrees and you want to get the radians(
&ransact-SQL provides the RD'NS/1 function. 3ts synta8 is,
&A4IANS:Expression+
&his function takes as argument a value in degrees. 3f it succeeds in its calculation( it returns the
radians value.
print radians)0$!*
3f you know the radians but want to get the degrees of an angle( you can use the
D)-R))S/1 function. 3ts synta8 is,
4E%&EES:Expression+
&his function takes as argument a value in radians. 3f it succeeds( it returns the e4uivalent value
in degrees.
print degrees)C*
&o get the cosine of an angle( you can call the C2S/1 function. 3ts synta8 is,
;'S:Expression+
&he angle to be considered is passed as the argument to this function. &he function then
calculates and returns its cosine.
print cos)C"*
&o get the sine of an angle( you can use the S'N/1 function whose synta8 is,
SIN:Expression+
&he angle to be considered is passed as the argument. After its calculation( the function returns
the sine of the angle between L0 and 0.
print sin);!*
&o get the tangent of an angle( you can use the TN/1 function of &ransact-SQL.
3ts synta8 is,
)AN:EDpressio/+
Date and time based functions,
&o get the current date and the current time of the computer that a user is using(
you can use the -)TDT)/1 function of &ransact-SQL. 3ts synta8 is,
%E)4A)E:+
&his function simply returns the current date and time of the operating system.
print AetDate)*
<ne of the primary operations you may want to perform on a date or a time value
would consist of adding a value to it. &o support this operation( &ransact-SQL
provides the DT)DD/1 function. 3ts synta8 is,
4A)EA44:TypeOf"alue, "alueTo#dd, DateOrTimeeferenced+
&he third argument to this function is the value of a date or a time on which the operation will be
performed. 3t can be a constant value in the form of NyearOmonthOdayN for a date or Nhour,minutes
A'O.'N for a time.
&he second argument is the value that will be added. 3t should be a constant integer( such as $( or
a floating point value( such as C.!;.
Bhen calling this function( you must first specify the type of value that you want to add. &his
type is passed as the first argument. 3t is used as follows,
3f you want to add a number of years to a date( specify the TypeOfValue as 7ear or yy( or
yyyy )remember that SQL is case-insensitive*.
print DA&1ADD)yy(C(AetDate)**
print DA&1ADD)mm(C(AetDate)**
print DA&1ADD)dd(C(AetDate)**
print DA&1ADD)yy($(N!0!-!C-:N*
select DA&1ADD)yy($(N!0!-!C-:N* as Tresultant dateU
3f you want to add a number of 4uarters of a year to a date( specify the
TypeOfValue as Quarter or d( or 33.
3n the same way( you can add values as follows,
Type o#
?alue
bbreviation s a result
Dear
yy
A number of years will be added to the date value
yyyy
4uarter
4
A number of 4uarters of a year will be added to the date value
44
'onth
m
A number of months will be added to the date value
mm
dayofyear
y
A number of days of a year will be added to the date value
dy
Day
d
A number of days will be added to the date value
dd
Beek
wk
A number of weeks will be added to the date value
ww
Hour hh A number of hours will be added to the time value
minute
n
A number of minutes will be added to the time value
mi
second
s
A number of seconds will be added to the time value
ss
millisecon
d
ms A number of milliseconds will be added to the time value

Another regular operation performed on a date or a time value consists of getting
the number of units that has elapsed in the range of two dates or two time values.
&o support this operation( &ransact-SQL provides the DT)D'FF/1 function. 3ts
synta8 is,
4A)E4IFF:TypeOf"alue, StartDate, EndDate+
&his function takes three arguments. &he second argument is the starting date or the starting time
of the range to be considered. &he third argument is the end or last date or time of the considered
range. Dou use the first argument to specify the type of value you want the function to produce.
&his argument uses the same value as those of the DT)DD/1 function,
Type o#
?alue
bbreviation s a result
Dear
yy &he function will return the number of years that have elapsed
between the start and the end dates yyyy
4uarter
4 &he function will return the number of 4uarters of a year that have
elapsed between the start and the end dates 44
'onth
m &he function will return the number of months that have elapsed
between the start and the end dates mm
dayofyear
y &he function will return the number of days of a year that have
elapsed between the start and the end dates dy
Day
d &he function will return the number of days that have elapsed
between the start and the end dates dd
Beek
wk &he function will return the number of weeks that have elapsed
between the start and the end dates ww
Hour hh
&he function will return the number of hours that have elapsed
between the start and the end times or dates
minute
n &he function will return the number of minutes that have elapsed
between the start and the end times or dates mi
second
s &he function will return the number of seconds that have elapsed
between the start and the end times or dates ss
millisecon
d
ms
&he function will return the number of milliseconds that have
elapsed between the start and the end times or dates
print DA&1D3//)yy(N!!!-00-0!N(AetDate)**
DATENAME
Ret)r,s a caracter str!,g tat re*rese,ts te
s*ec!1!ed date*art o1 te s*ec!1!ed date
S9/taD:
4A)ENAME : datepart , date +
SELE;) 4A)ENAME:9ear, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)ENAME:mo/t., '-"!!74E;7-1 !-:!":0".!-0'+
,4A)ENAME:da9, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)ENAME:da9of9ear, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)ENAME:6eeGda9, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)ENAME:.oEr, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)ENAME:mi/Ete, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)ENAME:seco/d, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)ENAME:milliseco/d, '-"!!74E;7-1 !-:!":0".!-0'+
go

DATE#ART
Ret)r,s a, !,teger tat re*rese,ts te s*ec!1!ed
date*art o1 te s*ec!1!ed date2
s-,ta/3
DATE#ART ( date*art , date 0
SELE;) 4A)E2A&):9ear, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)E2A&):mo/t., '-"!!74E;7-1 !-:!":0".!-0'+
,4A)E2A&):da9, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)E2A&):da9of9ear, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)E2A&):6eeGda9, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)E2A&):.oEr, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)E2A&):mi/Ete, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)E2A&):seco/d, '-"!!74E;7-1 !-:!":0".!-0'+
,4A)E2A&):milliseco/d, '-"!!74E;7-1 !-:!":0".!-0'+
go
4AJ:+,M'N)*:+,JEA&:+
&etEr/s a/ i/teger represe/ti/g t.e da9 :da9 of t.e
mo/t.+,t.e mo/t. a/d t.e 9ear of t.e specified date.
4AJ : date +
SELE;) 4AJ:'-""B7"170" "!:"!:"!.!-01$CB7"B:""'+
go
SELE;) M'N)*:'-""B7"170" "!:"!:"!.!-01$CB7"B:""'+
go
SELE;) JEA&:'-""B7"170" "!:"!:"!.!-01$CB7"B:""'+
go
SELE;) JEA&:"+, M'N)*:"+, 4AJ:"+
go
Aggregate /unctions,
Count, &he database engine uses the Count/1 function to count the number of
occurrences of the category in the column and produces the total. &his function
also counts EHLL values. &he synta8 of the Count/1 function is,

i/t ;'5N) : S > > ALL T 4IS)IN;) ? expression ? T P U +
&his function takes one argument. &o get the count of occurrences of a value( in the 7riteria
section( select C2.NT/F1.
&he Count/1 function returns an int value. 3f you are working on a large number of
records( you can call the Count%Bi$/1 function. 3ts synta8 is,
Figi/t ;'5N)=,I% : S > ALL T 4IS)IN;) ? expression U T P +
3f the column holds numeric values,
Sum, &he Sum/1 function is used to sum up the values in the category. &he synta8 of the
Sum/1 function is,

Number S5M : > ALL T 4IS)IN;) ? expression +
v$, &he sum of value in a category would be divided by the number of
occurrences in that category to get the average. &he synta8 of the v$/1 function is,

Number AM% : > ALL T 4IS)IN;) ? expression +
Min, &he lowest value of the category would be produced from the Min/1
function. &he synta8 of this function is,
DependsOnType MIN : > ALL T 4IS)IN;) ? expression +
Max: T"e "i$"est value o# t"e cate$ory *ould be produced usin$ t"e Max/1
#unction! T"e syntax o# t"is #unction is:

DependsOnType MA# : > ALL T 4IS)IN;) ? expression +
StdDev: T"e StdDev/1 #unction is used to calculate t"e standard deviation
o# all numeric values o# a $roup! '# t"ere is no value or t"e same value in t"e
considered $roup9 t"is #unction returns N.LL! T"is means t"at t"ere
s"ould be at least t*o di##erent values in t"e $roup!
T"e syntax o# t"e StdDev/1 #unction is:

float S)4EM : > ALL T 4IS)IN;) ? expression +
?ar: T"e ?ar/1 #unction calculates t"e statistical variance o#
all numeric values o# a $roup! '# t"ere is no value or t"e same value in t"e
considered $roup9 t"is #unction returns N.LL! T"e syntax o# t"e
?ar/1 #unction is:

float MA& : > ALL T 4IS)IN;) ? expression +
select C2.NT/comm1 #rom )M&L27))G
select 7<HE&)Q* from 1'.L<D11P
select 7<HE&)Q* Ntotal6no6empN from 1'.L<D11P
select count)Q* as Ttotal number of employeesUfrom 1'.L<D11 P
select 7<HE&)5ob*from 1'.L<D11P
select 7<HE&)distinct 5ob* from 1'.L<D11P
select ?-/sal1 #rom )M&L27))G
select '3E)sal* from 1'.L<D11P
select 'A@)sal* from 1'.L<D11P
select 'A@)comm* from 1'.L<D11P
select stdev)Sal* from 1'.L<D11P
select %A2)sal* from 1'.L<D11P
use videorentalsystem
go
select Q from video
go
Select SH').rice* from %ideo
go
Select '3E).rice* from %ideo
go
Select 'A@).rice* from %ideo
go
Select A%A).rice* from %ideo
go
Select 7<HE&).hone* from 7ustomer
go
Select 7<HE&)Q* from 7ustomer
go
Select 7<HE&)%&itle* from %ideo
go
Select 7<HE&)distinct %&itle* from %ideo
go
Select 7<HE&)%&ype* from %ideo
go
Select 7<HE&)Distinct %&ype* from %ideo
go
use videorentalsystem
go
Select Q from %ideo
go
S1lect 7ity( 7<HE&)7ustomer3d* from customer
Aroup +y 7ity
go
S1lect 7ity( 7<HE&)7ustomer3d* As T7ustomer 3dU from customer
Aroup +y 7ity
go
Select %&ype( 7<HE&)Q* As TEum <f %ideosU from %ideo
group by %&ype
go
Select DistEum( 7<HE&)Q* As TEum of %ideosU from %ideo
group by DistEum
go
Select %&ype(DistEum( 7<HE&)Q* As TEum of %ideosU from %ideo
group by %&ype(DistEum order by %&ype
go
Select DistEum( SH').rice* as T&otal 3nvestmentU from %ideo
Aroup +y DistEum
go
Select DistEum( Avg).rice* as TAverage .riceU from %ideo
Aroup +y DistEum
go
2ollHp,
3t is used to calculate cumulative totals at the end of grouping
created based on the first column in group.
Select %&ype( Sum).rice* as T&otal 3nvestedU from %ideo
Aroup +y %&ype with 2ollHp
go
Select isnull)%&ype(N&otalN* %&ype( Sum).rice* as T&otal 3nvestedU from %ideo
Aroup +y %&ype with 2ollHp
go
7ube is used for calculating sub-totals at the end of each group
Select DistEum(isnull)%&ype(N&otalN*( Sum).rice* As T&otal 7ostU from %ideo
group by %&ype(DistEum with cube
go
7ompute and 7ompute by,
7ompute by is like group by
for the reason that it also
groups records and
applies aggregate function on
each group but unlike group by
compute by allows us to retrieve
data from any column.
use videorentalsystem
go
select Q from video compute sum)price*
use videorentalsystem
go
select Q from video compute count)%ideoEum*
1very column that is in by clause of compute by must be in order by
use videorentalsystem
go
select Q from video order by %&ype compute sum)price* by %&ypeP
<ver )partition by...*
Determines the partitioning and ordering of the rowset before the associated
window function is applied.
.A2&3&3<E +D
Divides the result set into partitions. &he aggregate function
is applied to each partition separately and computation
restarts for each partition.
while _compute by_ will display the result of aggregate only once at end of the
group where as over)partition by...* displays the results of aggregates with every
row in the group and not at the end of the group.
/ind total cost of videos their type wise while displaying complete details of
video.
use videorentalsystem
go
select Q( SH')price* over).artition by %&ype* from %ideo
use videorentalsystem
go
select Q( SH')price* over).artition by %&ype* AS T&otal .riceU from %ideo
/ind highest and lowest costs of videos in a type wise manner while displaying
complete details of every video.
use %ideo2entalSystem
go
select Q( 'A@)price* over ).artition by %&ype*( '3E)price* over).artition by
%&ype* from %ideo
go
select Q( 'A@)price* over ).artition by %&ype* As T'inU( '3E)price*
over).artition by %&ype* As T'a8U from %ideo
go
2anking functions return a ranking value for each row in a partition. Depending on
the function that is used( some rows might receive the same value as other rows.
2anking functions are nondeterministic.
2ank,
2eturns the rank of each row within the partition of a result set. &he rank of a row
is one plus the number of ranks that come before the row in 4uestion.
3f two or more rows tie for a rank( each tied rows receives the same rank. /or
e8ample( if salaries of two employees are the highest and are also e4ual then(
they are both ranked one. &he employee with the ne8t highest salary is ranked
number three( because there are two rows that are ranked higher. &herefore( the
2AE> function does not always return consecutive integers. &he sort order that is
used for the whole 4uery determines the order in which the rows appear in a result
set.
Dense 2ank,
2eturns the rank of rows within the partition of a result set( without any gaps in the
ranking. &he rank of a row is one plus the number of distinct ranks that come
before the row in 4uestion.
3f two or more rows tie for a rank in the same partition( each tied rows receives the
same rank. /or e8ample( if salaries of two employees are the highest and are
also e4ual then( they are both ranked one. &he employee with the ne8t highest
salary is ranked number two. &his is one more than the number of distinct rows
that come before this row. &herefore( the numbers returned by the D1ES162AE>
function do not have gaps and always have consecutive ranks. &he sort order used
for the whole 4uery determines the order in which the rows appear in a result. &his
implies that a row ranked number one does not have to be the first row in the
partition.
use %ideo2entalSystem
go
select row6number)* over )order by price desc* as T2ow numberU(
%&itle(.rice(2AE>)* over )order by price desc* as T2ankU(
D1ES162AE>)* over )order by price desc* as TDense 2ankU
from %ideo
---------------------Q
select 2<B6EH'+12)* over)order by sal desc*( ename(Sal(2AE>)*
over )order by sal desc*( D1ES162AE>)* over )order by sal desc* from employee
show emplyoee name(department number and salary along with rank fro the
employee based on salary dept wise by giving rank0 for the highest paid employee.
select 2<B6EH'+12)* over)partition by deptno order by sal desc*
as Sno( ename(deptno(sal(2AE>)* over )partition by deptno order by sal desc*
as TrankU(D1ES162AE>)* over )partition by deptno order by sal desc*
as Tdense rankU from 1'.L<D11
---------------------------------Q
&op NnN,
&his is used to retrieve top NnN rows from the list of rows retrieved by the selected
statements. 3t supports a keyword apercentb to retrieve top n percent of rows
instead of top n rows. 3t also supports the keyword Nwith tiesb to retrieve every row
from the table that has same value as last row retrieved by the top n clause withing
the column that is specified by in order by clasuse.
Select &op 9 Q from %ideo
go
Select &op Q from %ideo order by .rice
go
Select &op Q from %ideo <rder +y .rice Desc
go
Select &op Bith &ies Q from %ideo <rder +y .rice Desc
go
Select &op "! .ercent Q from %ideo
go
Select &op ! .ercent Q from %ideo <rder +y .rice Desc
go
select top Q from 1'.L<D11 order by SAL desc
select top with ties Q from 1'.L<D11 order by SAL desc
select top C! percent Q from 1'.L<D11 order by SAL desc
Select 7ase Statement in Queries
Hse %ideorentalsystem
go
S1L17& %ideoEum( %&itle( %type(.rice( .rice R
7AS1
BH1E .rice GR" &hen NHigh 7ostN
BH1E .rice GR 9 &hen N'edium 7ostN
1LS1 NLow 7ostN
1ED
/2<' %ideo
-------------------------------Q
Hse %ideorentalsystem
go
select
case when A2<H.3EA)DistEum*R0 then NAll DistributorsN
else 7AS&)DistEum as varchar* end DistEum(
case when grouping )%&ype* R0 then NAll 7ategoriesN
else %&ype end &type(
SH').rice*

from %ideo group by DistEum(%&ype with rollup
------------------------------Q
Hse %ideorentalsystem
go
select
case when A2<H.3EA)DistEum*R0 then NAll DistributorsN
else 7AS&)DistEum as varchar* end DistEum(
case when grouping )%&ype* R0 then NAll 7ategoriesN
else %&ype end &type(
SH').rice*AS TSumU

from %ideo group by DistEum(%&ype with 7ube
---------------------------------------Q
select
case when A2<H.3EA)deptno*R0 then NAll DepartmentsN
else 7AS&)deptno as varchar* end deptno(
case when grouping )5ob* R0 then NAll MobsN
else Mob end 5ob(
SH')sal*

from employee group by deptno(5ob with rollup
-------------------------------------------------Q
select
case when grouping )5ob* R0 then NAll MobsN
else Mob end 5ob(
case when A2<H.3EA)deptno*R0 then NAll DepartmentsN
else 7AS&)deptno as varchar* end deptno(

SH')sal*

from employee group by deptno(5ob with cube
A2'NS
Aoin allo*s us to retrieve data #rom multiple tables usin$
a sin$le select statement!
&hey are classified as,
7ross Moin
3nner Moin
<uter Moin
AES3 synta8,
S1L17& Fcolumns-listG /2<' Ftable0G
inner 5oin O outer 5oinO cross 5oin FtableG
T on F5oin conditionGU......
Eon-AES3
S1L17& Fcolumns-listG /2<' Ftable0G(FtableG....(FtableEG
Twhere F5oin coditionGU
'nner A2'N
A M<3E that displays only rows that have a match in both the 5oined
tables is known as 3EE12 M<3E.
14ui Moin, &his is the inner 5oin or outer 5oin that uses NRN operator in the 5oin condition
Eatural Moin, 1ither inner 5oin or outer 5oin is a natural 5oin if,
it uses NRN operator
all common columns in the tables are in the 5oin condition
only one set of common columns is displayed in the operation
Eon-14ui 5oin, &he inner 5oin or outer 5oin that uses an operator other than NRN in 5oin condition
Self-Moin, A 5oin that 5oins a table with itself
2uter A2'N
A M<3E that includes rows even if they do not have related rows in the 5oined table is an
<uter M<3E. Dou can create three different outer M<3Es to specify the unmatched rows to be
included,
Left <uter M<3E, 3n Left <uter M<3E( all rows in the first-named table( i.e. aleftb table(
which appears leftmost in the M<3E clause( are included.
Hnmatched rows in the right table do not appear.
2ight <uter M<3E, 3n 2ight <uter M<3E( all rows in the second-named table( i.e. arightb table(
which appears rightmost in the M<3E clause( are included. Hnmatched rows in the left table are
not included.
/ull <uter M<3E, 3n /ull <uter M<3E( all rows in all the 5oined tables are included( whether they
are matched or not.
)xamples:
Hse %ideorentalsystem
go
7reate &able %ideoArades)Low.rice decimal)"(*(High.rice decimal)"(*(Arade
char)0**
go
3nsert into %ideoArades values)!."(0.!(N7N*
go
3nsert into %ideoArades values)0.0(9.!(N+N*
go
3nsert into %ideoArades values)9.0(".!(NAN*
go
Hse %ideorentalsystem
go
select 2ental.Q(customer./Eame(customer.LEame
from 2ental 7ross Moin 7ustomer
go
Hse %ideorentalsystem
go
select 2ental.7ustomer3d(2ental.%ideoEumber(
2ental.Date2ented(7ustomer./Eame(7ustomer.LEame(7ustomer.7ity
from 2ental 3nner Moin 7ustomer
<E 2ental.7ustomer3dR7ustomer.7ustomer3d
go
--<2
Hse %ideorentalsystem
go
select 2ental.7ustomer3d(2ental.%ideoEumber(
2ental.Date2ented(7ustomer./Eame(7ustomer.LEame(7ustomer.7ity
from 2ental Moin 7ustomer
<E 2ental.7ustomer3dR7ustomer.7ustomer3d
go
Moining 9 &ables,
Hse %ideorentalsystem
go
select 2ental.7ustomer3d(2ental.%ideoEumber(%ideo.%&itle(
%ideo.%&ype(2ental.Date2ented(7ustomer./Eame(7ustomer.LEame(
7ustomer.7ity from 2ental 3nner Moin %ideo
<E 2ental.%ideoEumber R %ideo.%ideoEum 3nner Moin customer
<E 2ental.7ustomer3dR7ustomer.7ustomer3d
Ao
)xamples Based 2n dventure=or6s
Database
INNER JOIN Example
3n this e8ample we are 5oining between the Sales.Sales<rderDetail and .roduction..roduct
tables. &he tables are aliased with the following, S<D for Sales.Sales<rderDetail and . for
.roduction..roduct. &he M<3E logic is based on matching records in the S<D..roduct3D and
...roduct3D columns. &he records are filtered by only returning records with the S<D.Hnit.rice
greater than 0!!!. /inally( the result set is returned in order with the most e8pensive first based
on the <2D12 +D clause and only the highest 0!! products based on the &<. clause.
HS1 ADBorks
A<
S1L17& &<. 0!! ...roduct3D(
..Eame(
..List.rice(
..Si=e(
..'odifiedDate(
S<D.Hnit.rice(
S<D.Hnit.riceDiscount(
S<D.<rderQty(
S<D.Line&otal
/2<' Sales.Sales<rderDetail S<D
3EE12 M<3E .roduction..roduct .
<E S<D..roduct3D R ...roduct3D
BH121 S<D.Hnit.rice G 0!!!
<2D12 +D S<D.Hnit.rice D1S7
A<
Moining 9 &ables
HS1 AdBorksP
A<
S1L17& 7.7ontact3D(
7./irstEame(
7.LastEame(
S..Sales.erson3D(
S..7ommission.ct(
S..SalesD&D(
S..SalesLastDear(
S..+onus(
S&.&erritory3D(
S&.Eame(
S&.TAroupU(
S&.SalesD&D
/2<' .erson.7ontact 7
3EE12 M<3E Sales.Sales.erson S.
<E 7.7ontact3D R S..Sales.erson3D
3nner M<3E Sales.Sales&erritory S&
<E S&.&erritory3D R S..&erritory3D
<2D12 +D S&.&erritory3D( 7.LastEame
A<
LEFT OUTER JOIN Example
3n this e8ample we are combining two concepts to show that more than two tables can be
M<3Eed in one S1L17& statement and more than one M<3E type can be used in a single
S1L17& statement. 3n the sample code below( we are retrieving the matching data between the
.erson.7ontact and Sales.Sales.erson tables in con5unction with all of the data from the
Sales.Sales.erson table and matching data in the Sales.Sales&erritory table. /or records that
e8ist Sales.Sales.erson table and not in the Sales.Sales&erritory table( EHLL values are returned
for the columns in the Sales.Sales&erritory. 3n addition( this code uses two columns to order the
data i.e. S&.&erritory3D and 7.LastEame.
HS1 AdBorksP
A<
S1L17& 7.7ontact3D(
7./irstEame(
7.LastEame(
S..Sales.erson3D(
S..7ommission.ct(
S..SalesD&D(
S..SalesLastDear(
S..+onus(
S&.&erritory3D(
S&.Eame(
S&.TAroupU(
S&.SalesD&D
/2<' .erson.7ontact 7
3EE12 M<3E Sales.Sales.erson S.
<E 7.7ontact3D R S..Sales.erson3D
L1/& <H&12 M<3E Sales.Sales&erritory S&
<E S&.&erritory3D R S..&erritory3D
<2D12 +D S&.&erritory3D( 7.LastEame
A<
RIGHT OUTER JOIN Example
3n an effort to e8plain how the 23AH& <H&12 M<3E and L1/& <H&12 M<3E is logically a
reciprocal on one another( the code below is re-written version of the L1/& <H&12 M<3E
above. As you can see the M<3E order and tables are different( but the final result set matches the
L1/& <H&12 M<3E logic. 3n the sample code below( we are retrieving the matching data
between the .erson.7ontact and Sales.Sales.erson tables in con5unction with all of the data from
the Sales.Sales.erson table and matching data in the Sales.Sales&erritory table. /or records that
e8ist Sales.Sales.erson table and not in the Sales.Sales&erritory table( EHLL values are returned
for the columns in the Sales.Sales&erritory.
HS1 AdBorksP
A<
S1L17& 7.7ontact3D(
7./irstEame(
7.LastEame(
S..Sales.erson3D(
S..7ommission.ct(
S..SalesD&D(
S..SalesLastDear(
S..+onus(
S&.&erritory3D(
S&.Eame( S&.TAroupU(
S&.SalesD&D
/2<' Sales.Sales&erritory S&
23AH& <H&12 M<3E Sales.Sales.erson S.
<E S&.&erritory3D R S..&erritory3D
3EE12 M<3E .erson.7ontact 7
<E 7.7ontact3D R S..Sales.erson3D
<2D12 +D S&.&erritory3D( 7.LastEame
A<
Self Join Example
3n this e8ample( we are actually self 5oining to the Human2esources.1mployee table. Be are
doing this to obtain the information about the 1mployee and 'anager relationship in the
Human2esources.1mployee table. 3n con5unction with that M<3E logic we are also 5oining to the
.erson.7ontact twice in order to capture the name and title data based on the original 1mployee
and 'anager relationships. 3n addition( another new concept introduced in this 4uery is aliasing
each of the columns. Although we could have done so in the previous e8amples( we made point
of doing so in this 4uery to differentiate between the 1mployee and 'anager related data.
HS1 AdBorksP
A<
S1L17& '.'anager3D AS N'anager3DN(
'0.7ontact3D AS N'anager7ontact3DN(
'0./irstEame AS N'anager/irstEameN(
'0.LastEame AS N'anagerLastEameN(
'.&itle AS N'anager&itleN(
1.1mployee3D AS N1mployee3DN(
10.7ontact3D AS N1mployee7ontact3DN(
10./irstEame AS N1mployee/irstEameN(
10.LastEame AS N1mployeeLastEameN(
1.&itle AS N1mployee&itleN
/2<' Human2esources.1mployee 1
3EE12 M<3E Human2esources.1mployee '
<E 1.'anager3D R '.'anager3D
3EE12 M<3E .erson.7ontact 10
<E 10.7ontact3D R 1.7ontact3D
3EE12 M<3E .erson.7ontact '0
<E '0.7ontact3D R '.7ontact3D
<2D12 +D '0.LastEame
A<
CROSS JOIN Example
As indicated above( please heed caution when running or modifying this 4uery in any SQL
Server database environment. &he result set is intentionally limited by the &<. 0!! clause and
the BH121 clause to prevent a 7artesian product( which is the result of each of the rows from
the left table multiplied by the number of rows in the right table.
HS1 AdBorksP
A<
S1L17& &<. 0!! ...roduct3D(
..Eame(
..List.rice(
..Si=e(
..'odifiedDate(
S<D.Hnit.rice(
S<D.Hnit.riceDiscount(
S<D.<rderQty(
S<D.Line&otal
/2<' Sales.Sales<rderDetail S<D
72<SS M<3E .roduction..roduct .
BH121 S<D.Hnit.rice G 9"!!
<2D12 +D S<D.Hnit.rice D1S7
A<
FULL OUTER JOIN Example
3n our last e8ample( we have modified the logic from the L1/& <H&12 M<3E e8ample above
and converted the L1/& <H&12 M<3E synta8 to a /HLL <H&12 M<3E. 3n this circumstance(
the result set is the same as the L1/& <H&12 M<3E where we are returning all of the data
between both tables and data not available in the Sales.Sales&erritory is returned as EHLL.
HS1 AdBorksP
A<
S1L17& 7.7ontact3D(
7./irstEame(
7.LastEame(
S..Sales.erson3D(
S..7ommission.ct(
S..SalesD&D(
S..SalesLastDear(
S..+onus(
S&.&erritory3D(
S&.Eame(
S&.TAroupU(
S&.SalesD&D
/2<' .erson.7ontact 7
3EE12 M<3E Sales.Sales.erson S.
<E 7.7ontact3D R S..Sales.erson3D
/HLL <H&12 M<3E Sales.Sales&erritory S&
<E S&.&erritory3D R S..&erritory3D
<2D12 +D S&.&erritory3D( 7.LastEame
A<
S)T 2&)RT'2NS
Set <perations are used to combine multiple result sets
into one single result set.
&here is +3A difference between a5oinb and a7ombineb.
Moin is Hori=ontal operation and a7ombineb is vertical operation.
select Q into cheapvideos from video where price F 9.!
select Q into 1mployee6Hist from employee where hiredate F N0J$0-0-90N
LetXs go with simple e8ample so that it will give you clear picture.
Basically t"ere are H set operators available in SQL Server!
0* Hnion, &his is to combine two or more result
sets into single
without or with )by using ALL* duplicates.
* 18cept, &akes the data from one result set
where there is no matching in another.
9* 3ntersect, &akes the data from both the
result sets which are in common.
<ne thing you need to make sure is when you are using set <perations(
the Eo. of columns should be same with the data type.
&here is no restriction on the column names.
Rules on Set 2perations:
0* &he column names or aliases must be
determined by the first select.
* 1very select must have the same
number of columns(
and each lineup of columns must
share the same data-type family.
9* 18pressions may be added to the
select statements to identify
the source of the row so long as the
column is added to every select.
C* <2D12 +D clause )if any* should be part
of the last Select statement but must refer to
column)s* of first select statement.

S1L17& %ideoEum(%title(.rice from %ideo
Hnion
S1L17& %ideoEum(%title(.rice from 7heap%ideos
go
S1L17& %ideoEum(%title(.rice from %ideo
Hnion ALL
S1L17& %ideoEum(%title(.rice from 7heap%ideos
go
S1L17& 1mpno(eEame(Sal(hiredate from 1mployee
HE3<E
S1L17& 1mpno(eEame(Sal(hiredate from 1mployee6H3S&

Here also we are combining the results from 1mployee and 1mployee6H3S& table.
Bhen you use HE3<E ALL operator it will not eliminate the duplicate records
meaning if you have the same record in both tables then in the final output you will
see both the records.
HE3<E is always creates the performance issue. So when ever you are using
HE3<E use it very 5udiciously. 3f you are not sure of what kind of data you have
then you can use HE3<E. 3f you know you donXt have any duplicate records for
which you want to combine the results then use HE3<E ALL.
S1L17& 1mpno(eEame(Sal(hiredate from 1mployee
HE3<E ALL
S1L17& 1mpno(eEame(Sal(hiredate from 1mployee6H3S&
3ntersection,
As you know this is basically to combine multiple result sets into single to fetch
the common records in multiple result sets. 3nner 5oin finds common rows
hori=ontally( while an 3E&12S17& finds common rows vertically.
S1L17& %ideoEum(%title(.rice from %ideo
3ntersect
S1L17& %ideoEum(%title(.rice from 7heap%ideos
go
S1L17& 1mpno(eEame(Sal(hiredate from 1mployee
3E&12S17&
S1L17& 1mpno(eEame(Sal(hiredate from 1mployee6H3S&

18cept,
&his is basically to return all the records from one result set where there is no
matching in another table. &his looks very similar to a<uter 5oinb but 5oin does
hori=ontally and 1@71.& does vertically.
S1L17& %ideoEum(%title(.rice from %ideo
18cept
S1L17& %ideoEum(%title(.rice from 7heap%ideos
go
S1L17& 1mpno(eEame(Sal(hiredate from 1mployee
1@71.&
S1L17& 1mpno(eEame(Sal(hiredate from 1mployee6H3S&

Bith the above 4uery we are fetching only the records which are in 1mployee but
not in 1mployee6H3S&.
S1L17& %ideoEum(%title(.rice(.riceQ!." AS sf0 from %ideo
Hnion ALL
S1L17& %ideoEum(%title(.rice(.riceQ!." As sf from 7heap%ideos
go
S1L17& %ideoEum(%title(.rice from %ideo
Hnion ALL
S1L17& %ideoEum(%title(.rice from 7heap%ideos <rder by .rice
go
Summary:
Eormally set operations are costly operations so use them very 5udiciously.
S.BQ.)R')S
A sub4uery is a 4uery that is nested inside a
S1L17&( 3ES12&( H.DA&1( or D1L1&1 statement(
or inside another sub4uery.
A sub4uery is also called an inner 4uery or inner select(
while the statement containing a sub4uery is also called
an outer 4uery or outer select.
'any &ransact-SQL statements that include sub4ueries
can be alternatively formulated as 5oins. <ther 4uestions
can be posed only with sub4ueries.
3n &ransact-SQL(
there is usually no performance difference between a
statement that includes a sub4uery and a 5oin.
However( in some
cases where e8istence must be checked( a 5oin yields
better performance.
<therwise( the nested 4uery must
be processed for each result of the outer 4uery to ensure
elimination of duplicates. 3n such cases( a 5oin approach
would yield better results.
A sub4uery nested in the outer S1L17& statement has
the following components,
A regular S1L17& 4uery including the regular select list components.
A regular /2<' clause including one or more tables or view names.
An optional BH121 clause.
An optional A2<H. +D clause.
An optional HA%3EA clause.
&he S1L17& 4uery of a sub4uery is always enclosed in parentheses.
3t cannot include a 7<'.H&1 clause( and may
only include an <2D12 +D clause when a &<.
clause is also specified.
A sub4uery can be nested inside the BH121 or HA%3EA clause of an outer
S1L17&( 3ES12&( H.DA&1( or D1L1&1 statement( or inside another sub4uery.
Hp to 9 levels of nesting is possible(
although the limit varies based on available memory
and the comple8ity of other e8pressions in the 4uery.
A sub4uery can appear anywhere an e8pression can be used( if it returns a single
value.
3f a table appears only in a sub4uery and not in the outer 4uery( then columns from
that table cannot be included in the output )the select list of the outer 4uery*.
Statements that include a sub4uery usually take one of these formats,
BH121 e8pression TE<&U 3E /sub4uery1
BH121 e8pression comparison6operator TAED ] ALLU /sub4uery1
BH121 TE<&U 1@3S&S /sub4uery1
3n some &ransact-SQL statements( the sub4uery can be evaluated as if it were an
independent 4uery. 7onceptually( the sub4uery results are substituted into the outer
4uery )although this is not necessarily how 'icrosoft SQL Server actually
processes &ransact-SQL statements with sub4ueries*.
&here are three basic types of sub4ueries,
Sub4ueries that operate on lists introduced with 3E(
or those that a comparison operator modified by AED or ALL.
Sub4ueries tht are introduced with an unmodified
comparison operator and must return a single value.
sub3uery t"at only selects one column or expression
and returns Iust one ro* is also called as a Scalar sub3uery!
Sub4uries that are used with 1@3S&S.
Scalar sub4ueries,
scalar sub4ueries allow us to treat the output of a sub4uery as a column or even an
e8pression within a S1L17& statement. 3t is a 4uery that only selects one column
or e8pression and returns Iust one ro*. 3f the scalar sub4uery fails to return any
rows( S4l Server will use a EHLL value for the output of the scalar sub4uery.
Brite a 4uery to determine number of videos supplied by
each Distributor and display the result along with
distrubutor number and name
Hse %ideo2entalSystem
go
select d.distributornum(d.DistributorEame (
)select 7<HE&)Q* from video v
where v.distnumRd.distributornum* As TEum %ideosU
from Distributor dP
----------------------------------------Q
Show number(title(type and distribuotr number of all
those videos supplied by the distrbutor L Disney Studios
Hse %ideo2entalSystem
go
select %ideoEum(%&itle(%&ype(DistEum from %ideo where
Distnum R )select DistributorEum from Distributor
where DistributorEame R NDisney StudiosN *P
7orrelated Sub4uery,
Brite a 4uery to determine how many number of times every video is ever issued
to any customer,
select v.%ideoEum(v.%&itle()select 7<HE&)Q* from rental r
where r.%ideoEumberRv.%ideoEum* As TEum 3ssuesU from %ideo %P
go
----------------------------Q
---------------------------Q
Brite a 4uery to show all the details of all those videos
that were supplied by the same distributor who supplied the
video C:::-0
select Q from %ideo where DistEum R
)select DistEum from %ideo where
%ideoEumRNC:::-0N*
go
--------------------------------Q
select Q from 1mployee where 5ob R )select 5ob from employee where
empnoR:;J$*P
-----------------------------------Q
Sub4ueries returning more than one row,
Show all the details of all the videos whose type is not the same
as the type of the video aAone with the bree=eb
Select v0.Q from %ideo v0
where v0.%&ype Eot 3n
)select v.%&ype from video v
where v.%&itle RNAone with the bree=eN*
go
List those videos whose price is less than the price of any video
belonging to the category NDramaN
Select Q from %ideo where .rice F Any)
Select .rice from %ideo where %&ypeRNDramaN*
go
List those videos whose price is less than the price of all videos
belonging to the category NDramaN
List those videos whose price is greater than the price of all
videos belonging to the category NDramaN
Select Q from %ideo where .rice G ALL)
Select .rice from %ideo where %&ypeRNDramaN*
go
List those videos whose price is less than the least price of all Drama type videos
Select Q from %ideo where .rice F ALL)
Select .rice from %ideo where %&ypeRNDramaN*
go
-----------------------------Q
Select e0.Q from employee e0 where e0.deptno FG )select e.deptno from
employee e where e.enameRNS'3&HN*P
-----------------------Q
Eested Sub4uery,
Brite a 4uery to list all the details of all those videos rented by customers living in
the city LA
Select %ideo.Q from %ideo where %ideoEum 3n
)Select 2ental.%ideoEumber from 2ental where 2ental.7ustomer3d 3n
)Select 7ustomer.7ustomer3d from customer where 7ustomer.7ityRNLAN**
go
-------------------------------Q
List all the employees who are working in 7hicago.
select empno(ename(5ob(sal(deptno from empL<D11 where
deptno in )select deptno from departments
where loc R N7H37AA<N*P
----------------------------------------Q
select Q from employee where sal G any)select Sal from employee where deptno R
9!*P
select Q from employee where sal G all)select Sal from employee where deptno R
9!*P
select Q from employee where sal F all)select Sal from employee where deptno R
9!*P
select Q from 1mployee where Deptno in )select Deptno from departments where
loc in)NE1B D<2>N(N7H37AA<N** P
-------------------------------------Q
usin$ a$$re$ate #unctions in sub3ueries:
Find second "i$"est salary:
/ind second highest price ,
select 'A@).rice* as high from %ideo
where price F )Select 'A@)price* from %ideo*P
select 'A@)sal* as high from employee
where Sal F )Select 'A@)sal* as sal0 from employee*P
/ind 9
rd
highest .rice,
select '3E)price* as high9 from video
where price in
)select distinct top 9 price from video order by price desc *
/ind C
th
highest .rice,
select '3E)price* as highC from video
where price in
)select distinct top C price from video order by price desc *
-------------------------------------Q
/ind "
th
highest salary,
select '3E)sal* as high" from employee
where Sal in )select distinct top " sal from employee order by Sal desc *
VVVVVVVVVVVVVVVVVVVVVVVVVVVVV

2eplacing a column name with a sub4uery,
write a 4uery to display price and avg of price for all videos,
Hse %ideorentalsystem
go
Select %&itle(.rice(
)select SH').rice* from %ideo *O)select 7<HE&)Q* from %ideo* AS
TAvg .riceU from %ideo
go
Brite a 4uery to find by how much price of each video
differs from the highest price,
Hse %ideorentalsystem
go
select %&itle(
)select ma8).rice* from %ideo* as Tma8priceU (
price(
))select ma8)price* from %ideo * - price *
as TdifferenceU from %ideo
----------------------Q
go
select ename(
)select ma8)sal* from employee* as Tma8salU (
sal(
))select ma8)sal* from employee * - sal *
as TdifferenceU from employeeP
Correlated sub3uery
A correlated sub4uery is evaluated once /<2 1A7H 2<B as opposed to a normal
sub4uery which is evaluated only once for each table.
Dou can reference the outer 4uery inside the correlated sub4uery using an alias
which makes it so handy to use.
LetNs select all employees whose salary is less than the average of all the
employeesN salaries in the same department.
7orrelated Sub4uery,
Brite a 4uery to determine how many number of times every video is ever issued
to any customer,
select v.%ideoEum(v.%&itle()select 7<HE&)Q* from rental r
where r.%ideoEumberRv.%ideoEum* As TEum 3ssuesU from %ideo %P
----------------------------Q
Brite a 4uery to determine how many rows in the D1.A2&'1E&S table contain
an employee corresponding to each row in the 1'.L<D11 table.
select d.deptno(d.dname()select 7<HE&)Q* from employee e
where e.deptnoRd.deptno* As TEum DeptU from departments dP
-----------------------------------Q
Brite a 4uery to determine number of videos supplied by
each Distributor and display the result along with
distrubutor number and name
Hse %ideo2entalSystem
go
select d.distributornum(d.DistributorEame (
)select 7<HE&)Q* from video v
where v.distnumRd.distributornum* As TEum %ideosU
from Distributor dP
------------------------------------Q
select 8.ename (8.sal (8.deptno from employee 8 where
8.sal F )select avg)sal* from employee y
where 8.deptno R y.deptno*
order by 8.deptnoP
---------------------------------------------Q
.sin$ a sub3uery in an update:
2aise the prices of all those videos
whose present prices are less than the
present avg price to that present average price itself.
Select Q into &emp%ideo from %ideo
go
H.DA&1 &emp%ideo
set price R )select avg)price*
from &empvideo*
where price F
)select avg)price* from &emp%ideo *P
Select Q from &emp%ideo
go
------------------------Q
LetNs give these people
)whose salary is less than their departmentNs average* a raise.
select Q into employee9 from employeeP
select ename( sal( deptno from employee9
order by deptno( enameP
H.DA&1 employee9
set sal R )select avg)sal*
from employee9 b
where
deptno R b.deptno*
where sal F
)select avg)sal* from employee9 c
where deptno R c.deptno*P
.sin$ a sub3uery in a delete
Brite a 4uery to delete lowest priced video or videos among
%type - N7omedyN
delete from %ideo9 where %&ypeRN7omedyN AED
price R )select min)price* from %ideo9 8
where 8.%&ypeRN7omedyN*

A<
---------------------Q
LetNs delete the highest earning employees in each department.
delete from employee where
sal R )select ma8)sal* from employee b
where deptno R b.deptno*P
------------------------------Q
3nserting into &ables( based on %alues from other &ables
Scalar sub4ueries are also handy for inserting into tables(
based on values from other tables.
7rate a table and store the following summaries
of .rice as a record,
sum(ma8(min and avg
create table summary )
sum6price numeric(
ma86price numeric(
min6price numeric(
avg6price numeric
*P
insert into summary )
sum6price(
ma86price(
min6price(
avg6price*
values )
)select sum)price* from video*(
)select ma8)price* from video*(
)select min)price* from video*(
)select avg)price* from video*
*P
select Q from summaryP
666666666666666666666666666666666Q
create table summary )
sum6sal numeric(
ma86sal numeric(
min6sal numeric(
avg6sal numeric
*P
insert into summary )
sum6sal(
ma86sal(
min6sal(
avg6sal*
values )
)select sum)sal* from employee*(
)select ma8)sal* from employee*(
)select min)sal* from employee*(
)select avg)sal* from employee*
*P
select Q from summaryP
--------------------------------Q
5si/g EDists:
(rite a qEer9 to list all t.ose videos 6.ic. .ave
/ever Fee/ issEed E/til /o6:
Select Q from %ideo
go
Select Q from 2ental
go
Select v.Q from %ideo v where not e8ists)
Select r.%ideoEumber /rom 2ental r
Bhere r.%ideoEumber R %.%ideoEum*
go
7777777777777P
select ename from employee e
where mgr in )select 1'.E< from 1'.L<D11 where 1EA'1RN>3EAN*P
select ename from employee e
where e8ists )select ename from employee 8 where e.mgr R 8.empno and
ename R N>3EAN*P
(*EN J'5 5SE 'IN', (*ILE ;*E;<IN% F'& (*E&E ;'N4I)I'N SLL
SE&ME& EN%INE 4'ES (*'LE )A,LE S;AN.
IF J'5 5SE 'E#IS)S' AS S''N AS EN%INE FIN4S )*E &EL5I&E4
&'( I) (ILL S)'2 E#E;5)IN% L5E&J AN4 %'IN% F5&)*E& S;ANNIN%
)A,LE.
S' ,ASI;ALLJ E#IS)S IS FAS)E& AS ;'M2A&E4 )' IN.
Esi/g t.e IN claEse, 9oE're telli/g t.e rEle7Fased
optimi8er t.at 9oE 6a/t t.e i//er qEer9 to drive t.e oEter
qEer9 :t.i/G: IN = i/side to oEtside+.
(.e/ 9oE 6rite E#IS)S i/ a 6.ere claEse, 9oE're telli/g t.e
optimi8er t.at 9oE 6a/t t.e oEter qEer9 to Fe rE/ first,
Esi/g eac. valEe to fetc. a valEe from t.e i//er qEer9
:t.i/G: E#IS)S = oEtside to i/side+.
/ind the names of all those employees who are working 3n 'r.SmithNs department.
3n the output show department name also against each employee name.
S1L17& e0.ename( d.dname
/2<' employee e0 inner 5oin departments d
on e0.deptno R d.deptno
AED 1@3S&S
)S1L17& Q /2<' employee e
BH121 e.ename R NSmithN AED e.deptno R e0.deptno*

--------------------------------------------Q
Eested sub 4uery,
Display all the details of those videos whose price is more than the least price of
videos supplied by NDisney StudiosN.

Select Q from %ideo where .rice G )
Select '3E)price* from %ideo
where DistEum R )
Select DistributorEum from Distributor
where DistributorEameRNDisney StudiosN**
go
-----------------------Q
Display the records of those employees who are earning more than the least salary
earned by any employee working at E1B D<2>.

S1L17& eEame
/2<' 1mployee
BH121 sal G)S1L17& min)sal*
/2<' 1mployee
BH121 deptno R )S1L17& deptno
/2<' departments
BH121 loc R NE1B
D<2>N**P
Show the records of those employees who are earning less than any salesman along
with records of those employees who are working the same department in which
any salesman worksP
S1L17& Q
/2<' 1mployee
BH121 sal F)S1L17& min)sal* /2<' 1mployee
BH121 5ob R NSAL1S'AEN*
or
deptno R )S1L17& distinct deptno
/2<' 1mployee
BH121 5ob R NSAL1S'AEN*P


?')=S
?ie*
A view is a virtual table that consists of columns from one or more tables.
3t is a 4uery stored as an ob5ect. Hence( a view is an ob5ect that derives
its data from one or more tables. &hese tables are referred to as base
or underlying tables.
<nce you have defined a view( you can reference it like any other table in a
database.
A view serves as a security mechanism. &his ensures that users are able to
retrieve and modify only the data seen by them.
Hsers cannot see or access the remaining data in the underlying tables.
A view also serves as a mechanism to simplify 4uery e8ecution.
7omple8 4ueries can be stored in the form of a view(
and data from the view can be e8tracted using simple 4ueries.
)xample
7onsider the .ublishers table below. 3f you want users to see only two columns in
the table( you can create a view called vw.ublishers that will refer to the
.ublishers table and the two columns re4uired. Dou can grant .ermissions to users
to use the view and revoke .ermissions from the base .ublishers table. &his way(
users will be able to view only the two columns referred to by the view. &hey will
not be able to 4uery on the .ublishers table.
&ublis"ers
.ubld .ubEame 7ity State 7ountry
!:9; Eew 'oon +ooks +oston 'A HSA
!$:: +innet # Hardly Bashington D7 HSA
09$J Algodata 3nfosystems +erkeley 7A HSA
0; /ive Lakes .ublishing 7hicago 3L HSA
?= &ublis"ers
.ubld .ubEame
!:9; Eew 'oon +ooks
!$:: +innet # Hardly
09$J Algodata 3nfosystems
0; /ive Lakes .ublishing
%iews ensure the security of data by restricting access to the following data,
Specific rows of the tables.
Specific columns of the tables.
Specific rows and columns of the tables.
2ows fetched by using 5oins.
Statistical summary of data in a given tables.
Subsets of another view or a subset of views and tables.
Some common e8amples of views are,
A subset of rows or columns of a base table.
A union of two or more tables.
A 5oin of two or more tables.
A statistical summary of base tables.
A subset of another view( or some combination of views and base table.
Creatin$ ?ie*s
A view can be created by using the 721A&1 %31B statement.
Syntax
721A&1 %31B view6name
T)column6nameT(column6nameUc.*U
TB3&H 1E72D.&3<EU
AS select6statement TB3&H 7H17> <.&3<EU
Bhere,
view6name specifies the name of the view and must follow the rules for identifiers.
column6name specifies the name of the column to be used in view. 3f the
column6name option is not specified( then the view is created with the same
columns as specified in the select6statement.
B3&H 1E72D.&3<E encrypts the te8t for the view in the syscomments table.
AS specifies the actions that will be performed by the view.
select6statement specifies the S1L17& Statement that defines a view. &he view
may use the data contained in other views and tables.
B3&H 7H17> <.&3<E forces the data modification statements to fulfill the
criteria given in the S1L17& statement defining the view. 3t also ensures that the
data is visible after the modifications are made permanent.
&he restrictions imposed on views are as follows,
A view can be created only in the current database.
&he name of a view must follow the rules for identifiers and must not be the
same as that of the base table.
A view can be created only if there is a S1L17& permission on its base
table.
A S1L17& 3E&< statement cannot be used in view declaration statement.
A trigger or an inde8 cannot be defined on a view.
&he 721A&1 %31B statement cannot be combined with other SQL
statements in a single batch.
)xample
721A&1 %31B vw7ustomer
AS
S1L17& 7ustomer3d( 7ompany Eame( .hone
/2<' 7ustomers
7reates a view called vw7ustomer. Eote that the view is a 4uery stored as an
ob5ect. &he data is derived from the columns of the base table 7ustomers.
Dou use the view by 4uerying the view like a table.
S1L17& Q/2<' vw7HS&<'12
.pdatable ?ie*s
Dou can modify the data of an underlying base table through a view(
as long as the following conditions are true,
Any modifications( including H.DA&1( 3ES12&( and D1L1&1 statements(
must reference columns from only one base table.
&he columns being modified in the view must directly reference the
underlying data in the table columns. &he columns cannot be derived in
any other way( such as through the following,
An aggregate function, A%A( 7<HE&( SH'( '3E( 'A@(
A2<H.3EA( S&D1%( S&D1%.( %A2( and %A2..
A computation. &he column cannot be computed from an e8pression
that uses other columns. 7olumns that are formed by using the set
operators HE3<E( HE3<E ALL( 72<SSM<3E( 1@71.&(
and 3E&12S17& amount to a computation and are also not updatable.
&he columns being modified are not affected by A2<H. +D(
HA%3EA( or D3S&3E7& clauses.
&<. is not used anywhere in the select6statement of the view together with
the B3&H 7H17> <.&3<E clause.
ST2R)D &R2C)D.R)S
Creatin$ a Stored &rocedure t"at returns a value:
use videorentalsystem
go
721A&1 .2<7 &est2eturn )V3n%alue int*
AS
2eturn V3nvalue
A<
D17LA21 V2eturn%alue 3E&
1@17 V2eturn%alue R &est2eturn 9
S1L17& 2eturn%alueRV2eturn%alue
A<
Creatin$ a Stored &rocedure *it" 2.T&.T &arameters
use videorentalsystem
go
721A&1 .2<71DH21 Aet7ount+yLastEame )
VLEame E%A27HA2)"!*(
VLastEame7ount 3E& <H&.H& *
AS
S1L17& VLastEame7ount R 7<HE&)Q*
/2<' customer
BH121 LEame R VLEame
A<
D17LA21 V&he7ount 3E&
1@17 Aet7ount+yLastEame
VLEame R N+rownN(
VLastEame7ount R V&he7ount <H&.H&
S1L17& &he7ount R V&he7ount
A<
Creatin$ a Stored &rocedure *it" 2.T&.T &arameters
use videorentalsystem
go
721A&1 .2<71DH21 op6test
Vip0 int(
Vop0 int <H&.H&(
Vop int <H&.H&
AS
set Vop0 R 0! K Vip0
set Vop R ! K Vip0
go
--7all it like this,
declare Vp int R 0!
declare V8 int
declare Vy int
e8ec op6test Vp (V8 <H&.H&( Vy <H&.H&
select V@
select Vy
Creatin$ a Stored &rocedure *it" 2.T&.T &arameters
use videorentalsystem
go
721A&1 .2<71DH21 AetEum<f%ideos+y%&ype )
V%&ype E%A27HA2)"!*(
V%ideo7ount 3E& <H&.H& *
AS
S1L17& V%ideo7ount R 7<HE&)Q*
/2<' %ideo
BH121 %&ype R V%&ype
2eturn
Ao
--call
D17LA21 V&he7ount 3E&
1@17 AetEum<f%ideos+y%&ype
V%&ype R N7omedyN( V%ideo7ount R V&he7ount <H&.H&
S1L17& &he7ount R V&he7ount
A<
777777777777777777P
Stored procedure *it" de#ault parameters
use %ideo2entalSystem
go
3/ 1@3S&S )S1L17& name /2<' sysob5ects
BH121 name R N'y.rocedure0N AED type R N.N*
D2<. .2<71DH21 'y.rocedure0
A<
7reate procedure 'y.rocedure0)
Vpara0 int R 0!(
Vpara int*
As
.rint Vpara0 K Vpara
2eturn
Ao
18ec 'y.rocedure0 Vpara R 9!
go
777777777777777777777777P
use %ideo2entalSystem
go
3/ 1@3S&S )S1L17& name /2<' sysob5ects
BH121 name R N'y.rocedureN AED type R N.N*
D2<. .2<71DH21 'y.rocedure
A<
7reate procedure 'y.rocedure)
Vpara0 int (
Vpara intR0!!*
As
.rint Vpara0 K Vpara
2eturn
Ao
18ec 'y.rocedure 0"!
go
18ec 'y.rocedure Vpara0 R !!
go
-------------------------------Q
use %ideo2entalSystem
go
3/ 1@3S&S )S1L17& name /2<' sysob5ects
BH121 name R N'y.rocedure9N AED type R N.N*
D2<. .2<71DH21 'y.rocedure9
A<
7reate procedure 'y.rocedure9)
Vpara0 intR"! (
Vpara intR0!!*
As
.rint Vpara0 K Vpara
2eturn
Ao
18ec 'y.rocedure9 0!(!
go
18ec 'y.rocedure9 Vpara0 R !!
go
18ec 'y.rocedure9 Vpara R "
go
18ec 'y.rocedure9 Vpara0 R C"( Vpara R ;!
go
-------------------------Q
Stored procedure *it" *ildcard parameters
Ese videore/tals9stem
go
3/ 1@3S&S )S1L17& name /2<' sysob5ects
BH121 name R N%ideo3nfoN AED type R N.N*
D2<. .2<71DH21 %ideo3nfo
A<
721A&1 .2<71DH21 %ideo3nfo
V%&itle varchar)9!* R NA\N
AS
S1L17& %ideoEum(%&itle(.rice
/2<' %ideo
BH121 %&itle L3>1 V%&itle

A<
--&he %ideo3nfo stored procedure can be
--e8ecuted in many combinations.
1@17H&1 %ideo3nfo
-- <r
1@17H&1 %ideo3nfo NA\N
-- <r
1@17H&1 %ideo3nfo V%&itle R N&\N
-- <r
1@17H&1 %ideo3nfo NAlien SurferN
-------------------------------Q
.se de#erred name resolution
&his e8ample shows a procedure that uses deferred name resolution. &he stored procedure is
created although the table that is referenced does not e8ist at compile time. &he table must e8ist(
however( at the time the procedure is e8ecuted.
Ese Mideo&e/talS9stem
go
3/ 1@3S&S )S1L17& name /2<' sysob5ects
BH121 name R N'y.rocedureCN AED type R N.N*
D2<. .2<71DH21 'y.rocedureC
A<
7reate procedure 'y.rocedureC
AS
Select Q from Hn>nown&able
Ao
.se a simple procedure *it" a complex S)L)CT
Ese /ort.6i/dI
go
3/ 1@3S&S )S1L17& name /2<' sysob5ects
BH121 name R Nemp6info6allN AED type R N.N*
D2<. .2<71DH21 emp6info6all
A<
721A&1 .2<71DH21 emp6info6all
AS
S1L17& e.empno(e.ename(e.mgr(m.ename AS
'anager(e.sal(SALA2AD1.A2AD1(
e.deptno(d.dname(d.loc /2<' 1'.L<D11 e 3EE12 M<3E D1.A2&'1E&S d
<E
e.D1.&E< R d.D1.&E< 3EE12 M<3E SALA2AD1 <E e.SAL +1&B11E
SALA2AD1.L<SAL AED
SALA2AD1.H3SAL L1/& <H&12 M<3E 1'.L<D11 m <E e.'A2 R
m.1'.E< <2D12 +D e.deptno
A<
.se t"e ='T: R)C2M&'L) option
&he B3&H 217<'.3L1 clause is helpful when the parameters supplied to the procedure will
not be typical( and when a new e8ecution plan should not be cached or stored in memory.
:a+ ).e sp=recompile s9stem stored procedEre forces a recompile
of a stored procedEre t.e /eDt time it is eDecEted. For eDample:
eDec sp=recompile M9)aFle
:F+ ;reate a stored procedEre specif9i/g (I)* &E;'M2ILE optio/.
If (I)* &E;'M2ILE is specified SLL Server does /ot cac.e a pla/
for t.is stored procedEreI t.e stored procedEre is recompiled
eac. time it is eDecEted. 5se t.e (I)* &E;'M2ILE optio/ 6.e/
stored procedEres taGe parameters 6.ose valEes differ 6idel9
Fet6ee/ eDecEtio/s of t.e stored procedEre, resElti/g i/
differe/t eDecEtio/ pla/s to Fe created eac. time.
*ere is .o6 9oE ca/ create a store procedEre Esi/g &E;'M2ILE
optio/:
;&EA)E 2&';E45&E Esp=M92rocedEre (I)* &E;'M2ILE
AS
Select SampleName, Sample4esc From Sample)aFle
%'
)c* Dou can force the stored procedure to be recompiled by specifying the B3&H 217<'.3L1
option when you e8ecute the stored procedure. Hse this option only if the parameter you are
supplying is atypical or if the data has significantly changed since the stored procedure was
created. /or e8ample,
E#E; Esp=M92rocedEre (I)* &E;'M2ILE
.se t"e ='T: )NCR7&T'2N option
&he B3&H 1E72D.&3<E clause obfuscates the te8t of a stored procedure. &his e8ample
creates an obfuscated procedure( uses the sp%"elptext system stored procedure to get
information on that obfuscated procedure( and then attempts to get information on that procedure
directly from the syscomments table.
Ese Mideo&e/talS9stem
go
3/ 1@3S&S )S1L17& name /2<' sysob5ects
BH121 name R N'y.rocedure"N AED type R N.N*
D2<. .2<71DH21 'y.rocedure"
A<
7reate procedure 'y.rocedure"
AS
Select Q from %ideo
Ao
e8ec sp6helpte8t 'y.rocedure"
go
7777777777777777777777777P
use %ideo2entalSystem
go
3/ 1@3S&S )S1L17& name /2<' sysob5ects
BH121 name R N'y.rocedure"N AED type R N.N*
D2<. .2<71DH21 'y.rocedure"
A<
7reate procedure 'y.rocedure" B3&H 1E72D.&3<E
AS
Select Q from %ideo
Ao
e8ec sp6helpte8t 'y.rocedure"
go
777777777777777777777P
+1A3E
Declare Va int R 0!
.rint Va
1nd
Tri$$ers
3ntroduction to &riggers
A trigger is an event handler which will be
automatically called and invoked as soon as the event
with which it is associated occurs.
&here are types of triggers,
/<2OA/&12 &riggers
3ES&1AD </ &riggers
D'L &riggers
A D'L trigger is a procedure that acts as a result of a data manipulation language )D'L* event
occurring on a table. &his means that the trigger must be created in connection to a table of a
non-system database.
A/&12O/<2 3ES12& &riggers ,
An insert trigger is a D'L trigger that acts when a new record is added to its intended table.
Such a trigger uses the 'NS)RT keywork. &he primary formula to create an 'NS)RT D'L
trigger on a table is,
;&EA)E )&I%%E& TriggerName
'N TableName
AF)E&VF'& INSE&)V524A)EV4ELE)E
AS
TriggerCode
3n our formula( we assume that the trigger will apply when a record has been added to the table.
&herefore( you use either the FT)R 'NS)RT or the F2R 'NS)RT e8pression.
&o start the SQL code that constitutes the trigger( write S( and then write your code.
After creating an 'NS)RT trigger( at the right time )when its intended event fires*( it will be
e8ecuted. Bhen this happens( the database engine automatically and internally creates a
temporary table named inserted. &his table holds a copy of the records that were created. Dou
can access those records if necessary.
use northwindP
go
7reate table 'y+ooks)+ookid int primary key(
+ook&itle nvarchar)0!!*(
+ookAuthor nvarchar)0!!*(
+ook.rice decimal*P
go
721A&1 &A+L1 Database<perations )
D+<peration3D int identity)0(0* E<& EHLL(
<b5ect&ype nchar)!*(
<b5ectEame nvarchar)C!*(
.erformed+y nvarchar)"!*(
Action.erformed nvarchar)"!*(
&ime.erformed datetime(
7<ES&2A3E& .>6D+<perations .23'A2D >1D)D+<peration3D*
*P
A<
721A&1 &23AA12 2ecord3nsertion
<E 'y+ooks
A/&12 3ES12&
AS
+1A3E
3ES12& 3E&< Database<perations
%ALH1S)EN&ableN( EN'y+ooksN( SHS126SEA'1)*(
EN7reated a new recordN( A1&DA&1)**
1ED
A<
select Q from databaseoperationsP
go
insert into 'y+ooks values)0(N.rogramming through 7N(
N%enugopalN(C"!*P
go
)0 row)s* affected*
)0 row)s* affected*
select Q from mybooksP
go
select Q from databaseoperationsP
go
A/&12O/<2 H.DA&1 &riggers ,
3nstead of record insertion time( a D'L trigger can act when a record has been
updated on a table. &o support this operation( you can use the following formula,
;&EA)E )&I%%E& TriggerName
'N TableName
AF)E&VF'& 524A)E
AS
TriggerCode
&he new keyword in this formula is .&DT). &his indicates that the D'L trigger will act when
the record has been updated. 1verything else is as described for the 'NS)RT operator.
2emember to use either FT)R .&DT) or F2R .&DT).
721A&1 &23AA12 2ecordHpdate
<E 'y+ooks
A/&12 H.DA&1
AS
+1A3E
3ES12& 3E&< Database<perations
%ALH1S)EN&ableN( EN'y+ooksN( SHS126SEA'1)*(
EN7hanged an e8isting book recordN( A1&DA&1)**
1ED
A<
update 'y+ooks set +ooktitleRNLearn 7N( +ookauthorRN%imalaN where
+ook3d R 0P
go
)0 row)s* affected*
)0 row)s* affected*
select Q from mybooksP
go
select Q from databaseoperationsP
go
A/&12O/<2 D1L1&1 &riggers
Bhen a record has been removed from a table( you can apply a D'L trigger in
response. &o make it possible( you can use the following formula,
;&EA)E )&I%%E& TriggerName
'N TableName
AF)E&VF'& 4ELE)E
AS
TriggerCode
&his time( the formula uses the D)L)T) operator as in FT)R D)L)T) or F2R D)L)T).
&he other factors follow the same description we saw for the 'NS)RT operator.
Bhen a D)L)T) trigger has acted on a table( the database engine creates a special temporary
table named deleted. &his table holds a copy of the records that were deleted. 1ventually( if
necessary( you can access this table to find out about those records.
721A&1 &23AA12 2ecordDeletion
<E 'y+ooks
A/&12 D1L1&1
AS
+1A3E
3ES12& 3E&< Database<perations
%ALH1S)EN&ableN( EN'y+ooksN( SHS126SEA'1)*(
ENDeleted a bookN( A1&DA&1)**
1ED
A<
delete from mybooks where bookidR0
go
&rigger 'anagement
A trigger is a database ob5ect. As such( it has a name. 3t can be modified. 3t can also
be deleted.
'odifying a &rigger
3f the behavior of a trigger is not appropriate( you can change it. &he formula to
modify a trigger is,
AL)E& )&I%%E& schema$name.trigger$name
'N schema$name.table$name
AF)E& , 524A)EW
AS
statement
Deleting a &rigger
3f you do not need a trigger anymore( you can remove it from a table. &he formula
to do this is,
4&'2 )&I%%E& TriggerName
After the DR2& TR'--)R e8pression( enter the name )of the trigger*.
7haracteristics of D'L &riggers
Although we created only one trigger for a table so far( you can go farther than
that,
Dou can create many D'L triggers )using different names( of course* that perform the
same action on a table. &his means that you can create many 'NS)RT triggers )or many
.&DT) triggers or many D)L)T) triggers* that act on the same table and that target
the same action
Dou can create different triggers that act on a table
D'L &riggers and 7onstraints
3f you create a D'L trigger that must act against that table( if the nullity rule is
violated( the trigger will not run.
3f a D'L trigger is supposed to act on the table( if this rule is not respected( the
trigger would fail.
A D'L trigger can be created to perform a check constraint on more than one
table. &his provides its advantage over the normal check constraint.
Bhen a D'L trigger runs( if a referential rule is violated( the trigger( which also
checks the referential integrity( fails.
3nstead of D'L &riggers
/rom what we have seen so far( when a user opens a table or a view to perform
data entry( when a new record has been created( the table or view fires an event.
Be saw that( using a D'L trigger( you can make a notification. /or e8ample you
can fill out a log to keep track of the changes. +y default( when a record is
submitted( it gets saved. 3n some cases( when a user has opened a table and tried to
make a change( such as adding a new record( editing an e8isting record( or deleting
a record( instead of accepting the change( you can dismiss it. Dou can then use a
D'L trigger to make a note. &his is the basis of another category of D'L triggers,
an _instead of_ trigger.
Bhile an FT)ROF2R trigger acts on a table after the action has occurred( you may want to do
something before the event fires. /or e8ample( you may want to prevent the user from adding a
new record on a tale( or from changing an e8isting record( or from deleting a record. <f course( it
is better to take care of this before the action is performed. <ne way you can do this is by
creating an _instead of_ trigger.
721A&1 DA&A+AS1 Small+usinessP
A<
HS1 Small+usinessP
A<
721A&1 &A+L1 7ustomers
)
7ustomer3D int identity)0( 0* primary key not null(
AccountEumber nchar)0!*(
/ullEame nvarchar)"!*
*P
A<
721A&1 &A+L1 Database<perations )
1mployeeEame nvarchar)"!*(
Action.erformed nvarchar)"!*(
&ime.erformed time
*P
A<
7reating an 3ES&1AD </ &rigger
Bhile an FT)R trigger can be applied to a table only( an _instead of_ trigger can
be associated with either a table or a view. &herefore( to create an _instead of_
trigger( you use the following formula,
;&EA)E )&I%%E& TriggerName
'N TableOr"ie%Name
INS)EA4 'F INSE&)V524A)EV4ELE)E
AS
TriggerCode
Dou start with the CR)T) TR'--)R e8pression followed by a name for the trigger. After the
name of the trigger( type 2N followed by the name of either a table or a view on which the
trigger will act.
/rom our review of the FT)R trigger( the new e8pression here is 'NST)D 2F. &his
e8pression is followed by the type of operation to perform,
3f you want to catch the creation of a new record( use the 'NS)RT operator
3f you want to catch the editing operation of an e8isting record( use the .&DT)
operator
3f you want to catch the removal of a record( use the D)L)T) operator
&o start the triggering code( type S and write the desired code.
3f you use the 'NST)D 2F e8pression( the trigger starts when the table or view is opened but
before a change has taken place. &he difference with the FT)R trigger is that( this time( you
can perform some action)s* before the change is made on the table or view. &his also implies
that( if the code of the trigger is to create a new record( at this time( the record doest not yet e8ist(
which means you cannot catch that record. At this time also( you can prevent the record from
being created )since it has not yet been created anyway*. /or e8ample( the following code will
not accept that a new record be added to the table,
HS1 Small+usinessP
A<
721A&1 &23AA12 7reate7ustomer
<E 7ustomers
3ES&1AD </ 3ES12&
AS
+1A3E
3ES12& 3E&< Database<perations
%ALH1S)SHS126SEA'1)*(
ENAttempt to create new recordN( A1&DA&1)**
1ED
A<
3f you want to get a copy of the record that was affected by the event( you can
access it from the inserted )for an 'NS)RT or .&DT) trigger* or from the
deleted )for a D)L)T)* trigger. Here is an e8ample,
HS1 Small+usinessP
A<
D2<. &23AA12 7reate7ustomerP
A<
721A&1 &23AA12 7reate7ustomer
<E 7ustomers
3ES&1AD </ 3ES12&
AS
+1A3E
3ES12& 3E&< 7ustomers
S1L17& AccountEumber( /ullEame /2<' inserted
1ED
A<
721A&1 &23AA12 Attempted2ecordHpdate
<E 7ustomers
3ES&1AD </ H.DA&1
AS
+1A3E
3ES12& 3E&< Database<perations
%ALH1S)SHS126SEA'1)*(
ENAttempted to change customer informationN(
A1&DA&1)**
1ED
A<
7haracteristics of 3ES&1AD </ &riggers
An FT)ROF2R and an 'NST)D 2F triggers have many differences. /or
e8ample,
3f a table has a relationship to another table and the referential integrity
on that relationship is marked with either 2N D)L)T) or 2N .&DT)(
an 'NST)D 2F .&DT) or an 'NST)D 2F D)L)T) trigger cannot
act on that table
Dou can create only one type of 'NST)D 2F trigger for each table.
/or e8ample( a table cannot have more than one 'NST)D 2F 'NS)RT
trigger
DDL &riggers
A DDL trigger is a trigger that acts when a certain type of
DDL event occurs. &hese include the creation( modification(
or removal of any system ob5ect like table but not its records. &his is the primary
difference with a D'L trigger which fires when a record is
added or modified.
A DDL trigger gives you the opportunity to do some administrative work in
response to the event. /or e8ample( you can get a notification(
or notify someone else using an automatically generated email(
that an ob5ect )and what ob5ect* has been created.
<r you can use a DDL trigger to discard the operation.
7reating a DDL &rigger
Dou create a DDL trigger using code. &he basic formula is,
;&EA)E )&I%%E& )riggerName
'N 4A)A,ASEVALL SE&ME&
F'&VAF)E& !hatEvent
AS
TriggerCode
Dou start a DDL trigger with the CR)T) TR'--)R e8pression followed by a name for the
new trigger. &he name follows the same rules we have applied to ob5ects so far. After the name
of the trigger( type the 2N keyword,
3f you want the trigger to act on the current database( type DTBS). Bhen the
intended event occurs on the current database( the trigger will e8ecute
3f you want the trigger to act on the server( follow the 2N operator with LL S)R?)R.
3n this case( when the intended event occurs on any part of the server( the trigger e8ecutes
After specifying the ob5ect )the whole server or only the current database* on which the trigger
will act( type either F2R or FT)R. &his is followed by the event against which the trigger will
act. As mentioned already( the events are DDL commands. &o specify the event( use the formula
of the command with the words separated by an underscore. /or e8ample( if you want the trigger
to act when a CR)T) TBL) command is e8ecuted( specify the event as CR)T)%TBL).
After specifying the event that will fire( type S followed by the normal code of the trigger.
Here is an e8ample that makes a note and adds it to a table when a new table has been created,
HS1 Small+usinessP
A<
721A&1 &23AA12 LogEew&able7reation
<E DA&A+AS1
/<2 721A&16&A+L1
AS
+1A3E
3ES12& 3E&< Database<perations
%ALH1S)SHS126SEA'1)*(
ENA new table was createdN( A1&DA&1)**
1ED
A<
Bhenever a new table is created in the current database( the trigger runs( gets the
name of the user who created the table( the date and time the table was created( and
a small message. &hese pieces of information are then stored in a log table.
As mentioned for D'L triggers( you manage DDL triggers by modifying or deleting them.
&hese are done using the same description we saw for D'L triggers.
DDL &rigger,
2eturns information about server or database events. 1%1E&DA&A)* is called
when an event notification fires( and the results are returned to the specified
service broker. 1%1E&DA&A)* can also be called by us from the body of a DDL
or logon trigger only.
HS1 18erciseP
A<
721A&1 &23AA12 safety
<E DA&A+AS1
/<2 721A&16&A+L1
AS
.23E& N721A&1 &A+L1 3ssued.N
S1L17& 1%1E&DA&A)*.value
)N)O1%1E&63ES&AE71O&SQL7ommandO7ommand&e8t*
T0UN(Nnvarchar)ma8*N*
2A3S122<2 )NEew tables cannot be created in this database.N( 0;( 0*
2<LL+A7>
P
A<
--&est the trigger.
721A&1 &A+L1 Eew&able )7olumn0 int*P
A<
--Drop the trigger.
D2<. &23AA12 safety
<E DA&A+AS1P
A<
.sin$ a lo$on tri$$er
&he following logon trigger e8ample denies an attempt to log in to SQL Server as a
member of the login6test login if there are already three user sessions running
under that login.
5SE masterI
%'
;&EA)E L'%IN logi/=test (I)* 2ASS('&4 = '0<*KCd.D:"DMJsdf' M5S)=;*AN%E,
;*E;<=E#2I&A)I'N = 'NI
%'
%&AN) MIE( SE&ME& S)A)E )' logi/=testI
%'
;&EA)E )&I%%E& co//ectio/=limit=trigger
'N ALL SE&ME& (I)* E#E;5)E AS 'logi/=test'
F'& L'%'N
AS
,E%IN
IF '&I%INAL=L'%IN:+= 'logi/=test' AN4
:SELE;) ;'5N):P+ F&'M s9s.dm=eDec=sessio/s
(*E&E is=Eser=process = ! AN4
origi/al=logi/=/ame = 'logi/=test'+ W 0
&'LL,A;<I
EN4I
More examples o# Tri$$ers
Hse &ri18amples
go
721A&1 &A+L1 .erson
)
SSE char)00* .23'A2D >1D(
Eame nvarchar)0!!*(
Address nvarchar)0!!*(
+irthdate datetime
*
go
7reate &able 3nsAudit)
2ow3d int 3dentity)0(0*(
SSE char)00*(
Date<f3ns datetime(
3ns+yBhom nvarchar)9!**
go
&riggers use two logical tables called the 3ES12&1D and the D1L1&1D table.
&hese tables are accessed only inside triggers and we cannot directly modify the
data in these tables. &hese tables hold the new and old rows of the data being
inserted or deleted.
3f we D1L1&1 a row ( a row will be created in the D1L1&1D table.
Similarly if we 3ES12& a row( a row is created in the 3ES12&1D table.
3f we update a record with an H.DA&1 statement( the 3ES12&1D table will
contain the updated row and a previous state of the row will be added to the
D1L1&1D table.
Eote, we cannot use a 721A&1 3ED1@ command on these tables.
721A&1 &23AA12 &rig3ns
<E .erson
A/&12 3ES12&
AS
insert into 3nsAudit)SSE(Date<f3ns(3ns+yBhom*
values))Select SSE /rom 3ES12&1D*(AetDate)*(SDS&1'6HS12*
Ao
insert into .erson)SSE(Eame(Address(+irthDate*
values)N000-00N(NMohnN(N"th Avenue LAN(N0J$!-!"-"N*
go
Select Q /rom .erson
go
Select Q from 3nsAudit
go
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
721A&1 &A+L1 'odifyAudit)
2ow3d int 3D1E&3&D)0(0* E<& EHLL(
<ldSSE char)00* EHLL(
<ldEame nvarchar)0!!* EHLL(
<ldAddress nvarchar)0!!* EHLL(
<ld+irthDate datetime EHLL
*
go
721A&1 &23AA12 &rigHpdate
<E .erson After Hpdate
AS
insert into 'odifyAudit
)<ldSSE(<ldEame(<ldAddress(<ld+irthDate*
values)
)Select SSE /rom D1L1&1D*(
)Select Eame /rom D1L1&1D*(
)Select TAddressU /rom D1L1&1D*(
)Select +irthDate /rom D1L1&1D**
Ao
---------------------
Hse %ideo2entalSystem
go
721A&1 &23AA12 &rigDelete
<E .erson After Delete
AS
2aiserror )Ncannot delete recordN(0!(0*
2oLL+A7>
Ao
Delete /rom .erson
go
Select Q from .erson
go
---------------------------
Disabling a D'L trigger on a table
&he following e8ample disables trigger uAddress that was created on table
Address.
HS1 AdventureBorksP
A<
D3SA+L1 &23AA12 dbo.&rigDelete <E dbo..erson
go
-----------------------------------
Disabling a DDL trigger
&he following e8ample creates a DDL trigger safety with database scope( and then
disables it.
3/ 1@3S&S )S1L17& Q /2<' sys.triggers
BH121 parent6class R ! AED name R NsafetyN*
D2<. &23AA12 safety <E DA&A+AS1P
A<
721A&1 &23AA12 safety
<E DA&A+AS1
/<2 D2<.6&A+L1( AL&126&A+L1
AS
.23E& NDou must disable &rigger _safety_ to drop or alter tables^N
2<LL+A7>P
A<
D3SA+L1 &23AA12 safety <E DA&A+AS1P
--------------------------------------
Disabling all triggers that were defined with the same scope
&he following e8ample disables all DDL and logon triggers that were created at the
server scope.
HS1 AdventureBorksP
A<
D3SA+L1 &rigger ALL <E ALL S12%12P
A<
-----------------------------
A. 1nabling a D'L trigger on a table
&he following e8ample disables trigger uAddress that was created on table
Address( and then enables it.
HS1 AdventureBorksP
A<
D3SA+L1 &23AA12 .erson.uAddress <E .erson.AddressP
A<
1EA+L1 &rigger .erson.uAddress <E .erson.AddressP
A<
+. 1nabling a DDL trigger
&he following e8ample creates a DDL trigger safety with database scope( and then
disables it.
3/ 1@3S&S )S1L17& Q /2<' sys.triggers
BH121 parent6class R ! AED name R NsafetyN*
D2<. &23AA12 safety <E DA&A+AS1P
A<
721A&1 &23AA12 safety
<E DA&A+AS1
/<2 D2<.6&A+L1( AL&126&A+L1
AS
.23E& NDou must disable &rigger _safety_ to drop or alter tables^N
2<LL+A7>P
A<
D3SA+L1 &23AA12 safety <E DA&A+AS1P
A<
1EA+L1 &23AA12 safety <E DA&A+AS1P
A<
7. 1nabling all triggers that were defined with the same scope
&he following e8ample enables all DDL and logon triggers that were created at the
server scope.
HS1 AdventureBorksP
A<
1EA+L1 &rigger ALL <E ALL S12%12P
A<
-----------------------------------
AL&123EA A &23AA12
HS1 AdventureBorksP
A<
3/ <+M17&63D)ENSales.bonus6reminderN( EN&2N* 3S E<& EHLL
D2<. &23AA12 Sales.bonus6reminderP
A<
721A&1 &23AA12 Sales.bonus6reminder
<E Sales.Sales.ersonQuotaHistory
B3&H 1E72D.&3<E
A/&12 3ES12&( H.DA&1
AS 2A3S122<2 )NEotify 7ompensationN( 0;( 0!*P
A<
-- Eow( change the trigger.
HS1 AdventureBorksP
A<
AL&12 &23AA12 Sales.bonus6reminder
<E Sales.Sales.ersonQuotaHistory
A/&12 3ES12&
AS 2A3S122<2 )NEotify 7ompensationN( 0;( 0!*P
A<
------------------------------------------
3ES&1AD </ &23AA12S )2evisited*
&he primary advantage of 3ES&1AD </ triggers is that they enable views to
support updates which are not updatable by default. A view based on multiple base
tables must use an 3ES&1AD </ trigger to support inserts( updates( and deletes
that reference data in more than one table. Another advantage of 3ES&1AD </
triggers is that they enable you to code logic that can re5ect parts of a batch while
letting other parts of a batch to succeed.
An 3ES&1AD </ trigger can take actions such as,
3gnoring parts of a batch.
Eot processing a part of a batch and logging the problem rows.
&aking an alternative action when an error condition is encountered.
3n the following se4uence of &ransact-SQL statements( an 3ES&1AD </ trigger
updates two base tables from a view. Additionally( the following approaches to
handling errors are shown,
Duplicate inserts to the .erson table are ignored( and the information from the
insert is logged in the .ersonDuplicates table.
3nserts of duplicates to the 1mployee&able are turned into an H.DA&1
statement that retrieves the current information into the 1mployee&able without
generating a duplicate key violation.
&he &ransact-SQL statements create two base tables( a view( a table to record
errors( and the 3ES&1AD </ trigger on the view. &he following tables separate
personal and business data and are the base tables for the view.
721A&1 &A+L1 .erson
)
SSE char)00* .23'A2D >1D(
Eame nvarchar)0!!*(
Address nvarchar)0!!*(
+irthdate datetime
*
721A&1 &A+L1 1mployee&able
)
1mployee3D int .23'A2D >1D(
SSE char)00* HE3QH1(
Department nvarchar)0!*(
Salary money(
7<ES&2A3E& />1mp.er /<213AE >1D )SSE*
21/121E71S .erson )SSE*
*
&he following view reports all relevant data from the two tables for a person.
721A&1 %31B 1mployee AS
S1L17& ..SSE as SSE( Eame( Address(
+irthdate( 1mployee3D( Department( Salary
/2<' .erson .( 1mployee&able 1
BH121 ..SSE R 1.SSE
Be can record attempts to insert rows with duplicate social security numbers. &he
.ersonDuplicates table logs the inserted values( the name of the user who tried the
insert( and the time of the insert.
721A&1 &A+L1 .ersonDuplicates
)
SSE char)00*(
Eame nvarchar)0!!*(
Address nvarchar)0!!*(
+irthdate datetime(
3nsertSEA'1 nchar)0!!*(
Bhen3nserted datetime
*
&he 3ES&1AD </ trigger inserts rows into multiple base tables from a single
view. Attempts to insert rows with duplicate SSE are recorded in the
.ersonDuplicates table. Duplicate rows in the 1mployee&able are changed to
update statements.
----------------------------------------------
----------------------------------------------
721A&1 &23AA12 3<6&rig63ES61mployee
<E 1mployee
3ES&1AD </ 3ES12&
AS
+1A3E
S1& E<7<HE& <E
-- 7heck for duplicate .erson. 3f there is no duplicate( do an insert.
3/ )E<& 1@3S&S )S1L17& ..SSE
/2<' .erson .( inserted 3
BH121 ..SSE R 3.SSE**
3ES12& 3E&< .erson
S1L17& SSE(Eame(Address(+irthdate
/2<' inserted
1LS1
-- Log an attempt to insert duplicate .erson row in .ersonDuplicates table.
3ES12& 3E&< .ersonDuplicates
S1L17& SSE(Eame(Address(+irthdate(SHS126SEA'1)*(A1&DA&1)*
/2<' inserted
-- 7heck for duplicate 1mployee. 3f there is no duplicate( do an 3ES12&.
3/ )E<& 1@3S&S )S1L17& 1.SSE
/2<' 1mployee&able 1( inserted
BH121 1.SSE R inserted.SSE**
3ES12& 3E&< 1mployee&able
S1L17& 1mployee3D(SSE( Department( Salary
/2<' inserted
1LS1
--3f there is a duplicate( change to H.DA&1 so that there will not
--be a duplicate key violation error.
H.DA&1 1mployee&able
S1& 1mployee3D R 3.1mployee3D(
Department R 3.Department(
Salary R 3.Salary
/2<' 1mployee&able 1( inserted 3
BH121 1.SSE R 3.SSE
1ED
----------------------------------------------------
HS12 D1/3E1D /HE7&3<ES
Bith SQL Server !!!( 'icrosoft has introduced the concept of
Hser-Defined /unctions that allow us to define our own &-SQL
functions that can accept =ero or more parameters and return a single
scalar data value or a table data type.
="at 8ind o# .ser4De#ined Functions can ' CreateC
&here are three types of Hser-Defined functions in SQL Server and they are
Scalar(
3nline &able-%alued and
'ulti-statement &able-valued.
:o* to create and use a Scalar .ser4De#ined FunctionC
A Scalar user-defined function returns one of the scalar data types.
&e8t( nte8t( image and timestamp data types are not supported.
&hese are the type of user-defined functions that most developers are used to in
other programming languages. Be can pass ! to many parameters and we get a
return value.
+elow is an e8ample,
Hse 3ndian1nterprise
go
7reate &able 7ustomers)7ust3d int primary key(
7ustEame nvarchar)9!*(
7ountry nvarchar)9!**
go
3nsert into 7ustomers values)0!!!(NSmithN(NArgentinaN*
go
3nsert into 7ustomers values)0!!0(N+lakeN(NArgentinaN*
go
3nsert into 7ustomers values)0!!(NLaraN(N7anadaN*
go
3nsert into 7ustomers values)0!!9(N2onaldN(N+elgiumN*
go
3nsert into 7ustomers values)0!!C(N'artinN(N/inlandN*
go
3nsert into 7ustomers values)0!!"(N>ingN(N/ranceN*
go
3nsert into 7ustomers values)0!!;(N<bamaN(NHSAN*
go
3nsert into 7ustomers values)0!!:(N.eleN(N+ra=ilN*
go
721A&1 /HE7&3<E which7ontinent
)V7ountry nvarchar)0"**
21&H2ES varchar)9!*
AS
+1A3E
declare V2eturn varchar)9!*
select Vreturn R case V7ountry
when NArgentinaN then NSouth AmericaN
when N+elgiumN then N1uropeN
when N+ra=ilN then NSouth AmericaN
when N7anadaN then NEorth AmericaN
when NDenmarkN then N1uropeN
when N/inlandN then N1uropeN
when N/ranceN then N1uropeN
else NHnknownN
end
return Vreturn
end
+ecause this function returns a scalar value of a varchar)9!* this function could be
used anywhere a varchar)9!* e8pression is allowed such as a computed column in
a table( view( a &-SQL select list item.
print dbo.which7ontinent)NDenmarkN*
create table test
)7ountry varchar)0"*(
7ontinent as )dbo.Bhich7ontinent)7ountry***
insert into test )country*
values )NHSAN*
select Q from test
insert into test )country*
values )NArgentinaN*
select Q from test
:o* to create and use an
'nline Table4?alued .ser4De#ined FunctionC
An 3nline &able-%alued user-defined function returns a table data type
and is an e8ceptional alternative to a view as the user-defined function
can pass parameters into a &-SQL select command and in
essence provide us with a parameteri=ed( non-updateable view
of the underlying tables.
Hse 3ndian1nterprise
go
721A&1 /HE7&3<E 7ustomers+y7ontinent
)V7ontinent varchar)9!**
21&H2ES &A+L1
AS
21&H2E
S1L17& dbo.Bhich7ontinent)7ustomers.7ountry* as continent(
customers.Q
/2<' customers
BH121 dbo.Bhich7ontinent)7ustomers.7ountry* R V7ontinent
A<
S1L17& Q from 7ustomersby7ontinent)NEorth AmericaN*
S1L17& Q from 7ustomers+y7ontinent)NSouth AmericaN*
S1L17& Q from customersby7ontinent)NHnknownN*

:o* to create and use a
Multi4statement
Table4?alued .ser4De#ined FunctionC
A 'ulti-Statement &able-%alued user-defined function returns a table
and is also an e8ceptional alternative to a view as the function can
support multiple &-SQL statements to build the final result( where as a view
is limited to a single S1L17& statement. Bithin the create function
command we must define the table structure that is being returned.
Hse 3ndian1nterprise
go
721A&1 /HE7&3<E dbo.7ustomersby7ountry ) V7ountry varchar)0"* *
21&H2ES
V7ustomersby7ountry&ab table )
7ust3D int (
7ustEame nvarchar )9!*(
7ountry nvarchar)9!*
*
AS
+1A3E
3ES12& 3E&< V7ustomers+y7ountry&ab
S1L17& 7ust3D(
7ustEame(
7ountry

/2<' T7ustomersU
BH121 country R V7ountry


3/))S1L17& 7<HE&)Q* /2<' Vcustomersby7ountry&ab*R!*
+egin
3ES12& 3E&< V7ustomers+y7ountry&ab )
7ust3d(
7ustEame(
7ountry
*
%ALH1S )null(NEo 7ustomer /oundN(NHnknownN*
1nd
21&H2E
1ED
A<
S1L17& Q /2<' dbo.customersbycountry)NHSAN*
S1L17& Q /2<' dbo.customersbycountry)N7AEADAN*
S1L17& Q /2<' dbo.customersbycountry)NAD/N*
.sin$ Synonyms in SQL Server +EEJ
3f youNve been developing with SQL Server for any length of time( youNre undoubtedly used to
referring to ob5ects with four-part identifiers,
>>>server.?>dataFase?.?>sc.ema=/ame?.?oFHect=/ame
As the s4uare brackets show( different parts of this synta8 can be omitted( as long as you supply
enough to unambiguously identify what youNre talking about. /or e8ample( all of these might
refer to the same ob5ect,
Server!.Adve/tEre(orGs.2rodEctio/.2rodEct;ategor9
Adve/tEre(orGs.2rodEctio/.2rodEct;ategor9
Adve/tEre(orGs..2rodEct;ategor9
2rodEct;ategor9
/or the most part( you can get by with three-part names( omitting the server name - unless youNre
dealing with ob5ects on a linked server. +y default( the conte8t of all ob5ects is the local database
where your SQL statements are e8ecuting. +ut sometimes( to be precise( you have no choice but
to use the four-part name )otherwise known as a fully-qualified name. <r do youd 3n SQL Server
!!"( the story changes a bit.
)nter t"e Synonym
SQL Server !!" introduces the concept of a synonym, a single-part name
that can replace a two-( three-( or four-part name in many SQL statements.
Hsing synonyms lets you cut down on typing )always a welcome
advance for developers^* and can also provide an abstraction layer
to protect you against changes in underlying ob5ects.
&o understand how this works( letNs start with the synta8
for creating synonyms. Eot surprisingly( this is the ;&EA)E SJN'NJM statement,
;&EA)E SJN'NJM >schema$name.?synonym$name F'& ob&ect$name
Here ob!ect_name is the name of a SQL Server ob5ect )specified fully enough to identify the
ob5ect* and synonym_name is the new name that you want to assign to it. 3f you donNt specify a
schema for the synonym( then SQL Server uses the current userNs default schema. &he ob5ect
doesnNt need to e8ist when you create the synonym( because synonyms are late bound, SQL
Server only checks the base ob5ect when you actually use the synonym.
/or e8ample( in the AdventureBorks sample database you can create a synonym this way,
;&EA)E SJN'NJM 2rod;at
F'& Adve/tEre(orGs.2rodEctio/.2rodEct;ategor9
Having done this( you can now proceed to use the synonym in SQL statements. /or e8ample,
SELE;) P F&'M 2rod;at
Bhen youNre done with a synonym(
you can get rid of it using the 4&'2 SJN'NJM statement(
which has the synta8 you e8pect,
4&'2 SJN'NJM >schema$name.?synonym$name
Fe* o# t"e Details
Eaturally( there are some limits to synonym use. /or starters( you canNt create a synonym for 5ust
anything. SQL Server !!" contains more ob5ects than ever before(
but synonyms are limited to a core set of the most useful ob5ects,
&ables
%iews
Stored procedures
7L2 stored procedures
7L2 functions
2eplication filter procedures
18tended stored procedures
SQL scalar( table-valued( and inline table-valued functions
&here are also limits on where we can use synonyms.
Aenerally speaking( we can use a synonym in these &-SQL statements,
SELE;)
sEF7selects
524A)E
INSE&)
4ELE)E
E#E;5)E
3f you think about it( that second list shouldnNt be too surprising, it encompasses the most
common statements where youNd use the ob5ects from the first list. Eote that you cannot
reference a synonym in a DDL statement. 3f you want to use AL)E& )A,LE to change
something about the 2rodEct;ategor9 table( for e8ample( you need to work with the base
table( not with the 2rod;at synonym.
&o create a synonym( you need ;&EA)E SJN'NJM permission.
After a synonym has been created( it has its own associated %&AN)( 4ENJ(
and &EM'<E permissions.
Synonyms as an bstraction Layer
+esides saving you typing( synonyms can also serve as an abstraction layer over unstable or
fre4uently updated portions of your database. &hatNs because the bindings between a synonym
and its base ob5ect are only checked at runtime( not at design time.
&o illustrate this( e8amine what happens if you redefine the 2rod;at synonym,
4&'2 SJN'NJM 2rod;at
;&EA)E SJN'NJM 2rod;at
F'& Adve/tEre(orGs.2rodEctio/.2rodEct;ategor9
SELE;) P F&'M 2rod;at
4&'2 SJN'NJM 2rod;at
;&EA)E SJN'NJM 2rod;at
F'& Adve/tEre(orGs.2rodEctio/.;EltEre
SELE;) P F&'M 2rod;at
Eote that you need to use 4&'2 and ;&EA)E whenever you want to change a synonymP thereNs
no AL)E& SJN'NJM statement. /igure shows the result of running this batch of statements.
Eote the very different results from the second e8ecution of SELE;) P F&'M 2rod;at(
because the synonym was redefined to refer to a different table in the interim.
Dou can take advantage of this behavior in your own applications. /or e8ample( suppose youNve
got an application that needs to analy=e customer data from a variety of different databases.
2ather than linking and unlinking the base tables from the individual databases( or writing
comple8 SQL that selects the tables to analy=e( you could use synonyms. Define a synonym such
as Data&able to refer to the four-part name of the data that you want to work with( and redefine it
whenever you want to switch source data.
<f course( this late binding is a two-edged sword. +ecause SQL Server doesnNt track whether a
synonym points to anything( it also doesnNt do any sort of schema binding. 3f you drop a
synonym thatNs used in another statement( you wonNt find out that anything is wrong until you try
to run that statement.
File .nder KNice to :aveK
7ould you develop your ne8t SQL Server application without synonymsd Sure. &hey donNt bring
anything fundamentally new to the tableP you could always use fully-4ualified names anywhere
that you could use a synonym. +ut sometimes itNs nice to have these little amenities in the
product( 5ust because they make for less typing and an easier development e8perience. .erhaps
synonyms will only save you ten minutes over the course of an entire application( but still( those
little ten-minute savings add up. LetNs hope 'icrosoft keeps delivering nice little improvements
like this along with the big headline features.
Table 'ndexes nd Table &artitionin$
Like a book( a table or a view can use the mechanism provided by an inde8. 3n a table or a view(
an inde8 is a column )or many columns* that can be used to locate records and take a specific
action based on some rule reinforced on that )those* column)s*.
7reating an 3nde8 Bith SQL
&o create an inde8 in SQL( the basic formula to follow is,
;&EA)E IN4E# 'ndexName 'N Table("ie%:Column:s++
3/ 1@3S&S )
S1L17& name
/2<' sys.databases
BH121 name R EN18erciseN
*
D2<. DA&A+AS1 18ercise
A<
721A&1 DA&A+AS1 18ercise
A<
HS1 18erciseP
A<
721A&1 &A+L1 1mployees
)
1mployeeEumber int E<& EHLL(
LastEame nvarchar)!* E<& EHLL(
/irstEame nvarchar)!*(
Hsername nchar)$* E<& EHLL(
DateHired date EHLL(
HourlySalary money
*P
A<
INSE&) IN)' Emplo9ees
MAL5ES:C-1A", N'Kames', N'*aa/s', N'H.aa/s', N'!@@A7!"7-$', -A."-+,
:0$A11, N'%ertrEde', N'Mo/a9', N'gmo/a9', N'-""C7"C7--', !1.0C+,
:-1@"1, N'2.ilomX/e', N'%Eillo/', N'pgEillo/', N'-""!7!"7!C', !A."$+,
:1A"1@, N'Eddie', N'Mo/soo/', N'emo/soo/', N'"AV!"V-""@', -C.--+,
:-$A"$, N'2eter', N'MEGoGo', N'pmEGoGo', N'"07!"7-""1', --.1A+,
:$A1"$, N';.ritia/', N'Alle/', N'calle/', N'"CV!CV!@@$', !C.1$+I
%'
721A&1 3ED1@ 3@61mployees
<E 1mployees)1mployeeEumber*P
A<
3f the inde8 will include more than one column( list them separated by commas.
Here is an e8ample,
721A&1 3ED1@ 3@61mployees
<E 1mployees)LastEame( Hsername*P
A<
Deleting an 3nde8
&he basic synta8 to delete an inde8 in &ransact-SQL is,
4&'2 IN4E# 'ndexName 'N TableNameI
HS1 18erciseP
A<
D2<. 3ED1@ 3@61mployees <E 1mployeesP
A<
7hecking the 18istence of an 3nde8es
HS1 18erciseP
A<
3/ 1@3S&S )S1L17& name /2<' sys.inde8es
BH121 name R EN3@61mployeesN*
D2<. 3ED1@ 3@61mployees
<E 1mployees
A<
721A&1 3ED1@ 3@61mployees
<E 1mployees)1mployeeEumber*P
A<
&he &ypes of 3nde8es
7lustered 3nde8es
3n our introduction( we saw that an inde8 is primarily created using one or more
columns from a designated table. &his means that( when it comes to using the
inde8( we would use the values stored in the column)s* that was )were* selected for
the inde8. Such an inde8 is referred to as clustered. &he columns that were made
part of an inde8 are referred to as keys.
HS1 18erciseP
A<
721A&1 7LHS&121D 3ED1@ 3@61mployees
<E 1mployees)LastEame*P
A<
Eon-clustered 3nde8
Bhile a clustered inde8 uses a sorted list of records of a table or view( another type
of inde8 can use a mechanism not based on the sorted records but on a bookmark.
&his is called a non-clustered inde8. As opposed to a clustered table that can
contain only one clustered inde8( you can create not only one( but as many as CJ
non-clustered inde8es.
&o create a non-clustered inde8 in SQL( use the following formula,
;&EA)E N'N;L5S)E&E4 IN4E# 'ndexName 'N Table("ie%:Column:s++
HS1 18erciseP
A<
721A&1 E<E7LHS&121D 3ED1@ E3@61mployees
<E 1mployees)LastEame( /irstEame*P
A<
3ntroduction to 3nde8 Hni4ueness
Bhen creating a table( we can create inde8 for it and let the inde8 apply a rule that
states that each record would be uni4ue. &o take care of this( we can apply a
uni4ueness rule on the inde8.
&o create a uni4ueness inde8 in SQL( apply the .N'Q.) keyword in the formula,
;&EA)E >5NIL5E? >;L5S)E&E4 T N'N;L5S)E&E4? IN4E# i/deD=/ame 'N
Table("ie%:Column:s++
HS1 18erciseP
A<
721A&1 HE3QH1 7LHS&121D 3ED1@ H3@61mployees
<E 1mployees)1mployeeEumber*P
A<
7annot create more than one clustered inde8 on table N1mployeesN. Drop the e8isting clustered inde8 N3@61mployeesN before creating another.
HS1 18erciseP
A<
D2<. 3ED1@ 3@61mployees <E 1mployees
Ao
721A&1 HE3QH1 7LHS&121D 3ED1@ H3@61mployees
<E 1mployees)1mployeeEumber*P
A<
&able and 3nde8 .artitioning
Data in your database may involve many records( in thousands or millions( so
much that at one time( it may become difficult to manage. <ne way you can deal
with this is to store the records of a table in different file groups. &his makes it
possible to store one section of records in one file group( another section in another
file group( possibly another section in another file group( and so on. As a result(
when it comes time to look for one or a few records among thousands or millions
of records( it would be easier to locate it or to locate them. <f course( the data still
belongs to one database and to the same table.
5SE masterI
%'
;&EA)E 4A)A,ASE &ealEstate0
'N 2&IMA&J
: NAME = N'&ealEstate2rimar9',
FILENAME = N';:\&eal Estate Mai/ &epositor9\&ealEstateMai/.mdf',
SIE = 1M,,
MA#SIE = !"M,,
FILE%&'()* = !M,+,
FILE%&'52 &ealEstate%roEp&ecords!
: NAME = N'&ealEstate&ecords!',
FILENAME = N';:\&eal Estate Mai/ &epositor9\&ealEstateFirst./df',
SIE = !M,,
MA#SIE = !"M,,
FILE%&'()* = !M,+,
FILE%&'52 &ealEstate%roEp&ecords-
: NAME = N'&ealEstate&ecords-',
FILENAME = N';:\&eal Estate Seco/dar9 &epositor9\&ealEstateSeco/d./df',
SIE = !M,,
MA#SIE = !"M,,
FILE%&'()* = !M,+,
FILE%&'52 &ealEstate%roEp&ecords0
: NAME = N'&ealEstate&ecords0',
FILENAME = N';:\&eal Estate ).ird &epositor9\&ealEstate).ird./df',
SIE = !M,,
MA#SIE = !"M,,
FILE%&'()* = !M,+
L'% 'N
: NAME = N'&ealEstate0Log',
FILENAME = N';:\&eal Estate Mai/ &epositor9\&ealEstateLogger.ldf',
SIE = !M,,
MA#SIE = !"M,,
FILE%&'()* = !M,+I
%'
.artitioning a &able
+efore partitioning a table( you must create the necessary file groups. &his can be
done when creating the database since it is at that time that you specify how the
database will be storedP that is( what files will hold the information of the database.
After creating the database and creating its file groups. +efore partitioning a table( you must
create a partition function and a partition scheme.
A .artition /unction
A partition function is used to define the ranges of records that will be stored in
what file group. &he SQL formula to create a partition function is,
;&EA)E 2A&)I)I'N F5N;)I'N )artitionFunctionName : )arameterType +
AS &AN%E > LEF) T &I%*) ?
F'& MAL5ES :Startange*, Startange+, Startange$n+
After closing the parenthesis( type S RN-)( which indicates that you are going
to specify the ranges of values. &his is followed by either L)FT or R'-:T. Bhen
the partition function will have been created and when the table itself will have
been created( when the database engine is asked to look for a record or a range of
records( it may have to sort the records. 3f you want it to sort the records from left
to right( use the L1/& keyword. 3f you want the records sorted from right to left(
use the 23AH& keyword.
&he S RN-) L)FT or S RN-) R'-:T e8pression is followed by F2R ?L.)S that
is followed by parentheses.
Bhen creating a partition function( you must provide a way for the database engine to get a
range of records. /or e8ample( you can use records from number 0 to number 0!!!( then another
range from 0!!0 to "!!!( and so on. <r you can specify that a range of records would go from
/ebruary 00th( !!! to Mune ;th( !!". &hen another range would go from Mune ;th !!" to
December 0Cth( !!;( and so on.
Dou specify the range in the parentheses that follow the F2R ?L.)S e8pression. &ype the
first value of the first range( followed by a comma( followed by the first value of the second
range( and so on.
5SE &ealEstate0I
%'
;&EA)E 2A&)I)I'N F5N;)I'N &ealEstateSegme/tatio/:i/t+
AS &AN%E LEF) F'& MAL5ES:!, !"+I
%'
A .artition Scheme
A partition scheme specifies the names of the file groups( in their order that will
store the ranges of records that were created in the partition function. &he formula
to create a partition scheme is,
;&EA)E 2A&)I)I'N S;*EME )artitionSchemeName
AS 2A&)I)I'N )artitionFunctionName
> ALL ? )' : S file=groEp=/ame T > 2&IMA&J ? U > ,.../ ? +
Dou start with the CR)T'2N &RT'T'2N SC:)M) e8pression do indication your
intention. &his is followed by a name. &he name follows the rules of ob5ects.
After the name of the partition scheme( type S &RT'T'2N followed by the name of the
partition function you should have previously created.
3f you are planning to use only one file group( after the name of the partition function( enter
LL( followed by parentheses( in which you will type .23'A2D.
3f you are planning to use different file groups( after the name of the partition function( enter T2(
followed by parentheses. Be saw that( in the parentheses of the F2R ?L.)S of the partition
function( you entered the starting value of the first range. 3n the parentheses of the &< keyword(
type the name of the file group that will hold the records of the first range of the partition
function. Be also saw how to specify the second range in the partition function. 3n the
parentheses of the &< clause( after the name of the first file group( type a comma followed by the
name of the file group that will hold the records of the second range.
5SE &ealEstate0I
%'
;&EA)E 2A&)I)I'N S;*EME &ealEstate4istriFEtio/Sc.eme
AS 2A&)I)I'N &ealEstateSegme/tatio/
)' :&ealEstate%roEp&ecords!, &ealEstate%roEp&ecords-,
&ealEstate%roEp&ecords0+I
%'
.artitioning a &able
After creating the partition scheme( you can create the table. &he formula to
specify a partition scheme when creating a table is,
;&EA)E )A,LE !hat !e -ave .earned So Far
:
!hat !e -ave .earned So Far
+ 'N )artitionSchemeName:ColumnName+
5SE &ealEstate0I
%'
;&EA)E )A,LE 2ropert9)9pes
:
2ropert9)9peI4 i/t ide/tit9:!,!+ N') N5LL,
2ropert9)9pe varc.ar:-"+,
;'NS)&AIN) 2<=2ropert9)9pes 2&IMA&J <EJ:2ropert9)9peI4+
+ 'N &ealEstate4istriFEtio/Sc.eme:2ropert9)9peI4+I
%'
;&EA)E )A,LE ;o/ditio/s
:
;o/ditio/I4 i/t ide/tit9:!,!+ N') N5LL,
;o/ditio/ varc.ar:-"+,
;'NS)&AIN) 2<=;o/ditio/s 2&IMA&J <EJ:;o/ditio/I4+
+ 'N &ealEstate4istriFEtio/Sc.eme:;o/ditio/I4+I
%'
;&EA)E )A,LE 2roperties
:
2ropert9I4 i/t ide/tit9:!,!+ N') N5LL,
2ropert9NEmFer c.ar:C+,
Address varc.ar:!""+,
;it9 varc.ar:$"+,
State c.ar:-+,
I2;ode varc.ar:!-+,
2ropert9)9peI4 i/t
;'NS)&AIN) F<=2ropert9)9pes
F'&EI%N <EJ &EFE&EN;ES 2ropert9)9pes:2ropert9)9peI4+,
;o/ditio/I4 i/t
;'NS)&AIN) F<=;o/ditio/s
F'&EI%N <EJ &EFE&EN;ES ;o/ditio/s:;o/ditio/I4+,
,edrooms smalli/t,
,at.rooms float,
Fi/is.ed,aseme/t Fit,
I/door%arage Fit,
Stories smalli/t,
Jear,Eilt smalli/t,
MarGetMalEe mo/e9,
;'NS)&AIN) 2<=2roperties 2&IMA&J <EJ:2ropert9I4+
+ 'N &ealEstate4istriFEtio/Sc.eme:2ropert9I4+I
%'
C.RS2RS
Processing Sequentially Through a Set of Records
Operations in a relational database act on a complete set of rows. The set of rows returned
by a SELECT statement consists of all the rows that satisfy the conditions in the WHEE
clause of the statement. This complete set of rows returned by the statement is !nown as
the result set. "pplications# especially interacti$e online applications# cannot always wor!
effecti$ely with the entire result set as a unit.
%f applications need a mechanism to wor! with one row or a small bloc! of rows at a time#
then Cursors are an e&tension to result sets that pro$ide that mechanism.
Using a Cursor
To define a cursor the 'ECL"E C(SO statement is used. Here is the basic format for the
simple cursor .
'ECL"E cursor_name C(SO
)O select_statement
The cursor_name is the name we want to associate with the cursor. The select_statement is
the *uery that will determine the rows that ma!e up the cursor.
Complete synta&+
%SO Synta&
4E;LA&E cErsor=/ame > INSENSI)IME ? > S;&'LL ? ;5&S'&
F'& select=stateme/t
> F'& S &EA4 'NLJ T 524A)E > 'F colEm/=/ame > ,.../ ? ? U ?
>I?
)ra/sact7SLL EDte/ded S9/taD
4E;LA&E cErsor=/ame ;5&S'& > L';AL T %L',AL ?
> F'&(A&4='NLJ T S;&'LL ?
> S)A)I; T <EJSE) T 4JNAMI; T FAS)=F'&(A&4 ?
> &EA4='NLJ T S;&'LL=L';<S T '2)IMIS)I; ?
> )J2E=(A&NIN% ?
F'& select=stateme/t
> F'& 524A)E > 'F colEm/=/ame > ,.../ ? ? ?
>I?
cursor_name , the name of the ser$er side cursor# must contain from - to -./ characters.
LOCAL , specifies that cursor can be a$ailable only in the batch# stored procedure#
or trigger in which the cursor was created. The LOC"L cursor will be implicitly
deallocated when the batch# stored procedure# or trigger terminates.
GLOBAL , specifies that cursor is global to the connection.
The 0LO1"L cursor will be implicitly deallocated at disconnect.
OR!AR"_O#L$ , specifies that cursor can only fetch data se*uentially
from the first to the last row. )ETCH 2E3T is the only fetch option supported.
STAT%C , specifies that cursor will use a temporary copy of the data instead
of base tables. This cursor does not allow modifications and modifications
made to base tables are not reflected in the data returned by fetches made
to this cursor.
&'$S'T , specifies that cursor uses the set of !eys that uni*uely identify
the cursor4s rows 5!eyset6# so that the membership and order of rows
in the cursor are fi&ed when the cursor is opened. SQL Ser$er uses a table
in tempdb to store !eyset. The 7E8SET cursor allows updates non!ey
$alues from being made through this cursor# but inserts made by other
users are not $isible. (pdates non!ey $alues made by other users are
$isible as the owner scrolls around the cursor# but updates !ey $alues
made by other users are not $isible. %f a row is deleted# an attempt to
fetch the row returns an 99)ETCH:ST"T(S of ,..
"$#A(%C , specifies that cursor reflects all data changes made to the
base tables as you scroll around the cursor. )ETCH "1SOL(TE
option is not supported with '82";%C cursor.
R'A" O#L$ , specifies that cursor cannot be updated.
select_statement , the standard select statement# cannot contain CO;<(TE# CO;<(TE 18
and %2TO !eywords.
UP"AT' )O column_name )*+++n,, , specifies that all cursor4s columns can be updated
5if O column_name )*+++n, is not specified6# or only the columns listed in the O
column_name )*+++n, list allow modifications.
'%))EE2T O<T%O2S )O )ETCH+
#'-T , the default cursor fetch option.
)ETCH 2E3T returns the ne&t row after the current row.
PR%OR , returns the prior row before the current row.
%RST , returns the first row in the cursor.
LAST , returns the last row in the cursor.
Cursor Process
&ransact-SQL cursors and A.3 cursors have different synta8( but the following general process is
used with all SQL Server cursors,
0. Associate a cursor with the result set of a &ransact-SQL statement( and define
characteristics of the cursor( such as whether the rows in the cursor can be updated.
. 18ecute the &ransact-SQL statement to populate the cursor.
9. 2etrieve the rows in the cursor we want to see. &he operation to retrieve one row or one
block of rows from a cursor is called a /1&7H. .erforming a series of fetches to retrieve
rows in either a forward or backward direction is called scrolling.
C. <ptionally( perform modification operations )update or delete* on the row at the current
position in the cursor.
". 7lose the cursor.
Cursor )unctions+
99)ETCH:ST"T(S returns the status of the last cursor
)ETCH statement issued against any cursor currently opened by
the connection.
Return value Description
! /1&7H statement was successful.
-0 /1&7H statement failed or the row was beyond the result set.
- 2ow fetched is missing.
99C(SO:OWS
eturns the number of *ualifying rows currently in the last cursor opened on the connection.
99C(SO:OWS can be called to determine that the number of the rows that *ualify for
a cursor are retrie$ed at the time 99C(SO:OWS is called.
C(SO:ST"T(S+
" scalar function that allows the caller of a stored procedure to determine whether or not
the procedure has returned a cursor and result set for a gi$en parameter.
declare 9Empno nchar5=6
declare V2owEum int
declare 1mpList cursor for
select top " 1mpno from 1mployee
<.1E 1mpList
/1&7H E1@& /2<' 1mpList
3E&< V1mpno
set V2owEum R !
BH3L1 VV/1&7H6S&A&HS R !
+1A3E
set V2owEum R V2owEum K 0
print cast)V2owEum as char)0** K N N K V1mpno
/1&7H E1@& /2<' 1mpList
3E&< V1mpno
1ED
7L<S1 1mpList
D1ALL<7A&1 1mpList

Here are the results that are generated from the print statement when % run it against my
2orthwind 'atabase.
- >?@A
. >BAA
? >=.-
B >=@@
= >@=B
Let4s loo! at the abo$e code in a little more detail.
We first declared a cursor called CEmpListC.
The CEmpListC cursor is populated using a SELECT statement that uses the
TO< clause to return only the top = employee no4s.
2e&t the cursor is opened.
Each record in the CEmpListC cursor is retrie$ed# one record at a time#
using the C)ETCH 2E3TC ne&t statement. The C)ETCH 2E3TC statement populates
the local $ariable 9Empno with the Empno of the current record being fetched.
The 99)ETCH:ST"T(S $ariable controls whether the WH%LE loop is e&ecuted.
99)ETCH:ST"T(S is set to Dero when a record is successfully retrie$ed from
the cursor CEmpListC.
%nside the WH%LE loop the 9ow2um $ariable is incremented by - for each record
processed. The calculated ow 2umber and 9Empno are then printed out.
Lastly# a C)ETCH 2E3TC statement is used to retrie$e the ne&t row before the ne&t cycle of
the WH%LE loop. This process continues one record at a time until all records in cursor
CEmpListC ha$e been processed.
"nother E&ample+
%n this e&ample# % chose the )"ST:)OW"' option to optimiDe performance because it
creates a forward only# read only cursor.
'ECL"E 9ETitle n$archar5?F6
D17LA21 Vpresent.rice decimal)"(*
D17LA21 Vnew.rice decimal)"(*
D17LA21 V'y7ursor 7H2S<2
S1& V'y7ursor R 7H2S<2 /AS&6/<2BA2D
/<2
Select %&itle(.rice
/rom %ideo
<.1E V'y7ursor
/1&7H E1@& /2<' V'y7ursor
3E&< V%&itle(Vpresent.rice
BH3L1 VV/1&7H6S&A&HS R !
+1A3E
if Vpresent.rice F 9
set Vnew.rice R Vpresent.rice K Vpresent.rice Q !.0!
else
set Vnew.rice R Vpresent.rice K Vpresent.rice Q !.!"
.23E& V%&itle K N - present price is N K cast)Vpresent.rice as nvarchar* K
N - new price is N K cast)Vnew.rice as nvarchar*
/1&7H E1@& /2<' V'y7ursor
3E&< V%&itle(Vpresent.rice
1ED
7L<S1 V'y7ursor
D1ALL<7A&1 V'y7ursor
A<
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,G
D17LA21 Vename nvarchar)!*
D17LA21 VpresentSal numeric
D17LA21 VnewSal numeric
D17LA21 V'y7ursor 7H2S<2
S1& V'y7ursor R 7H2S<2 /AS&6/<2BA2D
/<2
Select ename(sal
/rom 1mployee
<.1E V'y7ursor
/1&7H E1@& /2<' V'y7ursor
3E&< Vename(VpresentSal
BH3L1 VV/1&7H6S&A&HS R !
+1A3E
if VpresentSal F 9!!!
set VnewSal R VpresentSal K VpresentSal Q !.0!
else
set VnewSal R VpresentSal K VpresentSal Q !.!"
.23E& Vename K N N K cast)VpresentSal as nvarchar* K N N K cast)VnewSal as
nvarchar*
/1&7H E1@& /2<' V'y7ursor
3E&< Vename(VpresentSal
1ED
7L<S1 V'y7ursor
D1ALL<7A&1 V'y7ursor
A<
"nother e&ample+
'ECL"E 9Ename nchar5-=6
D17LA21 V2owEum int
D17LA21 1mpList S72<LL 7H2S<2
/<2 S1L17& 1name /2<' 1mployee
<.1E 1mpList
/1&7H LAS& /2<' 1mpList
3E&< V1name
S1& V2owEum R !
BH3L1 VV/1&7H6S&A&HS R !
+1A3E
S1& V2owEum R V2owEum K 0
.23E& cast)V2owEum as char)0** K N N K V1name
/1&7H .23<2 /2<' 1mpList
3E&< V1name
1ED
7L<S1 1mpList
D1ALL<7A&1 1mpList
"nother E&ample+
This e&ample declares a cursor and uses SELECT to display the
$alue of 99C(SO:OWS. The setting has a $alue of F before
the cursor is opened# and a $alue of ,- to indicate that the cursor
!eyset is populated asynchronously.
SELECT 99C(SO:OWS
D17LA21 videos6cursor 7H2S<2 /<2
S1L17& %&itle /2<' video
<.1E videos6cursor
/1&7H E1@& /2<' videos6cursor
S1L17& VV7H2S<262<BS
7L<S1 videos6cursor
D1ALL<7A&1 videos6cursor
SELECT 99C(SO:OWS
D17LA21 employees6cursor 7H2S<2 /<2
S1L17& ename /2<' 1mployee
<.1E employees6cursor
/1&7H E1@& /2<' employees6cursor
S1L17& VV7H2S<262<BS
7L<S1 employees6cursor
D1ALL<7A&1 employees6cursor
Using a Select Statement
We can also use a SELECT statement to process through a set of records one record at a
time. To do this we will issue an initial SELECT statement that will return the first row# then
a series of follow on SELECT statements where each SELECT statement retrie$es the ne&t
row. This is done by using the CTO< -C clause of the SELECT statement# and a WHEE
statement.
We will use the same e&ample as abo$e and only return the top = employee no4s from the
2orthwind database Employee table. %n this code we will use two different CSELECT TO< -C
statements and a WH%LE loop to return all = records. Each record will be processed one at a
time.
declare 9Empno nchar5=6
declare V2owEum int
select top 0 V1mpnoR1mpno from Eorthwind.dbo.1mployee
set V2owEum R !
BH3L1 V2owEum F "
+1A3E
set V2owEum R V2owEum K 0
print cast)V2owEum as char)0** K N N K V1mpno
select top 0 V1mpnoR1mpno from Eorthwind.dbo.1mployee
where 1mpno G V1mpno
1ED
- >?@A
. >BAA
? >=.-
B >=@@
= >@=B

Here we can see the first SELECT statement selects only the first Empno.
This %' is placed in the local $ariable 9Empno.
The WH%LE loop is controled by the local $ariable 9ow2um.
Each time through the WH%LE loop# the ow 2umber and Empno are printed out.
<rior to returning to the top of the WH%LE loop we used another CSELECT TO< -C statement
to select the ne&t Empno.
This SELECT statement uses a WHEE clause on the SELECT statement to select the first
Empno that is greater than the Empno that was Hust printed.
The WH%LE loop is processed = times# allowing the SELECT TO< - method to retrie$e the top
= Empno4s one records at a time.
D17LA21 V1mpno nchar)"*
D17LA21 V2owEum int
D17LA21 1mpList 7H2S<2 /AS&6/<2BA2D /<2
S1L17& &<. " 1mpno /2<' 1mployee
<.1E 1mpList
/1&7H E1@& /2<' 1mpList
3E&< V1mpno
S1& V2owEum R !
BH3L1 VV/1&7H6S&A&HS R !
+1A3E
S1& V2owEum R V2owEum K 0
.23E& cast)V2owEum as char)0** K N N K V1mpno
/1&7H E1@& /2<' 1mpList
3E&< V1mpno
1ED
7L<S1 1mpList
D1ALL<7A&1 1mpList
Cursor O.timi/ation Ti.s
Try to a0oid using S1L Ser0er cursors* 2hene0er .ossi3le+
SQL Ser$er cursors can results in some performance degradation in comparison with
select statements. Try to use correlated sub*uery or deri$ed tables# if you need to
perform row,by,row operations.
"o not forget to close S1L Ser0er cursor 2hen its result set is not needed+
"o not forget to deallocate S1L Ser0er cursor 2hen the data structures
com.rising the cursor are not needed+
Try to reduce the num3er of records to .rocess in the cursor+
To reduce the cursor result set# use the WHEE clause in the cursor4s select
statement.
Try to reduce the num3er of columns to .rocess in the cursor+
%nclude in the cursor4s select statement only necessary columns. %t will reduce the
cursor result set. So# the cursor will use fewer resources. %t can increase cursor
performance and reduce SQL Ser$er o$erhead.
Use R'A" O#L$ cursors* 2hene0er .ossi3le* instead of u.data3le cursors+
1ecause using cursors can reduce concurrency and lead to unnecessary loc!ing# try
to use E"' O2L8 cursors# if you do not need to update cursor result set.
Try a0oid using insensiti0e* static and 4eyset cursors* 2hene0er .ossi3le+
These types of cursor produce the largest amount of o$erhead on SQL Ser$er#
because they cause a temporary table to be created in TE;<'1# which results in
some performance degradation.
Use AST_OR!AR" cursors* 2hene0er .ossi3le+
The )"ST:)OW"' cursors produce the least amount of o$erhead on SQL Ser$er#
because there are read,only cursors and can only be scrolled from the first to the last
row. (se )"ST:)OW"' cursor if you do not need to update cursor result set and
the )ETCH 2E3T will be the only used fetch option.
Use OR!AR"_O#L$ cursors* if you need u.data3le cursor and the 'TC5
#'-T 2ill 3e the only used fetch o.tion+
%f you need read,only cursor and the )ETCH 2E3T will be the only used fetch option#
try to use )"ST:)OW"' cursor instead of )OW"':O2L8 cursor. 1y the way# if
one of the )"ST:)OW"' or )OW"':O2L8 is specified the other cannot be
specified.
Here is an e8ample cursor where backups are issued in a serial manner,
D17LA21 Vname %A27HA2)"!* -- database name
D17LA21 Vpath %A27HA2)";* -- path for backup files
D17LA21 VfileEame %A27HA2)";* -- filename for backup
D17LA21 VfileDate %A27HA2)!* -- used for file name
S1& Vpath R N7,-'y+ackup-N
S1L17& VfileDate R 7<E%12&)%A27HA2)!*(A1&DA&1)*(00*
D17LA21 db6cursor 7H2S<2 /<2
S1L17& name
/2<' master.dbo.sysdatabases
BH121 name E<& 3E )NmasterN(NmodelN(NmsdbN(NtempdbN*
<.1E db6cursor
/1&7H E1@& /2<' db6cursor 3E&< Vname
BH3L1 VV/1&7H6S&A&HS R !
+1A3E
S1& VfileEame R Vpath K Vname K N6N K VfileDate K N.+A>N
+A7>H. DA&A+AS1 Vname &< D3S> R VfileEame
/1&7H E1@& /2<' db6cursor 3E&< Vname
1ED
7L<S1 db6cursor
D1ALL<7A&1 db6cursor
Cursor Components
+ased on the e8ample above( cursors include these components,
D17LA21 statements - Declare variables used in the code block
S1&-S1L17& statements - 3nitiali=e the variables to a specific value
D17LA21 7H2S<2 statement - .opulate the cursor with values that will be evaluated
E<&1 - &here are an e4ual number of variables in the D17LA21 Fcursor6nameG
7H2S<2 /<2 statement as there are in the S1L17& statement. &his could be 0
or many variables and associated columns.
<.1E statement - <pen the cursor to begin data processing
/1&7H E1@& statements - Assign the specific values from the cursor to the variables
E<&1 - &his logic is used for the initial population before the BH3L1 statement
and then again during each loop in the process as a portion of the BH3L1
statement
BH3L1 statement - 7ondition to begin and continue data processing
+1A3E...1ED statement - Start and end of the code block
E<&1 - +ased on the data processing multiple +1A3E...1ED statements can be
used
Data processing - 3n this e8ample( this logic is to backup a database to a specific path and
file name( but this could be 5ust about any D'L or administrative logic
7L<S1 statement - 2eleases the current data and associated locks( but permits the cursor
to be re-opened
D1ALL<7A&1 statement - Destroys the cursor
#################################################
declare Vmyvar int R 0!( Vmystr nvarchar)0"*RNHelloN
print Vmyvar
print Vmystr
##########################################
"n insensitive cursor is not affected by changes to the underlying data. When the cursor
is opened# a temporary table is created in the tempdb database. This table is populated
with the results of the *uery immediately. Once populated# each fetch retrie$es information
from the temporary table# rather than the li$e data.
&o specify that a cursor is insensitive( add the 3ES1ES3&3%1 clause immediately after the cursor
name in the declaration. /or e8ample,
4E;LA&E ,illi/g;Ersor INSENSI)IME ;5&S'&
F'& SELE;) KoFId, ;o/tractNEmFer, 4Eratio/, E/gi/eer;ost, 2arts;ost
F&'M ,illi/gS9stem'EtpEt4ata
%f a 'ECL"E C(SO using Transact,SQL synta& does not specify E"':O2L8#
O<T%;%ST%C# or SCOLL:LOC7S# the default is as follows+
3f the S1L17& statement does not support updates )insufficient permissions( accessing
remote tables that do not support updates( and so on*( the cursor is 21AD6<ELD.
S&A&37 and /AS&6/<2BA2D cursors default to 21AD6<ELD.
DDEA'37 and >1DS1& cursors default to <.&3'3S&37.
-eneral 'ntervie* Questions o# SQL S)R?)R
="at is RDBMSC
2elational Data +ase 'anagement Systems )2D+'S* are database management systems that
maintain data records and indices in tables. 2elationships may be created and maintained across
and among the data and tables. 3n a relational database( relationships between data items are
e8pressed by means of tables. 3nterdependencies among these tables are e8pressed by data values
rather than by pointers. &his allows a high degree of data independence. An 2D+'S has the
capability to recombine the data items from different files( providing powerful tools for data
usage.
="at are t"e properties o# t"e Relational tablesC
2elational tables have si8 properties,
%alues are atomic.
7olumn values are of the same kind.
1ach row is uni4ue.
&he se4uence of columns is insignificant.
&he se4uence of rows is insignificant.
1ach column must have a uni4ue name.
="at is NormaliBationC
Database normali=ation is a data design and organi=ation process applied to data structures based
on rules that help building relational databases. 3n relational database design( the process of
organi=ing data to minimi=e redundancy is called normali=ation. Eormali=ation usually involves
dividing a database into two or more tables and defining relationships between the tables. &he
ob5ective is to isolate data so that additions( deletions( and modifications of a field can be made
in 5ust one table and then propagated through the rest of the database via the defined
relationships.
="at are di##erent normaliBation #ormsC
"N#$ Eliminate %epeating &roups
'ake a separate table for each set of related attributes( and give each table a primary key. 1ach
field contains at most one value from its attribute domain.
'N#$ Eliminate %edundant Data
3f an attribute depends on only part of a multi-valued key( remove it to a separate table.
(N#$ Eliminate Columns Not Dependent On )ey
3f attributes do not contribute to a description of the key( remove them to a separate table. All
attributes must be directly dependent on the primary key.
*CN#$ *oyce-Codd Normal #orm
3f there are non-trivial dependencies between candidate key attributes( separate them out into
distinct tables.
+N#$ ,solate ,ndependent -ultiple %elationships
Eo table may contain two or more 0,n or n,m relationships that are not directly related.
.N#$ ,solate Semantically %elated -ultiple %elationships
&here may be practical constrains on information that 5ustify separating logically related many-
to-many relationships.
ON#$ Optimal Normal #orm
A model limited to only simple )elemental* facts( as e8pressed in <b5ect 2ole 'odel notation.
D)N#$ Domain-)ey Normal #orm
A model free from all modification anomalies is said to be in D>E/.
2emember( these normali=ation guidelines are cumulative. /or a database to be in 9E/( it must
first fulfill all the criteria of a E/ and 0E/ database.
="at is De4normaliBationC
De-normali=ation is the process of attempting to optimi=e the performance of a database by
adding redundant data. 3t is sometimes necessary because current D+'Ss implement the
relational model poorly. A true relational D+'S would allow for a fully normali=ed database at
the logical level( while providing physical storage of data that is tuned for high performance. De-
normali=ation is a techni4ue to move from higher to lower normal forms of database modeling in
order to speed up database access.
="at is Stored &rocedureC
A stored procedure is a named group of SQL statements that have been previously created and
stored in the server database. Stored procedures accept input parameters so that a single
procedure can be used over the network by several clients using different input data. And when
the procedure is modified( all clients automatically get the new version. Stored procedures
reduce network traffic and improve performance. Stored procedures can be used to help ensure
the integrity of the database.
e.g. sp=.elpdF( sp=re/amedF( sp=depe/ds etc.
="at is Tri$$erC
A trigger is a SQL procedure that initiates an action when an event )3ES12&( D1L1&1 or
H.DA&1* occurs. &riggers are stored in and managed by the D+'S. &riggers are used to
maintain the referential integrity of data by changing the data in a systematic fashion. A trigger
cannot be called or e8ecutedP D+'S automatically fires the trigger as a result of a data
modification to the associated table. &riggers can be viewed as similar to stored procedures in
that both consist of procedural logic that is stored at the database level. Stored procedures(
however( are not event-drive and are not attached to a specific table as triggers are. Stored
procedures are e8plicitly e8ecuted by invoking a 7ALL to the procedure while triggers are
implicitly e8ecuted. 3n addition( triggers can also e8ecute stored procedures.
Nested Trigger, A trigger can also contain 3ES12&( H.DA&1 and D1L1&1 l
ogic within itself( so when the trigger is fired because of data modification
it can also cause another data modification( thereby firing another trigger.
A trigger that contains data modification logic
within itself is called a nested trigger.
="at is ?ie*C
A simple view can be thought of as a subset of a table. 3t can be used for retrieving data( as well
as updating or deleting rows. 2ows updated or deleted in the view are updated or deleted in the
table the view was created with. 3t should also be noted that as data in the original table changes(
so does data in the view( as views are the way to look at part of the original table. &he results of
using a view are not permanently stored in the database. &he data accessed through a view is
actually constructed using standard &-SQL select command and can come from one to many
different base tables or even other views.
="at is 'ndexC
An inde8 is a physical structure containing pointers to the data.
3ndices are created in an e8isting table to locate rows more 4uickly and efficiently. 3t is possible
to create an inde8 on one or more columns of a table( and each inde8 is given a name. &he users
cannot see the inde8esP they are 5ust used to speed up 4ueries. 1ffective inde8es are one of the
best ways to improve performance in a database application. A table scan happens when there is
no inde8 available to help a 4uery. 3n a table scan SQL Server e8amines every row in the table to
satisfy the 4uery results. &able scans are sometimes unavoidable( but on large tables( scans have
a terrific impact on performance.
="at is a Lin6ed ServerC
Linked Servers is a concept in SQL Server by which we can add
other SQL Server to a Aroup and 4uery both the SQL Server databases using
&-SQL Statements.
Bith a linked server( you can create very clean( easy to follow( SQL statements that allow remote
data to be retrieved( 5oined and combined with local data. Stored .rocedure sp=addli/Gedserver(
sp=addli/Gedsrvlogi/ will be used add new Linked Server-level
,1 -eneral Questions o# SQL S)R?)R
="at is CursorC
7ursor is a database ob5ect used by applications to manipulate data in a set on a row-by-row
basis( instead of the typical SQL commands that operate on all the rows in the set at one time.
3n order to work with a cursor we need to perform some steps in the following order,
Declare cursor
<pen cursor
/etch row from the cursor
.rocess fetched row
7lose cursor
Deallocate cursor
="at is CollationC
7ollation refers to a set of rules that determine how data is sorted and compared. 7haracter data
is sorted using rules that define the correct character se4uence( with options for specifying case
sensitivity( accent marks( kana character types and character width.
="at is Di##erence bet*een Function and Stored &rocedureC
HD/ can be used in the SQL statements anywhere in the BH121OHA%3EAOS1L17& section
where as Stored procedures cannot be. HD/s that return tables can be treated as another rowset.
&his can be used in M<3Es with other tables. 3nline HD/Xs can be thought of as views that take
parameters and can be used in M<3Es and other 2owset operations.
="at is sub43ueryC )xplain properties o# sub43ueryC
Sub-4ueries are often referred to as sub-selects( as they allow a S1L17& statement to be
e8ecuted arbitrarily within the body of another SQL statement. A sub-4uery is e8ecuted by
enclosing it in a set of parentheses. Sub-4ueries are generally used to return a single row as an
atomic value( though they may be used to compare values against multiple rows with the 3E
keyword.
A sub4uery is a S1L17& statement that is nested within another &-SQL statement. A sub4uery
S1L17& statement if e8ecuted independently of the &-SQL statement( in which it is nested( will
return a resultset. 'eaning a sub4uery S1L17& statement can standalone and is not depended on
the statement in which it is nested. A sub4uery S1L17& statement can return any number of
values( and can be found in( the column list of a S1L17& statement( a /2<'( A2<H. +D(
HA%3EA( andOor <2D12 +D clauses of a &-SQL statement. A Sub4uery can also be used as a
parameter to a function call. +asically a sub4uery can be used anywhere an e8pression can be
used. )2ead 'ore Here*
="at are di##erent Types o# AoinC
Cross /oin
A cross 5oin that does not have a BH121 clause produces the 7artesian product of the tables
involved in the 5oin. &he si=e of a 7artesian product result set is the number of rows in the first
table multiplied by the number of rows in the second table. &he common e8ample is when
company wants to combine each product with a pricing table to analy=e each product at each
price.
,nner /oin
A 5oin that displays only the rows that have a match in both 5oined tables is known as inner Moin.
&his is the default type of 5oin in the Query and %iew Designer.
Outer /oin
A 5oin that includes rows even if they do not have related rows in the 5oined table is an <uter
Moin. Dou can create three different outer 5oin to specify the unmatched rows to be included,
Le#t 2uter Aoin: 3n Left <uter Moin all rows in the first-named table i.e. aleftb table(
which appears leftmost in the M<3E clause are included. Hnmatched rows in the right
table do not appear.
Ri$"t 2uter Aoin: 3n 2ight <uter Moin all rows in the second-named table i.e. arightb
table( which appears rightmost in the M<3E clause are included. Hnmatched rows in the
left table are not included.
Full 2uter Aoin: 3n /ull <uter Moin all rows in all 5oined tables are included( whether
they are matched or not.
Self /oin
&his is a particular case when one table 5oins to itself( with one or two aliases to avoid confusion.
A self 5oin can be of any type( as long as the 5oined tables are the same. A self 5oin is rather
uni4ue in that it involves a relationship with only one table. &he common e8ample is when
company has a hierarchal reporting structure whereby one member of staff reports to another.
Self Moin can be <uter Moin or 3nner Moin.
="at are primary 6eys and #orei$n 6eysC
.rimary keys are the uni4ue identifiers for each row. &hey must contain uni4ue values and
cannot be null. Due to their importance in relational databases( .rimary keys are the most
fundamental of all keys and constraints. A table can have only one .rimary key.
/oreign keys are both a method of ensuring data integrity and a manifestation of the relationship
between tables.
="at is a .ser De#ined FunctionC ="at 6ind o# .ser4De#ined Functions
can be createdC
Hser-Defined /unctions allow defining its own &-SQL functions that can accept ! or more
parameters and return a single scalar data value or a table data type.
Different )inds of 0ser-Defined #unctions created are$
Scalar 0ser-Defined #unction
A Scalar user-defined function returns one of the scalar data types. &e8t( nte8t( image and
timestamp data types are not supported. &hese are the type of user-defined functions that most
developers are used to in other programming languages. Dou pass in ! to many parameters and
you get a return value.
,nline Table-Value 0ser-Defined #unction
An 3nline &able-%alue user-defined function returns a table data type and is an e8ceptional
alternative to a view as the user-defined function can pass parameters into a &-SQL select
command and in essence provide us with a parameteri=ed( non-updateable view of the
underlying tables.
-ulti-statement Table-Value 0ser-Defined #unction
A 'ulti-Statement &able-%alue user-defined function returns a table and is also an e8ceptional
alternative to a view as the function can support multiple &-SQL statements to build the final
result where the view is limited to a single S1L17& statement. Also( the ability to pass
parameters into a &SQL select command or a group of them gives us the capability to in essence
create a parameteri=ed( non-updateable view of the data in the underlying tables. Bithin the
create function command you must define the table structure that is being returned. After
creating this type of user-defined function( 3t can be used in the /2<' clause of a &-SQL
command unlike the behavior found when using a stored procedure which can also return record
sets.
="at is 'dentityC
3dentity )or AutoEumber* is a column that automatically
generates numeric values. A start and increment value can be set(
but most D+A leave these at 0.
A AH3D column also generates numbersP the value of this cannot be controlled. 3dentityOAH3D
columns do not need to be inde8ed.
="at is Data=are"ousin$C
Sub5ect-oriented( meaning that the data in the database is organi=ed
so that all the data elements relating to the same real-world event or
ob5ect are linked togetherP
&ime-variant( meaning that the changes to the data in the
database are tracked and recorded so that reports can be produced
showing changes over timeP
Eon-volatile( meaning that data in the database is never
over-written or deleted( once committed( the data is static(
read-only( but retained for future reporting.
3ntegrated( meaning that the database contains data from
most or all of an organi=ationXs operational applications(
and that this data is made consistent.
,1 -eneral Questions o# SQL S)R?)R
+1 Common Questions s6ed
="ic" TC&L'& port does SQL Server run onC :o* can it be c"an$edC
SQL Server runs on port 0C99. 3t can be changed from the
Eetwork Htility &7.O3. properties -G .ort number( both on client and the server.
="at are t"e di##erence bet*een clustered and a non4clustered indexC
1 clustered index is a special type of inde8 that reorders
the way records in the table are physically stored.
&herefore table can have only one clustered inde8.
&he leaf nodes of a clustered inde8 contain the data pages.
1 non clustered index is a special type of inde8 in which the logical
order of the inde8 does not match the physical stored order
of the rows on disk. &he leaf node of a non clustered
inde8 does not consist of the data pages but contains pointers to data.
="at are t"e di##erent index con#i$urations a table can "aveC
A table can have one of the following inde8 configurations,
Eo inde8es
A clustered inde8
A clustered inde8 and many nonclustered inde8es
A nonclustered inde8
'any nonclustered inde8es
="at are di##erent types o# Collation SensitivityC
Case sensiti2ity L A and a( + and b( etc.
1ccent sensiti2ity L a and e( o and f( etc.
)ana Sensiti2ity L Bhen Mapanese kana characters Hiragana and >atakana are treated differently(
it is called >ana sensitive.
3idth sensiti2ity L A single-byte character )half-width* and the same character represented as a
double-byte character )full-width* are treated differently than it is width sensitive.
="at is 2LT& /2nline Transaction &rocessin$1C
3n <L&. L online transaction processing systems relational database design use the discipline of
data modeling and generally follow the 7odd rules of data normali=ation in order to ensure
absolute data integrity. Hsing these rules comple8 information is broken down into its most
simple structures )a table* where all of the individual atomic level elements relate to each other
and satisfy the normali=ation rules.
="atMs t"e di##erence bet*een a primary 6ey and a uni3ue 6eyC
+oth primary key and uni4ue key enforces uni4ueness of the column on which they are defined.
+ut by default primary key creates a clustered inde8 on the column( where are uni4ue creates a
nonclustered inde8 by default. Another ma5or difference is that( primary key doesnXt allow
EHLLs( but uni4ue key allows one EHLL only.
="at is di##erence bet*een D)L)T) N TR.NCT) commandsC
Delete command removes the rows from a table based on the
condition that we provide with a BH121 clause.
&runcate will actually remove all the rows from a table and we can rollback it.
T%0NC1TE
&2HE7A&1 is faster and uses fewer system and transaction log resources than D1L1&1.
&2HE7A&1 removes the data by deallocating the data pages used to store the tableXs
data( and only the page deallocations are recorded in the transaction log.
&2HE7A&1 removes all rows from a table( but the table structure( its columns(
constraints( inde8es and so on( remains. &he counter used by an identity for new rows is
reset to the seed for the column.
Dou cannot use &2HE7A&1 &A+L1 on a table referenced by a /<213AE >1D
constraint. +ecause &2HE7A&1 &A+L1 is not logged( it cannot activate a trigger.
&2HE7A&1 cannot be rolled back.
&2HE7A&1 is DDL 7ommand.
&2HE7A&1 2esets identity of the table
DE4ETE
D1L1&1 removes rows one at a time and records an entry in the transaction log for each
deleted row.
3f you want to retain the identity counter( use D1L1&1 instead. 3f you want to remove
table definition and its data( use the D2<. &A+L1 statement.
D1L1&1 7an be used with or without a BH121 clause
D1L1&1 Activates &riggers.
D1L1&1 can be rolled back.
D1L1&1 is D'L 7ommand.
D1L1&1 does not reset identity of the table.
="en is t"e use o# .&DT)%STT'ST'CS commandC
&his command is basically used when a large processing of data has occurred. 3f a large amount
of deletions any modification or +ulk 7opy into the tables has occurred( it has to update the
inde8es to take these changes into account. H.DA&16S&A&3S&37S updates the inde8es on these
tables accordingly.
="at is t"e di##erence bet*een a :?'N- CL.S) and a =:)R) CL.S)C
&hey specify a search condition for a group or an aggregate. +ut the difference is that HA%3EA
can be used only with the S1L17& statement. HA%3EA is typically used in a A2<H. +D
clause. Bhen A2<H. +D is not used( HA%3EA behaves like a BH121 clause. Having 7lause
is basically used only with the A2<H. +D function in a 4uery whereas BH121 7lause is
applied to each row before they are part of the A2<H. +D function in a 4uery.
="at are t"e properties and di##erent Types o# Sub4QueriesC
5roperties of Sub-6uery
A sub-4uery must be enclosed in the parenthesis.
A sub-4uery must be put in the right hand of the comparison operator( and
A sub-4uery cannot contain an <2D12-+D clause.
A 4uery can contain more than one sub-4uery.
Types of Sub-query
Single-row sub-4uery( where the sub-4uery returns only one row.
'ultiple-row sub-4uery( where the sub-4uery returns multiple rows(. and
'ultiple column sub-4uery( where the sub-4uery returns multiple columns
="at is SQL &ro#ilerC
SQL .rofiler is a graphical tool that allows system administrators to monitor events in an
instance of 'icrosoft SQL Server. Dou can capture and save data about each event to a file or
SQL Server table to analy=e later. /or e8ample( you can monitor a production environment to see
which stored procedures are hampering performances by e8ecuting too slowly.
Hse SQL .rofiler to monitor only the events in which you are interested. 3f traces are becoming
too large( you can filter them based on the information you want( so that only a subset of the
event data is collected. 'onitoring too many events adds overhead to the server and the
monitoring process and can cause the trace file or trace table to grow very large( especially when
the monitoring process takes place over a long period of time.
="at are t"e aut"entication modes in SQL ServerC :o* can it be c"an$edC
Bindows mode and 'i8ed 'ode L SQL # Bindows.
&o change authentication mode in SQL Server click Start( .rograms( 'icrosoft SQL Server and
click SQL 1nterprise 'anager to run SQL 1nterprise 'anager from the 'icrosoft SQL Server
program group. Select the server then from the &ools menu select SQL Server 7onfiguration
.roperties( and choose the Security page.
,1 -eneral Questions o# SQL S)R?)R
="ic" command usin$ Query nalyBer *ill $ive you t"e version o# SQL server and
operatin$ systemC
SELE;) SE&ME&2&'2E&)J :'prodEctversio/'+, SE&ME&2&'2E&)J :'prodEctlevel'+,
SE&ME&2&'2E&)J :'editio/'+
="at is SQL Server $entC
SQL Server agent plays an important role in the day-to-day tasks of a database administrator
)D+A*. 3t is often overlooked as one of the main tools for SQL Server management. 3ts purpose
is to ease the implementation of tasks for the D+A( with its full-function scheduling engine(
which allows you to schedule your own 5obs and scripts.
Can a stored procedure call itsel# or recursive stored procedureC :o* muc" level S&
nestin$ is possibleC
Des. +ecause &ransact-SQL supports recursion( you can write stored procedures that call
themselves. 2ecursion can be defined as a method of problem solving wherein the solution is
arrived at by repetitively applying it to subsets of the problem. A common application of
recursive logic is to perform numeric computations that lend themselves to repetitive evaluation
by the same processing steps. Stored procedures are nested when one stored procedure calls
another or e8ecutes managed code by referencing a 7L2 routine( type( or aggregate. Dou can
nest stored procedures and managed code references up to 9 levels.
="at is Lo$ S"ippin$C
Log shipping is the process of automating the backup of database and transaction log files on a
production SQL server( and then restoring them onto a standby server. 1nterprise 1ditions only
supports log shipping. 3n log shipping the transactional log file from one server is automatically
updated into the backup database on the other server. 3f one server fails( the other server will
have the same db and can be used this as the Disaster 2ecovery plan. &he key feature of log
shipping is that it will automatically backup transaction logs throughout the day and
automatically restore them on the standby server at defined interval.
Name H *ays to $et an accurate count o# t"e number o# records in a tableC
SELE;) P F&'M taFle!
SELE;) ;'5N):P+ F&'M taFle!
SELE;) ro6s F&'M s9si/deDes (*E&E id = ',KE;)=I4:taFle!+ AN4 i/did Y -
="at does it mean to "ave Q.2T)D%'D)NT'F')R 2NC ="at are t"e implications o#
"avin$ it 2FFC
Bhen S1& QH<&1D63D1E&3/312 is <E( identifiers can be delimited by double 4uotation
marks( and literals must be delimited by single 4uotation marks. Bhen S1&
QH<&1D63D1E&3/312 is <//( identifiers cannot be 4uoted and must follow all &ransact-SQL
rules for identifiers.
="at is t"e di##erence bet*een a Local and a -lobal temporary tableC
1 local temporary table e8ists only for the duration of a connection or( if defined inside a
compound statement( for the duration of the compound statement.
1 global temporary table remains in the database permanently( but the rows e8ist only within a
given connection. Bhen connection is closed( the data in the global temporary table disappears.
However( the table definition remains with the database for access when database is opened ne8t
time.
="at is t"e ST.FF #unction and "o* does it di##er #rom t"e R)&LC) #unctionC
S&H// function is used to overwrite e8isting characters. Hsing this synta8( S&H//
)string6e8pression( start( length( replacement6characters*( string6e8pression is the string that will
have characters substituted( start is the starting position( length is the number of characters in the
string that are substituted( and replacement6characters are the new characters inter5ected into the
string. 21.LA71 function to replace e8isting characters of all occurrences. Hsing the synta8
21.LA71 )string6e8pression( search6string( replacement6string*( where every incidence of
search6string found in the string6e8pression will be replaced with replacement6string.
="at is &R'MR7 8)7C
A .23'A2D >1D constraint is a uni4ue identifier for a row within a database table. 1very table
should have a primary key constraint to uni4uely identify each row and only one primary key
constraint can be created for each table. &he primary key constraints are used to enforce entity
integrity.
="at is .N'Q.) 8)7 constraintC
A HE3QH1 constraint enforces the uni4ueness of the values in a set of columns( so no duplicate
values are entered. &he uni4ue key constraints are used to enforce entity integrity as the primary
key constraints.
="at is F2R)'-N 8)7C
A /<213AE >1D constraint prevents any actions that would destroy links between tables with
the corresponding data values. A foreign key in one table points to a primary key in another
table. /oreign keys prevent actions that would leave rows with foreign key values when there are
no primary keys with that value. &he foreign key constraints are used to enforce referential
integrity.
="at is C:)C8 ConstraintC
A 7H17> constraint is used to limit the values that can be placed in a column. &he check
constraints are used to enforce domain integrity.
="at is N2T N.LL ConstraintC
A E<& EHLL constraint enforces that the column will not accept null values. &he not null
constraints are used to enforce domain integrity( as the check constraints.
:o* to $et @@)RR2R and @@R2=C2.NT at t"e same timeC
3f VV2owcount is checked after 1rror checking statement then it will have ! as the value of
VV2ecordcount as it would have been reset. And if VV2ecordcount is checked before the
error-checking statement then VV1rror would get reset. &o get VVerror and VVrowcount at
the same time do both in same statement and store them in local variable. S1L17& V27 R
VV2<B7<HE&( V12 R VV122<2
="at is a Sc"eduled Aobs or ="at is a Sc"eduled Tas6sC
Scheduled tasks let user automate processes that run on regular or predictable cycles. Hser can
schedule administrative tasks( such as cube processing( to run during times of slow business
activity. Hser can also determine the order in which tasks run by creating 5ob steps within a SQL
Server Agent 5ob. 1.g. back up database( Hpdate Stats of &ables. Mob steps give user control over
flow of e8ecution. 3f one 5ob fails( user can configure SQL Server Agent to continue to run the
remaining tasks or to stop e8ecution.
="at are t"e advanta$es o# usin$ Stored &roceduresC
Stored procedure can reduced network traffic and latency( boosting application
performance.
Stored procedure e8ecution plans can be reused( staying cached in SQL ServerXs memory(
reducing server overhead.
Stored procedures help promote code reuse.
Stored procedures can encapsulate logic. Dou can change stored procedure code without
affecting clients.
Stored procedures provide better security to your data.
="at is a table called9 i# it "as neit"er Cluster nor Non4cluster 'ndexC ="at is it used #orC
Hninde8ed table or Heap. 'icrosoft .ress +ooks and +ook on Line )+<L* refers it as Heap. A
heap is a table that does not have a clustered inde8 and( therefore( the pages are not linked by
pointers. &he 3A' pages are the only structures that link the pages in a table together. Hninde8ed
tables are good for fast storing of data. 'any times it is better to drop all inde8es from table and
then do bulk of inserts and to restore those inde8es after that.
Can SQL Servers lin6ed to ot"er servers li6e 2racleC
SQL Server can be linked to any server provided it has <L1-D+ provider from 'icrosoft to
allow a link. 1.g. <racle has an <L1-D+ provider for oracle that 'icrosoft provides to add it as
linked server to SQL Server group
="at is BC&C ="en does it usedC
+ulk7opy is a tool used to copy huge amount of data from tables and views. +7. does not copy
the structures same as source to destination. +HL> 3ES12& command helps to import a data file
into a database table or view in a user-specified format.
="at command do *e use to rename a db9 a table and a columnC
To rename db
sp=re/amedF 'old/ame' , '/e6/ame'
3f someone is using db it will not accept sp6renmaedb. 3n that case first bring db to single user
using sp6dboptions. Hse sp6renamedb to rename database. Hse sp6dboptions to bring database
to multi user mode.
1.g.
5SE masterI
%'
E#E; sp=dFoptio/ Adve/tEre(orGs, 'Si/gle 5ser', )rEe
%'
E#E; sp=re/amedF 'Adve/tEre(orGs', 'Adve/tEre(orGs=Ne6'
%'
E#E; sp=dFoptio/ Adve/tEre(orGs, 'Si/gle 5ser', False
%'
To rename Table
Be can change the table name using sp6rename as follows(
sp=re/ame 'old)aFleName' '/e6)aFleName'
1.g.
sp=&ENAME ')aFle=First', ')aFle=Last'
%'
To rename Column
&he script for renaming any column ,
sp=re/ame ')aFleName.>'ldcolEm/Name?', 'Ne6;olEm/Name', ';olEm/'
1.g.
sp=&ENAME ')aFle=First.Name', 'Name;.a/ge' , ';'L5MN'
%'
="at are sp%con#i$ure commands and set commandsC
Hse sp6configure to display or change server-level settings. &o change database-level settings(
use AL&12 DA&A+AS1. &o change settings that affect only the current user session( use the
S1& statement.
1.g.
sp=;'NFI%5&E 's.o6 adva/ced', "
%'
&E;'NFI%5&E
%'
sp=;'NFI%5&E
%'
Dou can run following command and check advance global configuration settings.
sp=;'NFI%5&E 's.o6 adva/ced', !
%'
&E;'NFI%5&E
%'
sp=;'NFI%5&E
%'
:o* to implement one4to4one9 one4to4many and many4to4many relations"ips *"ile
desi$nin$ tablesC
<ne-to-<ne relationship can be implemented as a single table and rarely as two tables with
primary and foreign key relationships. <ne-to-'any relationships are implemented by splitting
the data into two tables with primary key and foreign key relationships.
'any-to-'any relationships are implemented using a 5unction table with the keys from both the
tables forming the composite primary key of the 5unction table.
="at is an execution planC ="en *ould you use itC :o* *ould you vie* t"e execution
planC
An e8ecution plan is basically a road map that graphically or te8tually shows the data retrieval
methods chosen by the SQL Server 4uery optimi=er for a stored procedure or ad-hoc 4uery and is
a very useful tool for a developer to understand the performance characteristics of a 4uery or
stored procedure since the plan is the one that SQL Server will place in its cache and use to
e8ecute the stored procedure or 4uery. /rom within Query Analy=er is an option called aShow
18ecution .lanb )located on the Query drop-down menu*. 3f this option is turned on it will
display 4uery e8ecution plan in separate window when 4uery is ran again.
="at are t"e basic #unctions #or master9 msdb9 model9 tempdb and resource databasesC
The master database holds information for all databases located on the SQL Server instance and
is theglue that holds the engine together. +ecause SQL Server cannot start without a functioning
masterdatabase( you must administer this database with care.
The msdb database stores information regarding database backups( SQL Agent information(
D&S packages( SQL Server 5obs( and some replication information such as for log shipping.
The tempdb holds temporary ob5ects such as global and local temporary tables and stored
procedures.
The model is essentially a template database used in the creation of any new user database
created in the instance.
The resoure Database is a read-only database that contains all the system ob5ects that are
included with SQL Server. SQL Server system ob5ects( such as sys.ob5ects( are physically
persisted in the 2esource database( but they logically appear in the sys schema of every database.
&he 2esource database does not contain user data or user metadata.
="at is Service Bro6erC
Service +roker is a message-4ueuing technology in SQL Server that allows developers to
integrate SQL Server fully into distributed applications. Service +roker is feature which provides
facility to SQL Server to send an asynchronous( transactional message. it allows a database to
send a message to another database without waiting for the response( so the application will
continue to function if the remote database is temporarily unavailable.
="ere SQL server user names and pass*ords are stored in SQL serverC
&hey get stored in System 7atalog %iews sys.server6principals and sys.s4l6logins.
="at is &olicy Mana$ementC
.olicy 'anagement in SQL S12%12 !!$ allows you to define and enforce policies for
configuring and managing SQL Server across the enterprise. .olicy-+ased 'anagement is
configured in SQL Server 'anagement Studio )SS'S*. Eavigate to the <b5ect 18plorer and
e8pand the 'anagement node and the .olicy 'anagement nodeP you will see the .olicies(
7onditions( and /acets nodes. )2ead 'ore Here*
="at is Replication and Database Mirrorin$C
Database mirroring can be used with replication to provide availability for the publication
database. Database mirroring involves two copies of a single database that typically reside on
different computers. At any given time( only one copy of the database is currently available to
clients which are known as the principal database. Hpdates made by clients to the principal
database are applied on the other copy of the database( known as the mirror database. 'irroring
involves applying the transaction log from every insertion( update( or deletion made on the
principal database onto the mirror database.
="at are Sparse ColumnsC
A sparse column is another tool used to reduce the amount of physical storage used in a database.
&hey are the ordinary columns that have an optimi=ed storage for null values. Sparse columns
reduce the space re4uirements for null values at the cost of more overhead to retrieve nonnull
values. )2ead 'ore Here*
="at does T2& 2perator DoC
&he &<. operator is used to specify the number of rows to be returned by a 4uery. &he &<.
operator has new addition in SQL S12%12 !!$ that it accepts variables as well as literal values
and can be used with 3ES12&( H.DA&1( and D1L1&1S statements.
="at is CT)C
7&1 is an abbreviation 7ommon &able 18pression. A 7ommon &able 18pression )7&1* is an
e8pression that can be thought of as a temporary result set which is defined within the e8ecution
of a single SQL statement! A 7&1 is similar to a derived table in that it is not stored as an ob5ect
and lasts only for the duration of the 4uery. )2ead 'ore Here*
="at is M)R-) StatementC
'12A1 is a new feature that provides an efficient way to perform multiple D'L operations. 3n
previous versions of SQL Server( we had to write separate statements to 3ES12&( H.DA&1( or
D1L1&1 data based on certain conditions( but now( using '12A1 statement we can include the
logic of such data modifications in one statement that even checks when the data is matched then
5ust update it and when unmatched then insert it. <ne of the most important advantages of
'12A1 statement is all the data is read and processed only once.
="at is Filtered 'ndexC
/iltered 3nde8 is used to inde8 a portion of rows in a table that means it applies filter on 3ED1@
which improves 4uery performance( reduce inde8 maintenance costs( and reduce inde8 storage
costs compared with full-table inde8es. Bhen we see an 3nde8 created with some where clause
then that is actually a /3L&121D 3ED1@.
="ic" are ne* data types introduced in SQL S)R?)R +EE0C
The &EO-ET%7 Type$ &he A1<'1&2D data type is a system .E1& common language runtime
)7L2* data type in SQL Server. &his type represents data in a two-dimensional 1uclidean
coordinate system.
The &EO&%1587 Type$ &he A1<A2A.HD datatypeXs functions are the same as with
A1<'1&2D. &he difference between the two is that when you specify A1<A2A.HD( you are
usually specifying points in terms of latitude and longitude.
Ne9 Date and Time Datatypes$ SQL Server !!$ introduces four new datatypes related to date
and time, DA&1( &3'1( DA&1&3'1<//S1&( and DA&1&3'1.
D1TE$ &he new DA&1 type 5ust stores the date itself. 3t is based on the Aregorian
calendar and handles years from 0 to JJJJ.
T,-E$ &he new &3'1 )n* type stores time with a range of !!,!!,!!.!!!!!!! through
9,"J,"J.JJJJJJJ. &he precision is allowed with this type. &3'1 supports seconds down
to 0!! nanoseconds. &he n in &3'1 )n* defines this level of fractional second precision(
from ! to : digits of precision.
The D1TET,-EO##SET Type, DA&1&3'1<//S1& )n* is the time-=one-aware version
of a datetime datatype. &he name will appear less odd when you consider what it really is,
a date K a time K a time-=one offset. &he offset is based on how far behind or ahead you
are from 7oordinated Hniversal &ime )H&7* time.
The D1TET,-E' Type, 3t is an e8tension of the datetime type in earlier versions of SQL
Server. &his new datatype has a date range covering dates from Manuary 0 of year 0
through December 90 of year JJJJ. &his is a definite improvement over the 0:"9 lower
boundary of the datetime datatype. DA&1&3'1 not only includes the larger date range(
but also has a timestamp and the same fractional precision that &3'1 type provides
="at are t"e dvanta$es o# usin$ CT)C
Hsing 7&1 improves the readability and makes maintenance of comple8 4ueries easy.
&he 4uery can be divided into separate( simple( logical building blocks which can be then
used to build more comple8 7&1s until final result set is generated.
7&1 can be defined in functions( stored procedures( triggers or even views.
After a 7&1 is defined( it can be used as a &able or a %iew and can S1L17&( 3ES12&(
H.DA&1 or D1L1&1 Data.
:o* can *e re*rite sub43ueries into simple select statements or *it" IoinsC
Des we can write using 7ommon &able 18pression )7&1*. A 7ommon &able 18pression )7&1*
is an e8pression that can be thought of as a temporary result set which is defined within the
e8ecution of a single SQL statement. A 7&1 is similar to a derived table in that it is not stored as
an ob5ect and lasts only for the duration of the 4uery.
1.g.
5SE Adve/tEre(orGs
%'
(I)* Emplo9ee4epartme/t=;)E AS :
SELE;) Emplo9eeI4,4epartme/tI4,S.iftI4
F&'M *Ema/&esoErces.Emplo9ee4epartme/t*istor9
+
SELE;) ecte.Emplo9eeId,ed.4epartme/tI4, ed.Name,ecte.S.iftI4
F&'M *Ema/&esoErces.4epartme/t ed
INNE& K'IN Emplo9ee4epartme/t=;)E ecte 'N ecte.4epartme/tI4 = ed.4epartme/tI4
%'
="at is CLRC
3n SQL Server !!$( SQL Server ob5ects such as user-defined functions can be created using
such 7L2 languages. &his 7L2 language support e8tends not only to user-defined functions( but
also to stored procedures and triggers. Dou can develop such 7L2 add-ons to SQL Server using
%isual Studio !!$. )
="at are synonymsC
Synonyms give you the ability to provide alternate names for database ob5ects. Dou can alias
ob5ect namesP for e8ample( using the 1mployee table as 1mp. Dou can also shorten names. &his
is especially useful when dealing with three and four part namesP for e8ample( shortening
server.database.owner.ob5ect to ob5ect.
="at is L'NQC
Language 3ntegrated Query )L3EQ* adds the ability to 4uery ob5ects using .E1& languages. &he
L3EQ to SQL ob5ectOrelational mapping )<O2'* framework provides the following basic
features,
&ools to create classes )usually called entities* mapped to database tables
7ompatibility with L3EQXs standard 4uery operations
&he Data7onte8t class( with features such as entity record monitoring( automatic SQL
statement generation( record concurrency detection( and much more
="at is 'solation LevelsC
&ransactions specify an isolation level that defines the degree to which one transaction must be
isolated from resource or data modifications made by other transactions. 3solation levels are
described in terms of which concurrency side-effects( such as dirty reads or phantom reads( are
allowed.
&ransaction isolation levels control,
Bhether locks are taken when data is read( and what type of locks are re4uested.
How long the read locks are held.
Bhether a read operation referencing rows modified by another transaction,
+locks until the e8clusive lock on the row is freed.
2etrieves the committed version of the row that e8isted at the time the statement or
transaction started.
2eads the uncommitted data modification.
="at is use o# )DC)&T ClauseC
)DC)&T clause is similar to M'N.S operation in 2racle! &he 1@71.& 4uery and '3EHS
4uery returns all rows in the first 4uery that are not returned in the second 4uery. 1ach SQL
statement within the 1@71.& 4uery and '3EHS 4uery must have the same number of fields in
the result sets with similar data types.
="at is D&at"C
@.ath uses a set of e8pressions to select nodes to be processed. &he most common e8pression
that youXll use is the location path e8pression( which returns back a set of nodes called a node
set. @.ath can use both an unabbreviated and an abbreviated synta8. &he following is the
unabbreviated synta8 for a location path,
Oa8isEame,,node&estTpredicateUOa8isEame,,node&estTpredicateU
="at is N2L2C8C
Hsing the E<L<7> 4uery optimi=er hint is generally considered good practice in order to
improve concurrency on a busy system. Bhen the E<L<7> hint is included in a S1L17&
statement( no locks are taken when data is read. &he result is a Dirty 2ead( which means that
another process could be updating the data at the e8act time you are reading it. &here are no
guarantees that your 4uery will retrieve the most recent data. &he advantage to performance is
that your reading of data will not block updates from taking place( and updates will not block
your reading of data. S1L17& statements take Shared )2ead* locks. &his means that multiple
S1L17& statements are allowed simultaneous access( but other processes are blocked from
modifying the data. &he updates will 4ueue until all the reads have completed( and reads
re4uested after the update will wait for the updates to complete. &he result to your system is
delay )blocking*.
:o* *ould you "andle error in SQL S)R?)R +EE0C
SQL Server now supports the use of &2Dc7A&7H constructs for providing rich error handling.
&2Dc7A&7H lets us build error handling at the level we need( in the way we need to( by
setting a region where if any error occurs( it will break out of the region and head to an error
handler. &he basic structure is as follows,
+1A3E &2D
FcodeG
1ED &2D
+1A3E 7A&7H
FcodeG
1ED 7A&7H
So if any error occurs in the &2D block( e8ecution is diverted to the 7A&7H block( and the error
can be dealt.
="at is R'S))RR2RC
2aise1rror generates an error message and initiates error processing for the session.
2A3S122<2 can either reference a user-defined message stored in the sys!messa$es catalog
view or build a message dynamically. &he message is returned as a server error message to the
calling application or to an associated 7A&7H block of a &2Dc7A&7H construct.
:o* to rebuild Master DatabseC
'aster database is system database and it contains information about running serverXs
configuration. Bhen SQL Server !!" is installed it usually creates master( model( msdb(
tempdb resource and distribution system database by default. <nly 'aster database is the one
which is absolutely must have database. Bithout 'aster database SQL Server cannot be started.
&his is the reason it is e8tremely important to backup 'aster database.
&o rebuild the 'aster database( 2un Setup.e8e( verify( and repair a SQL Server instance( and
rebuild the system databases. &his procedure is most often used to rebuild the master database
for a corrupted installation of SQL Server.
="at is DML DatatypeC
&he xml data type lets you store @'L documents and fragments in a SQL Server database. An
@'L fragment is an @'L instance that is missing a single top-level element. Dou can create
columns and variables of the xml type and store @'L instances in them. &he xml data type and
associated methods help integrate @'L into the relational framework of SQL Server.
="at is Data CompressionC
3n SQL S12%1 !!$ Data 7ompression comes in two flavors,
2ow 7ompression
.age 7ompression
Ro* Compression
2ow compression changes the format of physical storage of data. 3t minimi=e the metadata
)column information( length( offsets etc* associated with each record. Eumeric data types and
fi8ed length strings are stored in variable-length storage format( 5ust like %archar.
&a$e Compression
.age compression allows common data to be shared between rows for a given page. 3ts uses the
following techni4ues to compress data,
2ow compression.
.refi8 7ompression. /or every column in a page duplicate prefi8es are identified. &hese
prefi8es are saved in compression information headers )73* which resides after page
header. A reference number is assigned to these prefi8es and that reference number is
replaced where ever those prefi8es are being used.
Dictionary Compression.
Dictionary compression searches for duplicate values throughout the page and stores them in 73.
&he main difference between prefi8 and dictionary compression is that prefi8 is only restricted to
one column while dictionary is applicable to the complete page.
="at is use o# DBCC CommandsC
&he &ransact-SQL programming language provides D+77 statements that act as Database
7onsole 7ommands for SQL Server. D+77 commands are used to perform following tasks.
'aintenance tasks on database( inde8( or filegroup.
&asks that gather and display various types of information.
%alidation operations on a database( table( inde8( catalog( filegroup( or allocation of
database pages.
'iscellaneous tasks such as enabling trace flags or removing a DLL from memory.
:o* to #ind tables *it"out 'ndexesC
2un following 4uery in Query 1ditor.
5SE YdataFase=/ameWI
%'
SELE;) S;*EMA=NAME:sc.ema=id+ AS sc.ema=/ame
,/ame AS taFle=/ame
F&'M s9s.taFles
(*E&E ',KE;)2&'2E&)J:',KE;)=I4,'IsI/deDed'+ = "
'&4E& ,J sc.ema=/ame, taFle=/ameI
%'
:o* to copy t"e tables9 sc"ema and vie*s #rom one SQL Server to anot"erC
&here are multiple ways to do this.
0. IDetach Databaseb from one server and aAttach Databaseb to another server.
. 'anually script all the ob5ects using SS'S and run the script on new server.
9. Hse Bi=ard of SS'S. )2ead 'ore Here*
:o* to copy data #rom one table to anot"er tableC
&here are multiple ways to do this.
": ,NSE%T ,NTO SE4ECT
&his method is used when table is already created in the database earlier and data is to be
inserted into this table from another table. 3f columns listed in insert clause and select clause are
same( they are not re4uired to list them.
': SE4ECT ,NTO
&his method is used when table is not created earlier and needs to be created when data from one
table is to be inserted into newly created table from another table. Eew table is created with same
data types as selected columns.
)2ead 'ore Here*
="at is Catalo$ ?ie*sC
7atalog views return information that is used by the SQL Server Database 1ngine. 7atalog
%iews are the most general interface to the catalog metadata and provide the most efficient way
to obtain( transform( and present customi=ed forms of this information. All user-available catalog
metadata is e8posed through catalog views.
="at is &'?2T and .N&'?2TC
1 5i2ot Table can automatically sort( count( and total the data stored in one table or spreadsheet
and create a second table displaying the summari=ed data. &he .3%<& operator turns the values
of a specified column into column names( effectively rotating a table.
HE.3%<& table is reverse of .3%<& &able.
="at is FilestreamC
/ilestream allows you to store large ob5ects in the file system and have these files integrated
within the database. 3t enables SQL Server based applications to store unstructured data such as
documents( images( audios( videos etc. in the file system. /3L1S&21A' basically integrates the
SQL Server Database 1ngine with Eew &echnology /ile System )E&/S*P it basically stores the
data in varbinary )ma8* data type. Hsing this data type( the unstructured data is stored in the
E&/S file system and the SQL Server Database 1ngine manages the link between the /ilestream
column and the actual file located in the E&/S. Hsing &ransact SQL statements users can insert(
update( delete and select the data stored in /3L1S&21A' enabled tables.
="at is Dirty Read C
A dirty read occurs when two operations say( read and write occurs together giving the incorrect
or unedited data. Suppose( A has changed a row( but has not committed the changes. + reads the
uncommitted data but his view of the data may be wrong so that is Dirty 2ead.
="at is SQLCMDC
s4lcmd is enhanced version of the is4l and os4l and it provides way more functionality than other
two options. 3n other words s4lcmd is better replacement of is4l )which will be deprecated
eventually* and os4l )not included in SQL Server !!" 2&'*. s4lcmd can work two modes L i*
+A&7H and ii* interactive modes.
="at is $$re$ate FunctionsC
Aggregate functions perform a calculation on a set of values and return a single value. Aggregate
functions ignore EHLL values e8cept 7<HE& function. HA%3EA clause is used( along with
A2<H. +D( for filtering 4uery using aggregate values.
/ollowing functions are aggregate functions.
?-9 M'N9 C:)C8S.M%--9 S.M9 C2.NT9 STD)?9 C2.NT%B'-9 STD)?&9
-R2.&'N-9 ?R9 MD9 ?R&
="at do you mean by Table SampleC
&A+L1SA'.L1 allows you to e8tract a sampling of rows from a table in the /2<' clause.
&he rows retrieved are random and they are not in any order. &his sampling can be based on a
percentage of number of rows. Dou can use &A+L1SA'.L1 when only a sampling of rows is
necessary for the application instead of a full result set.
="at is Ro*%Number/1C
2<B6EH'+12)* returns a column as an e8pression that contains the rowXs number within the
result set. &his is only a number used in the conte8t of the result set( if the result changes( the
2<B6EH'+12)* will change.
="at are Ran6in$ FunctionsC
2anking functions return a ranking value for each row in a partition. All the ranking functions
are non-deterministic. Different 2anking functions are,
%O3_N0-*E% ;: OVE% ;<=partition_by_clause>? =order_by_clause>:
2eturns the se4uential number of a row within a partition of a result set( starting at 0 for the first
row in each partition.
%1N) ;: OVE% ;<=partition_by_clause>? =order_by_clause>:
2eturns the rank of each row within the partition of a result set.
DENSE_%1N) ;: OVE% ;<=partition_by_clause>? =order_by_clause>:
2eturns the rank of rows within the partition of a result set( without any gaps in the ranking.
="at is t"e di##erence bet*een .N'2N and .N'2N LLC
0N,ON
&he HE3<E command is used to select related information from two tables( much like the M<3E
command. However( when using the HE3<E command all selected columns need to be of the
same data type. Bith HE3<E( only distinct values are selected.
0N,ON 144
&he HE3<E ALL command is e4ual to the HE3<E command( e8cept that HE3<E ALL selects
all values.
&he difference between Hnion and Hnion all is that Hnion all will not eliminate duplicate rows(
instead it 5ust pulls all rows from all tables fitting your 4uery specifics and combines them into a
table.
="at is B4TreeC
&he database server uses a +-tree structure to organi=e inde8 information. +-&ree generally has
following types of inde8 pages or nodes,
root node$ A root node contains node pointers to branch nodes which can be only one.
branch nodes$ A branch node contains pointers to leaf nodes or other branch nodes which
can be two or more.
leaf nodes, A leaf node contains inde8 items and hori=ontal pointers to other leaf nodes
which can be many.

You might also like