dbms labmanual sql server2008

Upload: anishnair94

Post on 03-Jun-2018

249 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/11/2019 DBMS LabManual SQL Server2008

    1/47

    SQL Introduction About SQL

    SQL stands for Structured Query Language.

    SQL is a language that enables us to work with a database. Using SQL, we can insert records, update

    records, and delete records. We can also create new database objects such as databases and tables.And we can drop (delete the!.Although SQL is an A"S# (A!erican "ational Standards #nstitutestandard, there are !any different $ersions of SQL. %ifferent database $endors ha$e their own$ariations of the language.

    SQL Server Data Types

    Character strings:

    Data type Description Storage

    char(n &i'ed length character string. )a'i!u! *,+++ characters n$archar(n ariable length character string. )a'i!u! *,+++ characters$archar(!a' ariable length character string. )a'i!u! -,+ /, 0-,*10 characterste't ariable length character string. )a'i!u! 123 of te't data

    Unicode strings:

    Data type Description Storagenchar(n &i'ed length Unicode data. )a'i!u! 0,+++ characters

    n$archar(n ariable length Unicode data. )a'i!u! 0,+++ charactersn$archar(!a' ariable length Unicode data. )a'i!u! 4/5,* +,6-1 charactersnte't ariable length Unicode data. )a'i!u! 123 of te't data

    Binary types:

    Data type Description Storage bit Allows +, -, or "ULL binary(n &i'ed length binary data. )a'i!u! *,+++ bytes$arbinary(n ariable length binary data. )a'i!u! *,+++ bytes$arbinary(!a' ariable length binary data. )a'i!u! 123i!age ariable length binary data. )a'i!u! 123

  • 8/11/2019 DBMS LabManual SQL Server2008

    2/47

    Number types:

    Data type Description Storagetinyint Allows whole nu!bers fro! + to 144 - bytes!allint Allows whole nu!bers between /1, 5* and /1, 5 1 bytesint Allows whole nu!bers between 1,-0 ,0*/,50* and 1,-0 ,0*/,50 0 bytes

    bigint Allows whole nu!bers between 6,11/,/ 1,+/5,*40, 4,*+* and6,11/,/ 1,+/5,*40, 4,*+

    * bytes

    deci!al(p,s &i'ed precision and scale nu!bers.

    Allows nu!bers fro! -+7/* 8- to -+7/* 9-.

    :he p para!eter indicates the !a'i!u! total nu!ber of digits that can be stored (both to the left and to the right of the deci!al point . p !ust be a $alue fro! - to /*. %efault is -*.

    :he s para!eter indicates the !a'i!u! nu!ber of digits stored to theright of the deci!al point. s !ust be a $alue fro! + to p. %efault $alueis +

    4 - bytes

    nu!eric(p,s &i'ed precision and scale nu!bers.

    Allows nu!bers fro! -+7/* 8- to -+7/* 9-.

    :he p para!eter indicates the !a'i!u! total nu!ber of digits that can be stored (both to the left and to the right of the deci!al point . p !ust be a $alue fro! - to /*. %efault is -*.

    :he s para!eter indicates the !a'i!u! nu!ber of digits stored to theright of the deci!al point. s !ust be a $alue fro! + to p. %efault $alue

    is +

    4 - bytes

    s!all!oney )onetary data fro! 1-0, 0*./50* to 1-0, 0*./50 0 bytes!oney )onetary data fro! 611,// ,1+/,5*4,0 .4*+* to

    611,// ,1+/,5*4,0 .4*+* bytes

    float(n &loating precision nu!ber data fro! -. 6; 8 /+* to -. 6; 8 /+*.

    :he n para!eter indicates whether the field should hold 0 or * bytes.float(10 holds a 0 byte field and float(4/ holds an * byte field.%efault $alue of n is 4/.

    0 or * bytes

    real &loating precision nu!ber data fro! /.0+; 8 /* to /.0+; 8 /* 0 bytes

  • 8/11/2019 DBMS LabManual SQL Server2008

    3/47

    Date types:

    Data type Description Storagedateti!e &ro!

  • 8/11/2019 DBMS LabManual SQL Server2008

    4/47

    SQL CreateSQL has a nu!ber of B;A:; co!!ands that enable you to progra!atically create database objectsincluding the database, its tables and !ore.

    Cere are the B;A:; co!!ands supported by SQL Ser$erD

    B;A:; A :#E" B;A:; A C; B;A:; ;LL AL ULA:#E" B;A:; U3; B;A:; %A:A3AS; B;A:; %;&AUL: B;A:; &U" :#E"

    B;A:; #"%;@ B;A:; );)3;B B;A:; )#"#"2 )E%;L B;A:; FBE ;%UB; B;A:; BUL; B;A:; S C;)A B;A:; S;: B;A:; S:A:#S:# S B;A:; :A3L; B;A:; :B#22;B B;A:; U"#QU; LUS:;B;% #"%;@ B;A:; #;W

    SQL Create DatabaseGou can create a database using the B;A:; %A:A3AS; co!!and.

    SQL syntaxCREATE DATABASE database_name

    Example Code

    CREATE DATABASE Payroll

    Adding Arguments

    :here are a nu!ber of optional argu!ents that you can supply with the B;A:; %A:A3AS;co!!and. Gou should check your database syste!Hs docu!entation for the specific argu!entssupported and their usage, but hereHs an e'a!ple of supplying argu!ents when creating a databaseusing )icrosoftHs SQL Ser$er.

    Example Code

  • 8/11/2019 DBMS LabManual SQL Server2008

    5/47

    #n this e'a!ple, we are supplying the na!e and location of the databaseHs data file and transactionlog. We are also specifying the initial si=e of these files (with the S#I; argu!ent , the !a'i!u! si=eit can grow to (with the )A@S#I; argu!ent and the growth incre!ent of each file (using theL;2BEW:C argu!ent.

    USE masterGOCREATE DATABASE Payroll

    ON( NAME = Payroll_dat, !"ENAME = #$%&'ro ram )*les&m*$roso)t s+l ser er&mss+l&data&'ayrolldat-md)#, S!.E = /0MB, MA1S!.E = 20MB, !"EGRO3T4 = 5MB 6"OG ON( NAME = #Payroll_lo #, !"ENAME = #$%&'ro ram )*les&m*$roso)t s+l ser er&mss+l&data&'ayroll-ld)#, S!.E = 70MB, MA1S!.E = 80MB, !"EGRO3T4 = 5MB 6GO

    SQL Create TableGou create a table using the B;A:; :A3L; co!!and.

    SQL syntaxCREATE TAB"E table_name($ol9mn_name_7 dataty'e,$ol9mn_name_/ dataty'e,---6

    ExampleCREATE TAB"E !nd* *d9al(!nd* *d9al!d *nt,

    *rstName :ar$;ar(/556,"astName :ar$;ar(/556,UserName C;ar(7066

    Result

    :his results in an e!pty table. Gou can now use an #"S;B: state!ent to add data to the table.

    Indi idualId !irstName LastName UserName

    http://www.quackit.com/sql/tutorial/sql_insert.cfmhttp://www.quackit.com/sql/tutorial/sql_insert.cfm
  • 8/11/2019 DBMS LabManual SQL Server2008

    6/47

    SQL "lter TableWe will !odify the table using the AL:;B :A3L; co!!and.

    Add a Column

    SQL syntaxA"TER TAB"E table_name

    ADD $ol9mn_name dataty'e

    Example SQL StatementA"TER TAB"E !nd* *d9alADD a e *nt

    Change the Datatype

    SQL syntaxA"TER TAB"E table_nameA"TER CO"UMN $ol9mn_name dataty'e

    Example SQL StatementA"TER TAB"E !nd* *d9alA"TER CO"UMN a e n9mer*$

    Drop a Column

    H%roppingH a colu!n !eans re!o$ing or deleting that colu!n.

    SQL syntaxA"TER TAB"E table_nameDROP CO"UMN $ol9mn_name

    Example SQL Statement

    A"TER TAB"E !nd* *d9alDROP CO"UMN a e

    SQL Constraintsonstraints are used to li!it the type of data that can go into a table.

    onstraints can be specified when a table is created (with the B;A:; :A3L; state!ent or after the table is created (with the AL:;B :A3L; state!ent .We will focus on the following constraintsD

    "E: "ULL U"#QU; FB#)ABG J;G &EB;#2" J;G C; J %;&AUL:

  • 8/11/2019 DBMS LabManual SQL Server2008

    7/47

    SQL NOT NULL Constraint

    :he "E: "ULL constraint enforces a colu!n to "E: accept "ULL $alues.:he "E: "ULLconstraint enforces a field to always contain a $alue. :his !eans that you cannot insert a new record,or update a record without adding a $alue to this field.:he following SQL enforces the KF?#dKcolu!n and the KLast"a!eK colu!n to not accept "ULL $aluesD

    B;A:; :A3L; Fersons(

    F?#d int "E: "ULL,Last"a!e $archar(144 "E: "ULL,&irst"a!e $archar(144 ,Address $archar(144 ,

    ity $archar(144

    SQL UNIQUE Constraint

    :he U"#QU; constraint uni>uely identifies each record in a database table.

    :he U"#QU; and FB#)ABG J;G constraints both pro$ide a guarantee for uni>ueness for a colu!nor set of colu!ns. A FB#)ABG J;G constraint auto!atically has a U"#QU; constraint defined onit. "ote that you can ha$e !any U"#QU; constraints per table, but only one FB#)ABG J;Gconstraint per table.

    SQL UNIQUE Constraint on C EATE TA!LE

    :he following SQL creates a U"#QU; constraint on the KF?#dK colu!n when the KFersonsK table iscreatedD

    B;A:; :A3L; Fersons(F?#d int "E: "ULL U"#QU;,Last"a!e $archar(144 "E: "ULL,&irst"a!e $archar(144 ,Address $archar(144 ,

    ity $archar(144

    :o allow na!ing of a U"#QU; constraint, and for defining a U"#QU; constraint on !ultiplecolu!ns, use the following SQL synta'D

    B;A:; :A3L; Fersons(F?#d int "E: "ULL,Last"a!e $archar(144 "E: "ULL,&irst"a!e $archar(144 ,Address $archar(144 ,

    ity $archar(144 ,E"S:BA#": uc?Ferson#% U"#QU; (F?#d,Last"a!e

  • 8/11/2019 DBMS LabManual SQL Server2008

    8/47

    SQL UNIQUE Constraint on ALTE TA!LE

    :o create a U"#QU; constraint on the KF?#dK colu!n when the table is already created, use thefollowing SQLD

    AL:;B :A3L; FersonsA%% U"#QU; (F?#d

    :o allow na!ing of a U"#QU; constraint, and for defining a U"#QU; constraint on !ultiple

    colu!ns, use the following SQL synta'D

    AL:;B :A3L; FersonsA%% E"S:BA#": uc?Ferson#% U"#QU; (F?#d,Last"a!e

    To D O" a UNIQUE Constraint

    :o drop a U"#QU; constraint, use the following SQLD

    AL:;B :A3L; Fersons%BEF E"S:BA#": uc?Ferson#%

    SQL " I#A $ %E$ Constraint

    :he FB#)ABG J;G constraint uni>uely identifies each record in a database table. Fri!ary keys!ust contain uni>ue $alues.A pri!ary key colu!n cannot contain "ULL $alues. ;ach table shouldha$e a pri!ary key, and each table can ha$e only E"; pri!ary key.

    SQL " I#A $ %E$ Constraint on C EATE TA!LE :he following SQL creates a FB#)ABG J;G on the KF?#dK colu!n when the KFersonsK table iscreatedD

    B;A:; :A3L; Fersons(F?#d int "E: "ULL FB#)ABG J;G,Last"a!e $archar(144 "E: "ULL,&irst"a!e $archar(144 ,Address $archar(144 ,

    ity $archar(144

    :o allow na!ing of a FB#)ABG J;G constraint, and for defining a FB#)ABG J;G constraint on!ultiple colu!ns, use the following SQL synta'D

    B;A:; :A3L; Fersons(F?#d int "E: "ULL,Last"a!e $archar(144 "E: "ULL,&irst"a!e $archar(144 ,Address $archar(144 ,

    ity $archar(144 ,E"S:BA#": pk?Ferson#% FB#)ABG J;G (F?#d,Last"a!e

  • 8/11/2019 DBMS LabManual SQL Server2008

    9/47

    SQL " I#A $ %E$ Constraint on ALTE TA!LE

    :o create a FB#)ABG J;G constraint on the KF?#dK colu!n when the table is already created, usethe following SQLD

    AL:;B :A3L; FersonsA%% FB#)ABG J;G (F?#d

    :o allow na!ing of a FB#)ABG J;G constraint, and for defining a FB#)ABG J;G constraint on!ultiple colu!ns, use the following SQL synta'D

    AL:;B :A3L; FersonsA%% E"S:BA#": pk?Ferson#% FB#)ABG J;G (F?#d,Last"a!e

    Note: #f you use the AL:;B :A3L; state!ent to add a pri!ary key, the pri!ary key colu!n(s!ust already ha$e been declared to not contain "ULL $alues (when the table was first created .

    To D O" a " I#A $ %E$ Constraint

    :o drop a FB#)ABG J;G constraint, use the following SQLD

    AL:;B :A3L; Fersons%BEF E"S:BA#": pk?Ferson#%

    SQL &O EI'N %E$ Constraint

    A &EB;#2" J;G in one table points to a FB#)ABG J;G in another table. LetHs illustrate theforeign key with an e'a!ple. Look at the following two tablesD

    :he KFersonsK tableD

    #$Id LastName !irstName "ddress City- Cansen Ela :i!otei$n -+ Sandnes1 S$endson :o$e 3org$n 1/ Sandnes/ Fettersen Jari Storgt 1+ Sta$anger

    :he KErdersK tableD

    O$Id OrderNo #$Id- *64 /1 005 * // 11045 10 10451 -

    "ote that the KF?#dK colu!n in the KErdersK table points to the KF?#dK colu!n in the KFersonsK table.:he KF?#dK colu!n in the KFersonsK table is the FB#)ABG J;G in the KFersonsK table. :he KF?#dKcolu!n in the KErdersK table is a &EB;#2" J;G in the KErdersK table. :he &EB;#2" J;Gconstraint is used to pre$ent actions that would destroy links between tables. :he &EB;#2" J;Gconstraint also pre$ents that in$alid data for! being inserted into the foreign key colu!n, because ithas to be one of the $alues contained in the table it points to.

  • 8/11/2019 DBMS LabManual SQL Server2008

    10/47

    SQL &O EI'N %E$ Constraint on C EATE TA!LE

    :he following SQL creates a &EB;#2" J;G on the KF?#dK colu!n when the KErdersK table iscreatedD

    B;A:; :A3L; Erders(E?#d int "E: "ULL FB#)ABG J;G,Erder"o int "E: "ULL,

    F?#d int &EB;#2" J;G B;&;B;" ;S Fersons(F?#d

    :o allow na!ing of a &EB;#2" J;G constraint, and for defining a &EB;#2" J;G constraint on!ultiple colu!ns, use the following SQL synta'D

    B;A:; :A3L; Erders(E?#d int "E: "ULL,Erder"o int "E: "ULL,F?#d int,FB#)ABG J;G (E?#d ,

    E"S:BA#": fk?FerErders &EB;#2" J;G (F?#dB;&;B;" ;S Fersons(F?#d

    SQL &O EI'N %E$ Constraint on ALTE TA!LE

    :o create a &EB;#2" J;G constraint on the KF?#dK colu!n when the KErdersK table is alreadycreated, use the following SQLD

    AL:;B :A3L; ErdersA%% &EB;#2" J;G (F?#dB;&;B;" ;S Fersons(F?#d

    :o allow na!ing of a &EB;#2" J;G constraint, and for defining a &EB;#2" J;G constraint on!ultiple colu!ns, use the following SQL synta'D

    AL:;B :A3L; ErdersA%% E"S:BA#": fk?FerErders&EB;#2" J;G (F?#dB;&;B;" ;S Fersons(F?#d

    To D O" a &O EI'N %E$ Constraint

    :o drop a &EB;#2" J;G constraint, use the following SQLD

    AL:;B :A3L; Erders%BEF E"S:BA#": fk?FerErders

  • 8/11/2019 DBMS LabManual SQL Server2008

    11/47

    SQL C(EC% Constraint

    :he C; J constraint is used to li!it the $alue range that can be placed in a colu!n. #f you definea C; J constraint on a single colu!n it allows only certain $alues for this colu!n. #f you define a

    C; J constraint on a table it can li!it the $alues in certain colu!ns based on $alues in other colu!ns in the row.

    SQL C(EC% Constraint on C EATE TA!LE

    :he following SQL creates a C; J constraint on the KF?#dK colu!n when the KFersonsK table iscreated. :he C; J constraint specifies that the colu!n KF?#dK !ust only include integers greater than +.

    B;A:; :A3L; Fersons(F?#d int "E: "ULL C; J (F?#d + ,Last"a!e $archar(144 "E: "ULL,&irst"a!e $archar(144 ,Address $archar(144 ,

    ity $archar(144

    :o allow na!ing of a C; J constraint, and for defining a C; J constraint on !ultiple colu!ns,use the following SQL synta'D

    B;A:; :A3L; Fersons(F?#d int "E: "ULL,Last"a!e $archar(144 "E: "ULL,&irst"a!e $archar(144 ,

    Address $archar(144 ,ity $archar(144 ,E"S:BA#": chk?Ferson C; J (F?#d + A"% ityMHSandnesH

    SQL C(EC% Constraint on ALTE TA!LE

    :o create a C; J constraint on the KF?#dK colu!n when the table is already created, use thefollowing SQLD

    AL:;B :A3L; FersonsA%% C; J (F?#d +

    :o allow na!ing of a C; J constraint, and for defining a C; J constraint on !ultiple colu!ns,use the following SQL synta'D

    AL:;B :A3L; FersonsA%% E"S:BA#": chk?Ferson C; J (F?#d + A"% ityMHSandnesH

    To D O" a C(EC% Constraint

    :o drop a C; J constraint, use the following SQLD

    AL:;B :A3L; Fersons

  • 8/11/2019 DBMS LabManual SQL Server2008

    12/47

    %BEF E"S:BA#": chk?Ferson

    SQL DE&AULT Constraint

    :he %;&AUL: constraint is used to insert a default $alue into a colu!n. :he default $alue will beadded to all new records, if no other $alue is specified.

    SQL DE&AULT Constraint on C EATE TA!LE

    :he following SQL creates a %;&AUL: constraint on the K ityK colu!n when the KFersonsK table iscreatedD

    B;A:; :A3L; Fersons(F?#d int "E: "ULL,Last"a!e $archar(144 "E: "ULL,&irst"a!e $archar(144 ,Address $archar(144 ,

    ity $archar(144 %;&AUL: HSandnesH

    :he %;&AUL: constraint can also be used to insert syste! $alues, by using functions like2;:%A:;( D

    B;A:; :A3L; Erders(E?#d int "E: "ULL,Erder"o int "E: "ULL,F?#d int,Erder%ate date %;&AUL: 2;:%A:;(

    SQL DE&AULT Constraint on ALTE TA!LE

    :o create a %;&AUL: constraint on the K ityK colu!n when the table is already created, use thefollowing SQLD

    AL:;B :A3L; FersonsAL:;B ELU)" ity S;: %;&AUL: HSA"%";SH

    To D O" a DE&AULT Constraint

    :o drop a %;&AUL: constraint, use the following SQLD

    AL:;B :A3L; FersonsAL:;B ELU)" ity %BEF %;&AUL:

  • 8/11/2019 DBMS LabManual SQL Server2008

    13/47

    SQL Synta%:he SQL synta' is >uite an easy one to grasp. )ost of the actions you need to perfor! are done witha SQL statement .

    2enerally, a SQL state!ent begins by stating what to do (for e'a!ple, "SELECT" , then states whichob&ect to do it to (for e'a!ple, using the "FROM" clause .

    SE"ECT < ROM !nd* *d9al

    #t !ay also ha$e a condition added to the end (for e'a!ple, with a WHERE clause .

    SE"ECT < ROM !nd* *d9al34ERE *rstName = #4omer#

    SQL is not case sensiti$e the abo$e e'a!ples could just ha$e easily used all lowercase or alluppercase. %ifferent progra!!ers ha$e their own preferences. &or readability purposes, !any SQL

    progra!!ers prefer to use uppercase for SQL co!!ands and lowercase for e$erything else.

    :he SQL synta' allows you to include line breaks at logical points without it breaking the state!ent.&or e'a!ple, the abo$e e'a!ple could ha$e been written all on one line or across 0 lines.

    Also, so!e database syste!s re>uire that you use a se!icolon at the end of each SQL state!ent(although this tutorial doesnHt use the se!icolon .

    D#L ) DDL

    SQL is di$ided into two !ain categoriesN %ata )anipulation Language (%)L , and %ata %efinitionLanguage (%%L . An e'planation follows.

    Data Manipulation Language (DML)

    %)L enables you to work with the data that goes into the database. %)L is used to insert, select,update, and delete records in the database. )any of your SQL state!ents will begin with one of thefollowing co!!andsD

    S'L'CT Betrie$es data fro! the database INS'(T #nserts new data into the database U#D"T' Updates e'isting data in the database D'L'T' %eletes e'isting data fro! the database

    Data Definition Language (DDL)

    Gou !ay also occasionally need to create or drop a table or other database object. SQL enables youto do this progra!!atically using %%L.

    ;'a!ples of %%L co!!andsD

    C('"T' D"T"B"S' reates a new database "LT'( D"T"B"S' )odifies the database D(O# D"T"B"S' %rops (deletes a database C('"T' T"BL' reates a new table "LT'( T"BL' )odifies the table D(O# T"BL' %rops (deletes a table

  • 8/11/2019 DBMS LabManual SQL Server2008

    14/47

    :hese are just so!e of the object classes that can be defined using %%L. As you can probably guess,the synta' is generally the sa!e for any object, although, each object will ha$e properties specific tothat object class.

    As you can see, the SQL synta' is >uite si!ple. #t is also $ery powerful synta' you can do a lot of da!age with one line of codeO

    SQL Select:he S;L; : state!ent is probably the !ost co!!only used in SQL. #t si!ply retrie$es data fro!the database.

    SE"ECT < ROM !nd* *d9al

    :his SQL S;L; : state!ent is atte!pting to retrie$e all colu!ns fro! a table called Individual .Letsha$e a look at the table the state!ent is trying to select data fro!D

    Indi idualId !irstName LastName UserName

    - &red &linstone &reddo

    1 Co!er Si!pson Co!ey

    / Co!er 3rown "otsofa!ous

    0 E==y E==bourne Sabbath

    4 Co!er 2ain "oplacelike

    Sele*t +rom #ultiple Tables

    :o do this, si!ply separate each table with a co!!a. Also >ualify any references to colu!ns by placing the table na!e in front, separated by a dot.We ha$e another table called Occupation , whichcontains the indi$idualHs occupation.

    OccupationId Indi idualId )obTitle

    - - ;ngineer

    1 1 Accountant

    / / leaner

    0 0 Attorney

    4 4 Sales ;'ecuti$e

  • 8/11/2019 DBMS LabManual SQL Server2008

    15/47

    SQL statement

    Select fro! both the Individual table and the Occupation table.

    SE"ECT < ROM !nd* *d9al , Occupation34ERE Individual. *rstName = #4omer#

    ResultIndi idualId !irstNameLastName UserName OccupationIdIndi idualId)obTitle

    - &red &linstone freddo - - ;ngineer 1 Co!er Si!pson ho!ey 1 1 Accountant/ Co!er 3rown notsofa!ous / / leaner 0 E==y E==bourne sabbath 0 0 Attorney

    4 Co!er 2ain noplacelike 4 4 Sales;'ecuti$e

    Displaying Less Columns

    :o only display those colu!ns youHre interested in, si!ply replace the asterisk (P with a co!!a

    separated list of the colu!n na!es.

    SQL statementSE"ECT IndividualId, LastName, UserName ROM !nd* *d9al34ERE *rstName = #4omer#

    ResultIndi idualId LastName UserName1 Si!pson ho!ey/ 3rown notsofa!ous4 2ain noplacelike

  • 8/11/2019 DBMS LabManual SQL Server2008

    16/47

    SQL "lias#n SQL, an alias is a na!e that you gi$e a table. :his can !ake it easier to work with table na!es especially when they are long. Gou could na!e the alias anything, but usually youHd !ake it short.

    Alias Synta, SE"ECT < ROM table_name AS alias_name

    E,ample SQL Statement SE"ECT o - obT*tle ROM !nd* *d9al AS i , O$$9'at*on AS o34ERE i. *rstName = #4omer#ORDER B> o - obT*tle

    SQL *hereUsing the WC;B; clause, you can filter out only those records that satisfy a gi$en condition.

    SQL WHERE SyntaxSE"ECT < ROM table_name

    WHERE column_name = criteria

    E,ample

    SQL WHERE StatementSE"ECT < ROM !nd* *d9al

    WHERE !irstName = Homer

    Source a!leIndi idualId !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    Result

    2i$en there are / people with the first na!e of KCo!erK, the results will look like thisD

    Indi idualId !irstName LastName UserName1 Co!er Si!pson ho!ey/ Co!er 3rown notsofa!ous4 Co!er 2ain noplacelike

  • 8/11/2019 DBMS LabManual SQL Server2008

    17/47

    #ultiple Conditions

    Gou can filter records based on !ore than one condition using operators. :wo co!!on operators arethe A"% and EB operators.

    "#D $perator

    :he A"% operator filters the >uery to only those records that satisfy both the first condition and thesecond condition.

    SE"ECT < ROM !nd* *d9al34ERE *rstName = #4omer#

    AN" LastName = #ro$n

    ResultIndi idualId !irstName LastName UserName/ Co!er 3rown notsofa!ous

    $R $perator

    :he EB operator filters the >uery to only those records that satisfy either one or the other condition.

    SE"ECT < ROM !nd* *d9al34ERE *rstName = #4omer#OR LastName = O%%&ourne

    ResultIndi idualId !irstName LastName UserName1 Co!er Si!pson ho!ey/ Co!er 3rown notsofa!ous4 Co!er 2ain noplacelike0 E==y E==bourne sabbath

    SQL Bet+een:he 3;:W;;" operator is used in a WC;B; clause to select a range of data between two $alues.

    The !ET-EEN Operator

    :he 3;:W;;" operator selects a range of data between two $alues. :he $alues can be nu!bers,te't, or dates.

    SQL %E WEE# SyntaxS;L; : colu!n?na!e(s&BE) table?na!eWC;B; colu!n?na!e3;:W;;" $alue- A"% $alue1

    E,ample

    :he KFersonsK tableD

  • 8/11/2019 DBMS LabManual SQL Server2008

    18/47

    #$Id LastName !irstName "ddress City- Cansen Ela :i!otei$n -+ Sandnes1 S$endson :o$e 3org$n 1/ Sandnes/ Fettersen Jari Storgt 1+ Sta$anger

    "ow we want to select the persons with a last na!e alphabetically between KCansenK and KFettersenKfro! the table abo$e.We use the following S;L; : state!entD

    S;L; : P &BE) FersonsWC;B; Last"a!e3;:W;;" HCansenH A"% HFettersenH

    :he result set will look like thisD

    #$Id LastName !irstName "ddress City- Cansen Ela :i!otei$n -+ Sandnes

    #n so!e databases, persons with the Last"a!e of KCansenK or KFettersenK will not be listed, because

    the 3;:W;;" operator only selects fields that are between and e'cluding the test $alues .#n other databases, persons with the Last"a!e of KCansenK or KFettersenK will be listed, because the3;:W;;" operator selects fields that are between and including the test $alues .

    And in other databases, persons with the Last"a!e of KCansenK will be listed, but KFettersenK willnot be listed (like the e'a!ple abo$e , because the 3;:W;;" operator selects fields between thetest $alues, including the first test $alue and e'cluding the last test $alue.

    :hereforeD heck how your database treats the 3;:W;;" operator.

    E,ample .

    :o display the persons outside the range in the pre$ious e'a!ple, use "E: 3;:W;;"D

    S;L; : P &BE) FersonsWC;B; Last"a!e

    "E: 3;:W;;" HCansenH A"% HFettersenH

    :he result set will look like thisD

    #$Id LastName !irstName "ddress City

    1 S$endson :o$e 3org$n 1/ Sandnes/ Fettersen Jari Storgt 1+ Sta$anger

  • 8/11/2019 DBMS LabManual SQL Server2008

    19/47

    SQL In:he SQL #" operator assists in pro$iding !ultiple $alues in WC;B; clause. :his can pro$ide $eryuseful when you need to co!pare your $alue to a list of $alues. Eften this list could be the result of a>uery fro! another table.

    SQL SyntaxSE"ECT < ROM table_name

    34ERE $ol9mn_name IN 'value(,value),...*

    E,ample

    SQL statementSE"ECT < ROM !nd* *d9al34ERE "astName !N (#S*m'son#,#O??bo9rne#,# l*nstone#6

    Source a!le

    Id !irstName LastName UserName- &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    ResultIndi idualId !irstName LastName UserName- &red &linstone freddo1 Co!er Si!pson ho!ey0 E==y E==bourne sabbath

    SQL IN and Sub /ueries

    "ow, where the SQL #" operator beco!es really useful is when you need to co!pare a $alue againstthe result of another >uery.

    &or e'a!ple, let s say we ha$e another table called KFublisherK. :his table contains users who are

    allowed to contribute to the website $ia an ad!inistration console. All users in the Fublisher table arealso in the #ndi$idual table, but not all users in the #ndi$idual table are in the Fublisher table.

    Source a!les

    Indi idual Table

    Indi idualId !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

  • 8/11/2019 DBMS LabManual SQL Server2008

    20/47

    #ublisher Table

    Indi idualId "ccessLe el

    - Ad!inistrator

    1 ontributor

    / ontributor

    0 ontributor

    SQL statementSE"ECT UserName ROM !nd* *d9al34ERE !nd* *d9al!d !N'SELE+ IndividualId !RO- u&lis/er

    WHERE AccessLevel = +ontri&utor *

    ResultUserNameho!eynotsofa!oussabbath

    SQL Li,e:he L#J; operator is used in a WC;B; clause to search for a specified pattern in a colu!n.

    The LI%E Operator

    :he L#J; operator is used to search for a specified pattern in a colu!n.

    SQL L&'E SyntaxS;L; : colu!n?na!e(s&BE) table?na!eWC;B; colu!n?na!e L#J; pattern

    LI%E Operator E,ample

    :he KFersonsK tableD

    #$Id LastName !irstName "ddress City- Cansen Ela :i!otei$n -+ Sandnes1 S$endson :o$e 3org$n 1/ Sandnes/ Fettersen Jari Storgt 1+ Sta$anger

    "ow we want to select the persons li$ing in a city that starts with KsK fro! the table abo$e.

    We use the following S;L; : state!entD

    S;L; : P &BE) FersonsWC;B; ity L#J; HsRH

  • 8/11/2019 DBMS LabManual SQL Server2008

    21/47

    :he KRK sign can be used to define wildcards (!issing letters in the pattern both before and after the pattern.

    :he result set will look like thisD

    #$Id LastName !irstName "ddress City- Cansen Ela :i!otei$n -+ Sandnes1 S$endson :o$e 3org$n 1/ Sandnes/ Fettersen Jari Storgt 1+ Sta$anger

    "e't, we want to select the persons li$ing in a city that ends with an KsK fro! the KFersonsK table.

    We use the following S;L; : state!entD

    S;L; : P &BE) FersonsWC;B; ity L#J; HRsH

    :he result set will look like thisD

    #$Id LastName !irstName "ddress City- Cansen Ela :i!otei$n -+ Sandnes1 S$endson :o$e 3org$n 1/ Sandnes

    "e't, we want to select the persons li$ing in a city that contains the pattern Kta$K fro! the KFersonsKtable.

    We use the following S;L; : state!entD

    S;L; : P &BE) FersonsWC;B; ity L#J; HRta$RH

    :he result set will look like thisD

    #$Id LastName !irstName "ddress City/ Fettersen Jari Storgt 1+ Sta$anger

    #t is also possible to select the persons li$ing in a city that "E: contains the pattern Kta$K fro! theKFersonsK table, by using the "E: keyword.

    We use the following S;L; : state!entD

    S;L; : P &BE) FersonsWC;B; ity "E: L#J; HRta$RH

    :he result set will look like thisD

    #$Id LastName !irstName "ddress City

    - Cansen Ela :i!otei$n -+ Sandnes1 S$endson :o$e 3org$n 1/ Sandnes

  • 8/11/2019 DBMS LabManual SQL Server2008

    22/47

    SQL Order By:o sort the records by a gi$en colu!n

    SQL statementSE"ECT < ROM !nd* *d9alOR"ER #0 LastName

    Source a!le

    Indi idualId !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    ResultIndi idualId !irstName LastName UserName/ Co!er 3rown notsofa!ous- &red &linstone freddo4 Co!er 2ain noplacelike0 E==y E==bourne sabbath1 Co!er Si!pson ho!ey

    Des*ending Order

    3y default, EB%;B 3G sorts the colu!n in ascending order that is, fro! lowest $alues to highest$alues. We can use the %;S keyword.

    SQL statementSE"ECT < ROM !nd* *d9alORDER B> "astName "ES+

    ResultIndi idualId !irstName LastName UserName1 Co!er Si!pson ho!ey

    0 E==y E==bourne sabbath4 Co!er 2ain noplacelike- &red &linstone freddo/ Co!er 3rown notsofa!ous

  • 8/11/2019 DBMS LabManual SQL Server2008

    23/47

    Sorting !y #ultiple Columns

    We can sort by !ultiple colu!ns by stating each colu!n in the EB%;B 3G clause, separating eachcolu!n na!e with a co!!a. SQL will first order the results by the first colu!n, then the second, andso on for as !any colu!ns that are included in the EB%;B 3G clause.

    SQL statementSE"ECT < ROM !nd* *d9alORDER B> *rstName, "astName

    ResultIndi idualId !irstName LastName UserName- &red &linstone freddo/ Co!er 3rown notsofa!ous4 Co!er 2ain noplacelike1 Co!er Si!pson ho!ey0 E==y E==bourne sabbath

    SQL Top:he :EF clause allows us to specify how !any rows to return. :his can be useful on $ery largetables when there are thousands of records.

    SQL statementSE"ECT O 1 < ROM !nd* *d9al

    Source a!le

    Indi idualId !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    Result

    Indi idualId !irstName LastName UserName- &red &linstone freddo1 Co!er Si!pson ho!ey/ Co!er 3rown notsofa!ous

  • 8/11/2019 DBMS LabManual SQL Server2008

    24/47

    Spe*i+ying a "er*entage

    We ha$e the option of specifying a percentage of the result set instead of an absolute $alue with theF;B ;": keyword.

    SQL statementSE"ECT O 23 ER+EN < ROM !nd* *d9al

    ResultIndi idualId !irstName LastName UserName- &red &linstone freddo1 Co!er Si!pson ho!ey

    SQL TO" and the O DE !$ *lause

    #f you are using the :EF clause along with the EB%;B 3G clause, the :EF clause is applied to theordered result set.

    :herefore, if we add an EB%;B 3G to the abo$e >uery, we end up with so!ething like thisD

    SQL statementSE"ECT O 23 ER+EN < ROM !nd* *d9alOR"ER #0 LastName "ES+

    ResultIndi idualId !irstName LastName UserName1 Co!er Si!pson ho!ey0 E==y E==bourne sabbath

    SQL Distinct:o find out how !any uni>ue $alues there are in a table. :o do this you can use the %#S:#" :keyword.

    SQL statementSE"ECT "IS IN+ '!irstName* ROM !nd* *d9al

    Source a!le

    Indi idualId !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

  • 8/11/2019 DBMS LabManual SQL Server2008

    25/47

    Result

    Using the %#S:#" : keyword, all custo!ers with a na!e of KCo!erK are counted as one.

    !irstName&redCo!er E==y

    SQL !unctionsSQL has a nu!ber of functions to assist you in your database progra!!ing.

    &unctions are a self contained script progra! built for a specific purpose. 2enerally, the $aluereturned by a function will depend on the conte't in which it is being used. Eften, a SQL functionwill be used within a >uery and this is what pro$ides it with itHs conte't.

    :ransact SQL pro$ides / different types of functionsD

    (o+set!unctions

    :hese return an object that can be used in place of a table reference in a SQLstate!ent

    "ggregate!unctions

    Ferfor! a calculation on a set of $alues and return a single $alue. Aggregatefunctions can be used in the followingD

    :he select list of a S;L; : state!ent A E)FU:; or E)FU:; 3G clause

    A CA #"2 clauseScalar !unctions :hese return a single $alue fro! a single $alue. Scalar functions are categori=ed as

    followsD onfiguration &unctions ursor &unctions %ate and :i!e &unctions )athe!atical &unctions )etadata &unctions Security &unctions String &unctions Syste! &unctions Syste! Statistical &unctions

    :e't and #!age &unctions

  • 8/11/2019 DBMS LabManual SQL Server2008

    26/47

    SQL CountA co!!only used aggregate function in SQL is EU":. EU": returns the nu!ber of rows that!atch the gi$en criteria.

    COUNT012

    #f we only want to see how !any records are in a table (but not actually $iew those records , we

    could use EU":(P . EU":(P returns e$erything including null $alues and duplicates.

    SQL statementSE"ECT +OUN '4* ROM !nd* *d9al

    Source a!le

    Indi idualId !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    5 3ono u1

    Result5

    COUNT0 column name 2

    #f we want to see how !any non null $alues are in a gi$en colu!n, we use EU":( column namewhere column name is the na!e of the colu!n we want to test.

    SQL statementSE"ECT +OUN 'LastName* ROM !nd* *d9al

    Source a!le

    Id !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey/ Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    5 3ono u1

  • 8/11/2019 DBMS LabManual SQL Server2008

    27/47

    Result

  • 8/11/2019 DBMS LabManual SQL Server2008

    28/47

    4

  • 8/11/2019 DBMS LabManual SQL Server2008

    29/47

    Combining COUNT ) DISTINCT

    SQL statementSE"ECT +OUN '"IS IN+ '!irstName** ROM !nd* *d9al

    Result

  • 8/11/2019 DBMS LabManual SQL Server2008

    30/47

    0

  • 8/11/2019 DBMS LabManual SQL Server2008

    31/47

    SQL -a%:he SQL -". aggregate function allows us to select the highest (!a'i!u! $alue for a certaincolu!n. :he SQL -". function synta' is $ery si!ple and it looks like thisD

  • 8/11/2019 DBMS LabManual SQL Server2008

    32/47

    S;L; : )A@( olu!n-&BE) :able-

    #f we use the usto!ers table fro! our pre$ious chapters, we can select the highest date of birth withthe following SQL -". e'pressionD

    S;L; : )A@(%E3 AS )a'%E3

    &BE) usto!ers

    SQL -in:he SQL -IN aggregate function allows us to select the lowest (!ini!u! $alue for a certaincolu!n.

    :he SQL -IN function synta' is $ery si!ple and it looks like thisD

    S;L; : )#"( olu!n-&BE) :able-

    #f we use the usto!ers table fro! our pre$ious chapters, we can select the lowest date of birth withthe following SQL -IN e'pressionD

    S;L; : )#"(%E3 AS )in%E3&BE) usto!ers

    SQL " g:he SQL "/0 aggregate function selects the a$erage $alue for certain table colu!n. Ca$e a look atthe SQL "/0 synta'D

    S;L; : A 2( olu!n-&BE) :able-

    #f we want to find out what is the a$erage SaleA!ount in the Sales table, we will use the followingSQL "/0 state!entD

    S;L; : A 2(SaleA!ount AS A$gSaleA!ount&BE) Sales

    which will result in the following datasetD

    A$gSaleA!ountT-64. /

  • 8/11/2019 DBMS LabManual SQL Server2008

    33/47

    SQL Sum:he SQL SU- aggregate function allows selecting the total for a nu!eric colu!n. :he SQL SU-synta' is displayed belowD

    S;L; : SU)( olu!n-&BE) :able-

    We are going to use the Sales table to illustrate the use of SQL SU- clauseD

    Sales:

    usto!er#% %ate SaleA!ount

    1 4 5 1++0 T-++.11

    - 4 1++0 T66.64/ 4 1++0 T-11.64

    / 4 -/ 1++0 T-++.++

    0 4 11 1++0 T444.44

    onsider the following SQL SU- state!entD

    S;L; : SU)(SaleA!ount&BE) Sales

    :his SQL state!ent will return the su! of all SaleA!ount fields and the result of it will beD

    SaleA!ount

    T6 *.5

    Ef course you can specify search criteria using the SQL WC;B; clause in your SQL SU-state!ent. #f you want to select the total sales for custo!er with usto!er#% M /, you will use thefollowing SQL SU- state!entD

    S;L; : SU)(SaleA!ount&BE) SalesWC;B; usto!er#% M /

    :he result will beD

    SaleA!ount

    T111.64

    SQL Union

  • 8/11/2019 DBMS LabManual SQL Server2008

    34/47

    :he SQL U"#E" operator co!bines two or !ore S;L; : state!ents.

    The SQL UNION Operator

    :he U"#E" operator is used to co!bine the result set of two or !ore S;L; : state!ents.

    "otice that each S;L; : state!ent within the U"#E" !ust ha$e the sa!e nu!ber of colu!ns. :hecolu!ns !ust also ha$e si!ilar data types. Also, the colu!ns in each S;L; : state!ent !ust be inthe sa!e order.

    SQL #&$# SyntaxS;L; : colu!n?na!e(s &BE) table?na!e-U"#E"S;L; : colu!n?na!e(s &BE) table?na!e1

    Note: :he U"#E" operator selects only distinct $alues by default. :o allow duplicate $alues, useU"#E" ALL.

    SQL #&$# "LL Syntax

    S;L; : colu!n?na!e(s &BE) table?na!e-U"#E" ALLS;L; : colu!n?na!e(s &BE) table?na!e1#S: :he colu!n na!es in the result set of a U"#E" are always e>ual to the colu!n na!es in thefirst S;L; : state!ent in the U"#E".

    SQL UNION E,ample

    Look at the following tablesD

    1'mployees$Nor+ay1 D

    '$ID '$Name+- Cansen, Ela+1 S$endson, :o$e+/ S$endson, Stephen+0 Fettersen, Jari

    1'mployees$US"1 D

    '$ID '$Name+- :urner, Sally+1 Jent, lark +/ S$endson, Stephen+0 Scott, Stephen

    "ow we want to list all the di22erent e!ployees in "orway and USA.

    We use the following S;L; : state!entD

    S;L; : ;?"a!e &BE) ;!ployees?"orwayU"#E"S;L; : ;?"a!e &BE) ;!ployees?USA

  • 8/11/2019 DBMS LabManual SQL Server2008

    35/47

    :he result set will look like thisD

    '$NameCansen, ElaS$endson, :o$eS$endson, StephenFettersen, Jari:urner, Sally

    Jent, lark Scott, Stephen

    Note: :his co!!and cannot be used to list all e!ployees in "orway and USA. #n the e'a!ple abo$ewe ha$e two e!ployees with e>ual na!es, and only one of the! will be listed. :he U"#E"co!!and selects only distinct $alues.

    SQL UNION ALL E,ample

    "ow we want to list all e!ployees in "orway and USAD

    S;L; : ;?"a!e &BE) ;!ployees?"orwayU"#E" ALLS;L; : ;?"a!e &BE) ;!ployees?USA

    (esult

    '$NameCansen, ElaS$endson, :o$eS$endson, StephenFettersen, Jari:urner, SallyJent, lark S$endson, Stephen

    Scott, Stephen

    SQL Select Into:he SQL S;L; : #":E state!ent can be used to create backup copies of tables.

    The SQL SELECT INTO Statement

    :he S;L; : #":E state!ent selects data fro! one table and inserts it into a different table. :heS;L; : #":E state!ent is !ost often used to create backup copies of tables.

    SQL SELEC $ Syntax

    We can select all colu!ns into the new tableD

  • 8/11/2019 DBMS LabManual SQL Server2008

    36/47

    S;L; : P#":E new?table?na!e #" e'ternaldatabaseV&BE) old?tablena!e

    Er we can select only the colu!ns we want into the new tableD

    S;L; : colu!n?na!e(s#":E new?table?na!e #" e'ternaldatabaseV&BE) old?tablena!e

    SQL SELECT INTO E,ample

    -a,e a Bac,up Copy "ow we want to !ake an e'act copy of the data in our KFersonsK table.Weuse the following SQL state!entD

    S;L; : P#":E Fersons?3ackup&BE) Fersons

    We can also use the #" clause to copy the table into another databaseD

    S;L; : P#":E Fersons?3ackup #" H3ackup.!dbH&BE) Fersons

    We can also copy only a few fields into the new tableD

    S;L; : Last"a!e,&irst"a!e#":E Fersons?3ackup&BE) Fersons

    SQL SELECT INTO 3 -ith a -(E E Clause

    We can also add a WC;B; clause.:he following SQL state!ent creates a KFersons?3ackupK tablewith only the persons who li$es in the city KSandnesKD

    S;L; : Last"a!e,&irstna!e#":E Fersons?3ackup&BE) FersonsWC;B; ityMHSandnesH

    SQL SELECT INTO 3 4oined Tables

    Selecting data fro! !ore than one table is also possible.:he following e'a!ple creates aKFersons?Erder?3ackupK table contains data fro! the two tables KFersonsK and KErdersKD

    S;L; : Fersons.Last"a!e,Erders.Erder"o#":E Fersons?Erder?3ackup&BE) Fersons#"";B

  • 8/11/2019 DBMS LabManual SQL Server2008

    37/47

    E" Fersons.F?#dMErders.F?#d

    SQL 0roup By:he SQL 0(OU# B3 state!ent is used along with the SQL aggregate functions like SU) to

    pro$ide !eans of grouping the result dataset by certain database table colu!n(s .

    :he best way to e'plain how and when to use the SQL 0(OU# B3 state!ent is by e'a!ple, andthat s what we are going to do. onsider the following database table called ;!ployeeCours storingthe daily hours for each e!ployee of a factious co!panyD

    ;!ployee %ate Cours

  • 8/11/2019 DBMS LabManual SQL Server2008

    38/47

    As you can see we ha$e only one entry for each e!ployee, because we are grouping by the;!ployee colu!n.

    :he SQL 0(OU# B3 clause can be used with other SQL aggregate functions, for e'a!ple SQLA 2D

    S;L; : ;!ployee, A 2(Cours&BE) ;!ployeeCours2BEUF 3G ;!ployee

    :he result of the SQL state!ent abo$e will beD

    ;!ployee Cours

  • 8/11/2019 DBMS LabManual SQL Server2008

    39/47

    :he SQL 4"/IN0 clause is used to do e'actly this, to specify a condition for an aggregate functionwhich is used in your >ueryD

    S;L; : ;!ployee, SU) (Cours&BE) ;!ployeeCours2BEUF 3G ;!ployeeCA #"2 SU) (Cours 10

    :he abo$e SQL state!ent will select all e!ployees and the su! of their respecti$e hours, as long asthis su! is greater than 10. :he result of the SQL 4"/IN0 clause can be seen belowD

    ;!ployee Cours

  • 8/11/2019 DBMS LabManual SQL Server2008

    40/47

    SQL )oin:he SQL uery data fro! twotables.

    When you perfor! a SQL join, you specify one colu!n fro! each table to join on. :hese twocolu!ns contain data that is shared across both tables.

    Gou can use !ultiple joins in the sa!e SQL state!ent to >uery data fro! as !any tables as you like.

    4oin Types

    %epending on your re>uire!ents, you can do an KinnerK join or an KouterK join. :hese are different ina subtle way

    #"";B

  • 8/11/2019 DBMS LabManual SQL Server2008

    41/47

    SQL Inner )oinExample SQL statementSE"ECT < ROM !nd* *d9al!NNER O!N P9bl*s;erON !nd* *d9al-!nd* *d9al!d = P9bl*s;er-!nd* *d9al!d34ERE !nd* *d9al-!nd* *d9al!d = #/#

    Source a!les

    Le2t Table

    Id !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    (ight Table

    Indi idualId "ccessLe el

    - Ad!inistrator

    1 ontributor

    / ontributor

    0 ontributor

    -+ Ad!inistrator

    ResultIndi idualId !irstName LastName UserName Indi idualId "ccessLe el1 Co!er Si!pson ho!ey 1 ontributor

  • 8/11/2019 DBMS LabManual SQL Server2008

    42/47

    SQL Outer )oinLe+t Outer 4oin

    Use this when you only want to return rows that ha$e !atching data in the left table, e$en if thereHsno !atching rows in the right table.

    Example SQL statementSE"ECT < ROM !nd* *d9al AS !nd"E T O!N P9bl*s;er AS P9bON !nd-!nd* *d9al!d = P9b-!nd* *d9al!d

    Source a!les

    Le2t Table

    Id !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    (ight Table

    Indi idualId "ccessLe el

    - Ad!inistrator 1 ontributor

    / ontributor

    0 ontributor

    -+ Ad!inistrator

    ResultIndi idualId !irstName LastName UserName Indi idualId "ccessLe el- &red &linstone freddo - Ad!inistrator

    1 Co!er Si!pson ho!ey 1 ontributor / Co!er 3rown notsofa!ous / ontributor 0 E==y Esbourne sabbath 0 ontributor 4 Co!er 2ain noplacelike "ULL "ULL

  • 8/11/2019 DBMS LabManual SQL Server2008

    43/47

    ight Outer 4oin

    Use this when you only want to return rows that ha$e !atching data in the right table, e$en if thereHsno !atching rows in the left table.

    Example SQL statementSE"ECT < ROM !nd* *d9al AS !nd

    R!G4T O!N P9bl*s;er AS P9bON !nd-!nd* *d9al!d = P9b-!nd* *d9al!d

    Source a!les

    Le2t Table

    Id !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    (ight Table

    Indi idualId "ccessLe el

    - Ad!inistrator

    1 ontributor

    / ontributor

    0 ontributor

    -+ Ad!inistrator

    ResultIndi idualId !irstName LastName UserName Indi idualId "ccessLe el- &red &linstone freddo - Ad!inistrator 1 Co!er Si!pson ho!ey 1 ontributor / Co!er 3rown notsofa!ous / ontributor 0 E==y Esbourne sabbath 0 ontributor

    "ULL "ULL "ULL "ULL -+ Ad!inistrator

  • 8/11/2019 DBMS LabManual SQL Server2008

    44/47

    &ull Outer 4oin

    Use this when you want to all rows, e$en if thereHs no !atching rows in the right table.

    Example SQL statementSE"ECT < ROM !nd* *d9al AS !nd

    U"" O!N P9bl*s;er AS P9bON !nd-!nd* *d9al!d = P9b-!nd* *d9al!d

    Source a!lesLe2t Table

    Id !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike

    (ight Table

    Indi idualId "ccessLe el

    - Ad!inistrator

    1 ontributor

    / ontributor

    0 ontributor

    -+ Ad!inistrator

    ResultIndi idualId !irstName LastName UserName Indi idualId "ccessLe el- &red &linstone freddo - Ad!inistrator 1 Co!er Si!pson ho!ey 1 ontributor / Co!er 3rown notsofa!ous / ontributor 0 E==y Esbourne sabbath 0 ontributor 4 Co!er 2ain noplacelike "ULL "ULL

    "ULL "ULL "ULL "ULL -+ Ad!inistrator

  • 8/11/2019 DBMS LabManual SQL Server2008

    45/47

    SQL Insert:he SQL #"S;B: co!!and allows you to insert a record into a table in your database. As with theS;L; : synta', the #"S;B: synta' is >uite straight forward.

    SQL statement!NSERT !NTO !nd* *d9al:A"UES ( #@#, #Benny#, #4*ll#, #;*llbenny# 6

    Source a!le

    Indi idualId !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath4 Co!er 2ain noplacelike

    Result

    "ow if we do a S;L; : on the #ndi$idual table, we can see the new record added to the botto! of the result set.

    Indi idualId !irstName LastName UserName- &red &linstone freddo

    1 Co!er Si!pson ho!ey/ Co!er 3rown notsofa!ous0 E==y E==bourne sabbath4 Co!er 2ain noplacelike5 3enny Cill hillbenny

  • 8/11/2019 DBMS LabManual SQL Server2008

    46/47

    SQL Update:he SQL UF%A:; state!ent allows you to update an e'isting record in the database.:he UF%A:;co!!and uses a WC;B; clause. #f you donHt use a WC;B; clause, all rows will be updated. #n fact,the synta' for a basic UF%A:; state!ent is $ery si!ilar to a S;L; : state!ent.

    SQL statementUPDATE !nd* *d9al

    SET UserName = #)9nnyman#34ERE !nd* *d9al!d = #@#

    Source a!le

    Indi idualId !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath

    4 Co!er 2ain noplacelike5 3enny Cill hillbenny

    Result

    "ow if we select this record, we can see the updated $alue.

    Indi idualId !irstName LastName UserName

    5 3enny Cill funny!an

    Updating #ultiple &ields

    :o update !ultiple fields, separate each field assign!ent with a co!!a.

    SQL statementUPDATE !nd* *d9alSET UserName = # etser*o9s#, *rstName = #Onetree#34ERE !nd* *d9al!d = #@#

    ResultIndi idualId !irstName LastName UserName5 Enetree Cill getserious

  • 8/11/2019 DBMS LabManual SQL Server2008

    47/47

    SQL Delete:he SQL %;L;:; state!ent allows you to delete a record fro! the database. :he %;L;:;co!!and uses a WC;B; clause. #f you donHt use a WC;B; clause, all rows in the table will bedeleted. Again, as with the UF%A:; state!ent, the synta' for a basic %;L;:; state!ent is si!ilar to a S;L; : state!ent.

    SQL statementDE"ETEROM !nd* *d9al34ERE !nd* *d9al!d = #@#

    Source a!le

    Indi idualId !irstName LastName UserName

    - &red &linstone freddo

    1 Co!er Si!pson ho!ey

    / Co!er 3rown notsofa!ous

    0 E==y E==bourne sabbath4 Co!er 2ain noplacelike

    5 3enny Cill funny!an

    Result

    "ow if we select all records fro! the table, we see that record 5 has been deleted.

    Indi idualId !irstName LastName UserName

    - &red &linstone freddo1 Co!er Si!pson ho!ey/ Co!er 3rown notsofa!ous0 E==y E==bourne sabbath4 Co!er 2ain noplacelike