Professional Documents
Culture Documents
SQ L Server Reference1
SQ L Server Reference1
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.