You are on page 1of 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 #nstitute
standard, 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 characters
te't ,ariable(length character string. )a'i!u! 123 of te't data
Unicode strings:
Data type Description Storage
nchar(n &i'ed(length Unicode data. )a'i!u! 0,+++ characters
n$archar(n ,ariable(length Unicode data. )a'i!u! 0,+++ characters
n$archar(!a' ,ariable(length Unicode data. )a'i!u! 4/5,*.+,6-1 characters
nte'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! 123
i!age ,ariable(length binary data. )a'i!u! 123
Number types:
Data type Description Storage
tinyint Allows whole nu!bers fro! + to 144 - byte
s!allint Allows whole nu!bers between (/1,.5* and /1,.5. 1 bytes
int 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,*+* and
6,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 the
right of the deci!al point. s !ust be a $alue fro! + to p. %efault $alue
is +
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 the
right 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
Date types:
Data type Description Storage
dateti!e &ro! <anuary -, -.4/ to %ece!ber /-, 6666 with an accuracy of /.//
!illiseconds
* bytes
dateti!e1 &ro! <anuary -, +++- to %ece!ber /-, 6666 with an accuracy of -++
nanoseconds
5(* bytes
s!alldateti!e &ro! <anuary -, -6++ to <une 5, 1+.6 with an accuracy of - !inute 0 bytes
date Store a date only. &ro! <anuary -, +++- to %ece!ber /-, 6666 / bytes
ti!e Store a ti!e only to an accuracy of -++ nanoseconds /(4 bytes
dateti!eoffset :he sa!e as dateti!e1 with the addition of a ti!e =one offset *(-+
bytes
ti!esta!p Stores a uni>ue nu!ber that gets updated e$ery ti!e a row gets created
or !odified. :he ti!esta!p $alue is based upon an internal clock and
does not correspond to real ti!e. ;ach table !ay ha$e only one
ti!esta!p $ariable

Other data types:
Data type Description
s>l?$ariant Stores up to *,+++ bytes of data of $arious data types, e'cept te't, nte't, and
ti!esta!p
uni>ueidentifier Stores a globally uni>ue identifier (2U#%
'!l Stores @)L for!atted data. )a'i!u! 123
cursor Stores a reference to a cursor used for database operations
table Stores a result(set for later processing
SQL Create
SQL has a nu!ber of AB;A:; co!!ands that enable you to progra!atically create database objects
including the database, its tables and !ore.
Cere are the AB;A:; co!!ands supported by SQL Ser$erD
AB;A:; AA:#E"
AB;A:; AAAC;
AB;A:; A;LL AALAULA:#E"
AB;A:; AU3;
AB;A:; %A:A3AS;
AB;A:; %;&AUL:
AB;A:; &U"A:#E"
AB;A:; #"%;@
AB;A:; );)3;B
AB;A:; )#"#"2 )E%;L
AB;A:; FBEA;%UB;
AB;A:; BUL;
AB;A:; SAC;)A
AB;A:; S;:
AB;A:; S:A:#S:#AS
AB;A:; :A3L;
AB;A:; :B#22;B
AB;A:; U"#QU; ALUS:;B;% #"%;@
AB;A:; ,#;W
SQL Create Database
Gou can create a database using the AB;A:; %A:A3AS; co!!and.
SQL syntax
CREATE 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 AB;A:; %A:A3AS;
co!!and. Gou should check your database syste!Hs docu!entation for the specific argu!ents
supported and their usage, but hereHs an e'a!ple of supplying argu!ents when creating a database
using )icrosoftHs SQL Ser$er.
Example Code
#n this e'a!ple, we are supplying the na!e and location of the databaseHs data file and transaction
log. We are also specifying the initial si=e of these files (with the S#I; argu!ent, the !a'i!u! si=e
it can grow to (with the )A@S#I; argu!ent and the growth incre!ent of each file (using the
&#L;2BEW:C argu!ent.
USE master
GO
CREATE 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 6
GO
SQL Create Table
Gou create a table using the AB;A:; :A3L; co!!and.
SQL syntax
CREATE TAB"E table_name
($ol9mn_name_7 dataty'e,
$ol9mn_name_/ dataty'e,
---
6
Example
CREATE TAB"E !nd*,*d9al
(!nd*,*d9al!d *nt,
*rstName :ar$;ar(/556,
"astName :ar$;ar(/556,
UserName C;ar(706
6
Result
:his results in an e!pty table. Gou can now use an #"S;B: state!ent to add data to the table.
IndiidualId !irstName LastName UserName

SQL "lter Table
We will !odify the table using the AL:;B :A3L; co!!and.
Add a Column
SQL syntax
A"TER TAB"E table_name
ADD $ol9mn_name dataty'e
Example SQL Statement
A"TER TAB"E !nd*,*d9al
ADD a(e *nt
Change the Datatype
SQL syntax
A"TER TAB"E table_name
A"TER CO"UMN $ol9mn_name dataty'e
Example SQL Statement
A"TER TAB"E !nd*,*d9al
A"TER CO"UMN a(e n9mer*$
Drop a Column
H%roppingH a colu!n !eans re!o$ing or deleting that colu!n.
SQL syntax
A"TER TAB"E table_name
DROP CO"UMN $ol9mn_name
Example SQL Statement
A"TER TAB"E !nd*,*d9al
DROP CO"UMN a(e
SQL Constraints
Aonstraints are used to li!it the type of data that can go into a table.
Aonstraints can be specified when a table is created (with the AB;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
AC;AJ
%;&AUL:
SQL NOT NULL Constraint
:he "E: "ULL constraint enforces a colu!n to "E: accept "ULL $alues.:he "E: "ULL
constraint 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?#dK
colu!n and the KLast"a!eK colu!n to not accept "ULL $aluesD
AB;A:; :A3L; Fersons
(
F?#d int "E: "ULL,
Last"a!e $archar(144 "E: "ULL,
&irst"a!e $archar(144,
Address $archar(144,
Aity $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!n
or set of colu!ns. A FB#)ABG J;G constraint auto!atically has a U"#QU; constraint defined on
it. "ote that you can ha$e !any U"#QU; constraints per table, but only one FB#)ABG J;G
constraint per table.
SQL UNIQUE Constraint on CEATE TA!LE
:he following SQL creates a U"#QU; constraint on the KF?#dK colu!n when the KFersonsK table is
createdD
AB;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,
Aity $archar(144

: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
AB;A:; :A3L; Fersons
(
F?#d int "E: "ULL,
Last"a!e $archar(144 "E: "ULL,
&irst"a!e $archar(144,
Address $archar(144,
Aity $archar(144,
AE"S:BA#": uc?Ferson#% U"#QU; (F?#d,Last"a!e

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 the
following SQLD
AL:;B :A3L; Fersons
A%% 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; Fersons
A%% AE"S:BA#": uc?Ferson#% U"#QU; (F?#d,Last"a!e
To DO" a UNIQUE Constraint
:o drop a U"#QU; constraint, use the following SQLD
AL:;B :A3L; Fersons
%BEF AE"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 should
ha$e a pri!ary key, and each table can ha$e only E"; pri!ary key.
SQL "I#A$ %E$ Constraint on CEATE TA!LE
:he following SQL creates a FB#)ABG J;G on the KF?#dK colu!n when the KFersonsK table is
createdD
AB;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,
Aity $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
AB;A:; :A3L; Fersons
(
F?#d int "E: "ULL,
Last"a!e $archar(144 "E: "ULL,
&irst"a!e $archar(144,
Address $archar(144,
Aity $archar(144,
AE"S:BA#": pk?Ferson#% FB#)ABG J;G (F?#d,Last"a!e

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, use
the following SQLD
AL:;B :A3L; Fersons
A%% 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; Fersons
A%% AE"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 DO" a "I#A$ %E$ Constraint
:o drop a FB#)ABG J;G constraint, use the following SQLD
AL:;B :A3L; Fersons
%BEF AE"S:BA#": pk?Ferson#%
SQL &OEI'N %E$ Constraint
A &EB;#2" J;G in one table points to a FB#)ABG J;G in another table. LetHs illustrate the
foreign 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 -+ Sandnes
1 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 1
0 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?#dK
colu!n in the KErdersK table is a &EB;#2" J;G in the KErdersK table. :he &EB;#2" J;G
constraint is used to pre$ent actions that would destroy links between tables. :he &EB;#2" J;G
constraint also pre$ents that in$alid data for! being inserted into the foreign key colu!n, because it
has to be one of the $alues contained in the table it points to.
SQL &OEI'N %E$ Constraint on CEATE TA!LE
:he following SQL creates a &EB;#2" J;G on the KF?#dK colu!n when the KErdersK table is
createdD
AB;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;"A;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
AB;A:; :A3L; Erders
(
E?#d int "E: "ULL,
Erder"o int "E: "ULL,
F?#d int,
FB#)ABG J;G (E?#d,
AE"S:BA#": fk?FerErders &EB;#2" J;G (F?#d
B;&;B;"A;S Fersons(F?#d

SQL &OEI'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 already
created, use the following SQLD
AL:;B :A3L; Erders
A%% &EB;#2" J;G (F?#d
B;&;B;"A;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; Erders
A%% AE"S:BA#": fk?FerErders
&EB;#2" J;G (F?#d
B;&;B;"A;S Fersons(F?#d
To DO" a &OEI'N %E$ Constraint
:o drop a &EB;#2" J;G constraint, use the following SQLD
AL:;B :A3L; Erders
%BEF AE"S:BA#": fk?FerErders
SQL C(EC% Constraint
:he AC;AJ constraint is used to li!it the $alue range that can be placed in a colu!n. #f you define
a AC;AJ constraint on a single colu!n it allows only certain $alues for this colu!n. #f you define a
AC;AJ 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 CEATE TA!LE
:he following SQL creates a AC;AJ constraint on the KF?#dK colu!n when the KFersonsK table is
created. :he AC;AJ constraint specifies that the colu!n KF?#dK !ust only include integers greater
than +.
AB;A:; :A3L; Fersons
(
F?#d int "E: "ULL AC;AJ (F?#dL+,
Last"a!e $archar(144 "E: "ULL,
&irst"a!e $archar(144,
Address $archar(144,
Aity $archar(144

:o allow na!ing of a AC;AJ constraint, and for defining a AC;AJ constraint on !ultiple colu!ns,
use the following SQL synta'D
AB;A:; :A3L; Fersons
(
F?#d int "E: "ULL,
Last"a!e $archar(144 "E: "ULL,
&irst"a!e $archar(144,
Address $archar(144,
Aity $archar(144,
AE"S:BA#": chk?Ferson AC;AJ (F?#dL+ A"% AityMHSandnesH

SQL C(EC% Constraint on ALTE TA!LE


:o create a AC;AJ constraint on the KF?#dK colu!n when the table is already created, use the
following SQLD
AL:;B :A3L; Fersons
A%% AC;AJ (F?#dL+
:o allow na!ing of a AC;AJ constraint, and for defining a AC;AJ constraint on !ultiple colu!ns,
use the following SQL synta'D
AL:;B :A3L; Fersons
A%% AE"S:BA#": chk?Ferson AC;AJ (F?#dL+ A"% AityMHSandnesH
To DO" a C(EC% Constraint
:o drop a AC;AJ constraint, use the following SQLD
AL:;B :A3L; Fersons
%BEF AE"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 be
added to all new records, if no other $alue is specified.
SQL DE&AULT Constraint on CEATE TA!LE
:he following SQL creates a %;&AUL: constraint on the KAityK colu!n when the KFersonsK table is
createdD
AB;A:; :A3L; Fersons
(
F?#d int "E: "ULL,
Last"a!e $archar(144 "E: "ULL,
&irst"a!e $archar(144,
Address $archar(144,
Aity $archar(144 %;&AUL: HSandnesH

:he %;&AUL: constraint can also be used to insert syste! $alues, by using functions like
2;:%A:;(D
AB;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 KAityK colu!n when the table is already created, use the
following SQLD
AL:;B :A3L; Fersons
AL:;B AELU)" Aity S;: %;&AUL: HSA"%";SH
To DO" a DE&AULT Constraint
:o drop a %;&AUL: constraint, use the following SQLD
AL:;B :A3L; Fersons
AL:;B AELU)" Aity %BEF %;&AUL:
SQL Synta%
:he SQL synta' is >uite an easy one to grasp. )ost of the actions you need to perfor! are done with
a SQL statement.
2enerally, a SQL state!ent begins by stating what to do (for e'a!ple, "SELECT", then states which
ob&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*,*d9al
34ERE *rstName = #4omer#
SQL is not case sensiti$e ( the abo$e e'a!ples could just ha$e easily used all lowercase or all
uppercase. %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 %efinition
Language (%%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 the
following 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 you
to do this progra!!atically using %%L.
;'a!ples of %%L co!!andsD
C('"T' D"T"B"S' ( Areates 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' ( Areates a new table
"LT'( T"BL' ( )odifies the table
D(O# T"BL' ( %rops (deletes a table
: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 to
that 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;A: 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;A: state!ent is atte!pting to retrie$e all colu!ns fro! a table called Individual.Lets
ha$e a look at the table the state!ent is trying to select data fro!D
IndiidualId !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, which
contains the indi$idualHs occupation.
OccupationId IndiidualId )obTitle
- - ;ngineer
1 1 Accountant
/ / Aleaner
0 0 Attorney
4 4 Sales ;'ecuti$e
SQL statement
Select fro! both the Individual table and the Occupation table.
SE"ECT < ROM !nd*,*d9al, Occupation
34ERE Individual.*rstName = #4omer#
Result
IndiidualId!irstNameLastNameUserName OccupationIdIndiidualId)obTitle
- &red &linstone freddo - - ;ngineer
1 Co!er Si!pson ho!ey 1 1 Accountant
/ Co!er 3rown notsofa!ous / / Aleaner
0 E==y E==bournesabbath 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 statement
SE"ECT IndividualId, LastName, UserName ROM !nd*,*d9al
34ERE *rstName = #4omer#
Result
IndiidualId LastName UserName
1 Si!pson ho!ey
/ 3rown notsofa!ous
4 2ain noplacelike
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 o
34ERE i.*rstName = #4omer#
ORDER B> o-=obT*tle
SQL *here
Using the WC;B; clause, you can filter out only those records that satisfy a gi$en condition.
SQL WHERE Syntax
SE"ECT < ROM table_name
WHERE column_name = criteria
E,ample
SQL WHERE Statement
SE"ECT < ROM !nd*,*d9al
WHERE !irstName = Homer
Source a!le
IndiidualId !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
IndiidualId !irstName LastName UserName
1 Co!er Si!pson ho!ey
/ Co!er 3rown notsofa!ous
4 Co!er 2ain noplacelike
#ultiple Conditions
Gou can filter records based on !ore than one condition using operators. :wo co!!on operators are
the A"% and EB operators.
"#D $perator
:he A"% operator filters the >uery to only those records that satisfy both the first condition and the
second condition.
SE"ECT < ROM !nd*,*d9al
34ERE *rstName = #4omer#
AN" LastName = #ro$n
Result
IndiidualId !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*,*d9al
34ERE *rstName = #4omer#
OR LastName = O%%&ourne
Result
IndiidualId !irstName LastName UserName
1 Co!er Si!pson ho!ey
/ Co!er 3rown notsofa!ous
4 Co!er 2ain noplacelike
0 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 %EWEE# Syntax
S;L;A: colu!n?na!e(s
&BE) table?na!e
WC;B; colu!n?na!e
3;:W;;" $alue- A"% $alue1
E,ample
:he KFersonsK tableD
#$Id LastName !irstName "ddress City
- Cansen Ela :i!otei$n -+ Sandnes
1 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 KFettersenK
fro! the table abo$e.We use the following S;L;A: state!entD
S;L;A: P &BE) Fersons
WC;B; Last"a!e
3;: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 the
3;: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 will
not be listed (like the e'a!ple abo$e, because the 3;:W;;" operator selects fields between the
test $alues, including the first test $alue and e'cluding the last test $alue.
:hereforeD Aheck 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;A: P &BE) Fersons
WC;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
SQL In
:he SQL #" operator assists in pro$iding !ultiple $alues in WC;B; clause. :his can pro$ide $ery
useful 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 Syntax
SE"ECT < ROM table_name
34ERE $ol9mn_name IN 'value(,value),...*
E,ample
SQL statement
SE"ECT < ROM !nd*,*d9al
34ERE "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
Result
IndiidualId !irstName LastName UserName
- &red &linstone freddo
1 Co!er Si!pson ho!ey
0 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 against
the result of another >uery.
&or e'a!ple, letQs 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 are
also in the #ndi$idual table, but not all users in the #ndi$idual table are in the Fublisher table.
Source a!les
Indiidual Table
IndiidualId !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
#ublisher Table
IndiidualId "ccessLeel
- Ad!inistrator
1 Aontributor
/ Aontributor
0 Aontributor
SQL statement
SE"ECT UserName ROM !nd*,*d9al
34ERE !nd*,*d9al!d !N
'SELE+, IndividualId
!RO- .u&lis/er
WHERE AccessLevel = +ontri&utor*
Result
UserName
ho!ey
notsofa!ous
sabbath
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 Syntax
S;L;A: colu!n?na!e(s
&BE) table?na!e
WC;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 -+ Sandnes
1 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;A: state!entD
S;L;A: P &BE) Fersons
WC;B; Aity L#J; HsRH
: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 -+ Sandnes
1 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;A: state!entD
S;L;A: P &BE) Fersons
WC;B; Aity L#J; HRsH
:he result(set will look like thisD
#$Id LastName !irstName "ddress City
- Cansen Ela :i!otei$n -+ Sandnes
1 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 KFersonsK
table.
We use the following S;L;A: state!entD
S;L;A: P &BE) Fersons
WC;B; Aity 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! the
KFersonsK table, by using the "E: keyword.
We use the following S;L;A: state!entD
S;L;A: P &BE) Fersons
WC;B; Aity "E: L#J; HRta$RH
:he result(set will look like thisD
#$Id LastName !irstName "ddress City
- Cansen Ela :i!otei$n -+ Sandnes
1 S$endson :o$e 3org$n 1/ Sandnes
SQL Order By
:o sort the records by a gi$en colu!n
SQL statement
SE"ECT < ROM !nd*,*d9al
OR"ER #0 LastName
Source a!le
IndiidualId !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
IndiidualId !irstName LastName UserName
/ Co!er 3rown notsofa!ous
- &red &linstone freddo
4 Co!er 2ain noplacelike
0 E==y E==bourne sabbath
1 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 %;SA keyword.
SQL statement
SE"ECT < ROM !nd*,*d9al
ORDER B> "astName "ES+
Result
IndiidualId !irstName LastName UserName
1 Co!er Si!pson ho!ey
0 E==y E==bourne sabbath
4 Co!er 2ain noplacelike
- &red &linstone freddo
/ Co!er 3rown notsofa!ous
Sorting !y #ultiple Columns
We can sort by !ultiple colu!ns by stating each colu!n in the EB%;B 3G clause, separating each
colu!n na!e with a co!!a. SQL will first order the results by the first colu!n, then the second, and
so on for as !any colu!ns that are included in the EB%;B 3G clause.
SQL statement
SE"ECT < ROM !nd*,*d9al
ORDER B> *rstName, "astName
Result
IndiidualId !irstName LastName UserName
- &red &linstone freddo
/ Co!er 3rown notsofa!ous
4 Co!er 2ain noplacelike
1 Co!er Si!pson ho!ey
0 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 large
tables when there are thousands of records.
SQL statement
SE"ECT ,O. 1 < ROM !nd*,*d9al
Source a!le
IndiidualId !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
IndiidualId !irstName LastName UserName
- &red &linstone freddo
1 Co!er Si!pson ho!ey
/ Co!er 3rown notsofa!ous
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 the
F;BA;": keyword.
SQL statement
SE"ECT ,O. 23 .ER+EN, < ROM !nd*,*d9al
Result
IndiidualId !irstName LastName UserName
- &red &linstone freddo
1 Co!er Si!pson ho!ey
SQL TO" and the ODE !$ *lause
#f you are using the :EF clause along with the EB%;B 3G clause, the :EF clause is applied to the
ordered result set.
:herefore, if we add an EB%;B 3G to the abo$e >uery, we end up with so!ething like thisD
SQL statement
SE"ECT ,O. 23 .ER+EN, < ROM !nd*,*d9al
OR"ER #0 LastName "ES+
Result
IndiidualId !irstName LastName UserName
1 Co!er Si!pson ho!ey
0 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:#"A:
keyword.
SQL statement
SE"ECT "IS,IN+,'!irstName* ROM !nd*,*d9al
Source a!le
IndiidualId !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
Using the %#S:#"A: keyword, all custo!ers with a na!e of KCo!erK are counted as one.
!irstName
&red
Co!er
E==y
SQL !unctions
SQL has a nu!ber of functions to assist you in your database progra!!ing.
&unctions are a self contained scriptSprogra! built for a specific purpose. 2enerally, the $alue
returned by a function will depend on the conte't in which it is being used. Eften, a SQL function
will 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 SQL
state!ent
"ggregate
!unctions
Ferfor! a calculation on a set of $alues and return a single $alue. Aggregate
functions can be used in the followingD
:he select list of a S;L;A: state!ent
A AE)FU:; or AE)FU:; 3G clause
A CA,#"2 clause
Scalar !unctions :hese return a single $alue fro! a single $alue. Scalar functions are categori=ed as
followsD
Aonfiguration &unctions
Aursor &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
SQL Count
A co!!only used aggregate function in SQL is AEU":. AEU": 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 AEU":(P. AEU":(P returns e$erything ( including null $alues and duplicates.
SQL statement
SE"ECT +OUN,'4* ROM !nd*,*d9al
Source a!le
IndiidualId !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
Result
5
COUNT0column name2
#f we want to see how !any non(null $alues are in a gi$en colu!n, we use AEU":(column name
where column name is the na!e of the colu!n we want to test.
SQL statement
SE"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
Result
4
Combining COUNT ) DISTINCT
SQL statement
SE"ECT +OUN,'"IS,IN+,'!irstName** ROM !nd*,*d9al
Result
0
SQL -a%
:he SQL -". aggregate function allows us to select the highest (!a'i!u! $alue for a certain
colu!n. :he SQL -". function synta' is $ery si!ple and it looks like thisD
S;L;A: )A@(Aolu!n-
&BE) :able-
#f we use the Austo!ers table fro! our pre$ious chapters, we can select the highest date of birth with
the following SQL -". e'pressionD
S;L;A: )A@(%E3 AS )a'%E3
&BE) Austo!ers
SQL -in
:he SQL -IN aggregate function allows us to select the lowest (!ini!u! $alue for a certain
colu!n.
:he SQL -IN function synta' is $ery si!ple and it looks like thisD
S;L;A: )#"(Aolu!n-
&BE) :able-
#f we use the Austo!ers table fro! our pre$ious chapters, we can select the lowest date of birth with
the following SQL -IN e'pressionD
S;L;A: )#"(%E3 AS )in%E3
&BE) Austo!ers
SQL "g
:he SQL "/0 aggregate function selects the a$erage $alue for certain table colu!n. Ca$e a look at
the SQL "/0 synta'D
S;L;A: A,2(Aolu!n-
&BE) :able-
#f we want to find out what is the a$erage SaleA!ount in the Sales table, we will use the following
SQL "/0 state!entD
S;L;A: A,2(SaleA!ount AS A$gSaleA!ount
&BE) Sales
which will result in the following datasetD
A$gSaleA!ount
T-64../
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;A: SU)(Aolu!n-
&BE) :able-
We are going to use the Sales table to illustrate the use of SQL SU- clauseD
Sales:
Austo!er#% %ate SaleA!ount
1 4S5S1++0 T-++.11
- 4S.S1++0 T66.64
/ 4S.S1++0 T-11.64
/ 4S-/S1++0 T-++.++
0 4S11S1++0 T444.44
Aonsider the following SQL SU- state!entD
S;L;A: 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 Austo!er#% M /, you will use the
following SQL SU- state!entD
S;L;A: SU)(SaleA!ount
&BE) Sales
WC;B; Austo!er#% M /
:he result will beD
SaleA!ount
T111.64
SQL Union
:he SQL U"#E" operator co!bines two or !ore S;L;A: state!ents.
The SQL UNION Operator
:he U"#E" operator is used to co!bine the result(set of two or !ore S;L;A: state!ents.
"otice that each S;L;A: state!ent within the U"#E" !ust ha$e the sa!e nu!ber of colu!ns. :he
colu!ns !ust also ha$e si!ilar data types. Also, the colu!ns in each S;L;A: state!ent !ust be in
the sa!e order.
SQL (#&$# Syntax
S;L;A: colu!n?na!e(s &BE) table?na!e-
U"#E"
S;L;A: colu!n?na!e(s &BE) table?na!e1
Note: :he U"#E" operator selects only distinct $alues by default. :o allow duplicate $alues, use
U"#E" ALL.
SQL (#&$# "LL Syntax
S;L;A: colu!n?na!e(s &BE) table?na!e-
U"#E" ALL
S;L;A: 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 the
first S;L;A: state!ent in the U"#E".
SQL UNION E,ample
Look at the following tablesD
1'mployees$Nor+ay1D
'$ID '$Name
+- Cansen, Ela
+1 S$endson, :o$e
+/ S$endson, Stephen
+0 Fettersen, Jari
1'mployees$US"1D
'$ID '$Name
+- :urner, Sally
+1 Jent, Alark
+/ 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;A: state!entD
S;L;A: ;?"a!e &BE) ;!ployees?"orway
U"#E"
S;L;A: ;?"a!e &BE) ;!ployees?USA
:he result(set will look like thisD
'$Name
Cansen, Ela
S$endson, :o$e
S$endson, Stephen
Fettersen, Jari
:urner, Sally
Jent, Alark
Scott, Stephen
Note: :his co!!and cannot be used to list all e!ployees in "orway and USA. #n the e'a!ple abo$e
we 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: ;?"a!e &BE) ;!ployees?"orway
U"#E" ALL
S;L;A: ;?"a!e &BE) ;!ployees?USA
(esult
'$Name
Cansen, Ela
S$endson, :o$e
S$endson, Stephen
Fettersen, Jari
:urner, Sally
Jent, Alark
S$endson, Stephen
Scott, Stephen
SQL Select Into
:he SQL S;L;A: #":E state!ent can be used to create backup copies of tables.
The SQL SELECT INTO Statement
:he S;L;A: #":E state!ent selects data fro! one table and inserts it into a different table. :he
S;L;A: #":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
S;L;A: P
#":E new?table?na!e U#" e'ternaldatabaseV
&BE) old?tablena!e
Er we can select only the colu!ns we want into the new tableD
S;L;A: colu!n?na!e(s
#":E new?table?na!e U#" 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.We
use the following SQL state!entD
S;L;A: P
#":E Fersons?3ackup
&BE) Fersons
We can also use the #" clause to copy the table into another databaseD
S;L;A: P
#":E Fersons?3ackup #" H3ackup.!dbH
&BE) Fersons
We can also copy only a few fields into the new tableD
S;L;A: Last"a!e,&irst"a!e
#":E Fersons?3ackup
&BE) Fersons
SQL SELECT INTO 3 -ith a -(EE Clause
We can also add a WC;B; clause.:he following SQL state!ent creates a KFersons?3ackupK table
with only the persons who li$es in the city KSandnesKD
S;L;A: Last"a!e,&irstna!e
#":E Fersons?3ackup
&BE) Fersons
WC;B; AityMHSandnesH
SQL SELECT INTO 3 4oined Tables
Selecting data fro! !ore than one table is also possible.:he following e'a!ple creates a
KFersons?Erder?3ackupK table contains data fro! the two tables KFersonsK and KErdersKD
S;L;A: Fersons.Last"a!e,Erders.Erder"o
#":E Fersons?Erder?3ackup
&BE) Fersons
#"";B <E#" Erders
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, and
thatQs what we are going to do. Aonsider the following database table called ;!ployeeCours storing
the daily hours for each e!ployee of a factious co!panyD
;!ployee %ate Cours
<ohn S!ith 4S5S1++0 *
Allan 3abel 4S5S1++0 *
:ina Arown 4S5S1++0 *
<ohn S!ith 4S.S1++0 6
Allan 3abel 4S.S1++0 *
:ina Arown 4S.S1++0 -+
<ohn S!ith 4S*S1++0 *
Allan 3abel 4S*S1++0 *
:ina Arown 4S*S1++0 6
#f the !anager of the co!pany wants to get the si!ple su! of all hours worked by all e!ployees, he
needs to e'ecute the following SQL state!entD
S;L;A: SU) (Cours
&BE) ;!ployeeCours
3ut what if the !anager wants to get the su! of all hours for each of his e!ployeesW
:o do that he need to !odify his SQL >uery and use the SQL 0(OU# B3 state!entD
S;L;A: ;!ployee, SU) (Cours
&BE) ;!ployeeCours
2BEUF 3G ;!ployee
:he result of the SQL e'pression abo$e will be the followingD
;!ployee Cours
<ohn S!ith 14
Allan 3abel 10
:ina Arown 1.
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 SQL
A,2D
S;L;A: ;!ployee, A,2(Cours
&BE) ;!ployeeCours
2BEUF 3G ;!ployee
:he result of the SQL state!ent abo$e will beD
;!ployee Cours
<ohn S!ith *.//
Allan 3abel *
:ina Arown 6
#n our ;!ployee table we can group by the date colu!n too, to find out what is the total nu!ber of
hours worked on each of the dates into the tableD
S;L;A: %ate, SU)(Cours
&BE) ;!ployeeCours
2BEUF 3G %ate
Cere is the result of the abo$e SQL e'pressionD
%ate Cours
4S5S1++0 10
4S.S1++0 1.
4S*S1++0 14
SQL 4aing
:he SQL 4"/IN0 clause is used to restrict conditionally the output of a SQL state!ent, by a SQL
aggregate function used in your S;L;A: list of colu!ns. Gou canHt specify criteria in a SQL
WC;B; clause against a colu!n in the S;L;A: list for which SQL aggregate function is used. &or
e'a!ple the following SQL state!ent will generate an errorD
S;L;A: ;!ployee, SU) (Cours
&BE) ;!ployeeCours
WC;B; SU) (Cours L 10
2BEUF 3G ;!ployee
:he SQL 4"/IN0 clause is used to do e'actly this, to specify a condition for an aggregate function
which is used in your >ueryD
S;L;A: ;!ployee, SU) (Cours
&BE) ;!ployeeCours
2BEUF 3G ;!ployee
CA,#"2 SU) (Cours L 10
:he abo$e SQL state!ent will select all e!ployees and the su! of their respecti$e hours, as long as
this su! is greater than 10. :he result of the SQL 4"/IN0 clause can be seen belowD
;!ployee Cours
<ohn S!ith 14
:ina Arown 1.
SQL )oin
:he SQL <E#" refers to using the <E#" keyword in a SQL state!ent in order to >uery data fro! two
tables.
When you perfor! a SQL join, you specify one colu!n fro! each table to join on. :hese two
colu!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 in
a subtle way
#"";B <E#"D :his will only return rows when there is at least one row in both tables that
!atch the join condition.
L;&: EU:;B <E#" (or L;&: <E#"D :his will return rows that ha$e data in the left table
(left of the <E#" keyword, e$en if thereHs no !atching rows in the right table.
B#2C: EU:;B <E#" (or B#2C: <E#"D :his will return rows that ha$e data in the right
table (right of the <E#" keyword, e$en if thereHs no !atching rows in the left table.
&ULL EU:;B <E#" (or &ULL <E#"D :his will return all rows, as long as thereHs !atching
data in one of the tables.
4oin Synta,
Inner )oin:
SE"ECT < ROM table_name7
INNER =O!N table_name/
ON table_name7-$ol9mn_name = table_name/-$ol9mn_name
Le2t )oin:
SE"ECT < ROM table_name7
LE!, =O!N table_name/
ON table_name7-$ol9mn_name = table_name/-$ol9mn_name
(ight )oin:
SE"ECT < ROM table_name7
RI5H, =O!N table_name/
ON table_name7-$ol9mn_name = table_name/-$ol9mn_name
!ull )oin:
SE"ECT < ROM table_name7
!ULL =O!N table_name/
ON table_name7-$ol9mn_name = table_name/-$ol9mn_name
E,ample Inner 4oin Statement
SE"ECT < ROM !nd*,*d9al
!NNER =O!N P9bl*s;er
ON !nd*,*d9al-!nd*,*d9al!d = P9bl*s;er-!nd*,*d9al!d
Note: We could use table aliases instead of the full table na!e. :his will keep our state!ent shorter.
&or e'a!pleD
SE"ECT < ROM !nd*,*d9al AS Ind
!NNER =O!N P9bl*s;er AS .u&
ON Ind-!nd*,*d9al!d = .u&-!nd*,*d9al!d
SQL Inner )oin
Example SQL statement
SE"ECT < ROM !nd*,*d9al
!NNER =O!N P9bl*s;er
ON !nd*,*d9al-!nd*,*d9al!d = P9bl*s;er-!nd*,*d9al!d
34ERE !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
IndiidualId "ccessLeel
- Ad!inistrator
1 Aontributor
/ Aontributor
0 Aontributor
-+ Ad!inistrator
Result
IndiidualId !irstName LastName UserName IndiidualId "ccessLeel
1 Co!er Si!pson ho!ey 1 Aontributor
SQL Outer )oin
Le+t Outer 4oin
Use this when you only want to return rows that ha$e !atching data in the left table, e$en if thereHs
no !atching rows in the right table.
Example SQL statement
SE"ECT < ROM !nd*,*d9al AS !nd
"ET =O!N P9bl*s;er AS P9b
ON !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
IndiidualId "ccessLeel
- Ad!inistrator
1 Aontributor
/ Aontributor
0 Aontributor
-+ Ad!inistrator
Result
IndiidualId !irstName LastName UserName IndiidualId "ccessLeel
- &red &linstone freddo - Ad!inistrator
1 Co!er Si!pson ho!ey 1 Aontributor
/ Co!er 3rown notsofa!ous / Aontributor
0 E==y Esbourne sabbath 0 Aontributor
4 Co!er 2ain noplacelike "ULL "ULL
ight Outer 4oin
Use this when you only want to return rows that ha$e !atching data in the right table, e$en if thereHs
no !atching rows in the left table.
Example SQL statement
SE"ECT < ROM !nd*,*d9al AS !nd
R!G4T =O!N P9bl*s;er AS P9b
ON !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
IndiidualId "ccessLeel
- Ad!inistrator
1 Aontributor
/ Aontributor
0 Aontributor
-+ Ad!inistrator
Result
IndiidualId !irstName LastName UserName IndiidualId "ccessLeel
- &red &linstone freddo - Ad!inistrator
1 Co!er Si!pson ho!ey 1 Aontributor
/ Co!er 3rown notsofa!ous / Aontributor
0 E==y Esbourne sabbath 0 Aontributor
"ULL "ULL "ULL "ULL -+ Ad!inistrator
&ull Outer 4oin
Use this when you want to all rows, e$en if thereHs no !atching rows in the right table.
Example SQL statement
SE"ECT < ROM !nd*,*d9al AS !nd
U"" =O!N P9bl*s;er AS P9b
ON !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
IndiidualId "ccessLeel
- Ad!inistrator
1 Aontributor
/ Aontributor
0 Aontributor
-+ Ad!inistrator
Result
IndiidualId !irstName LastName UserName IndiidualId "ccessLeel
- &red &linstone freddo - Ad!inistrator
1 Co!er Si!pson ho!ey 1 Aontributor
/ Co!er 3rown notsofa!ous / Aontributor
0 E==y Esbourne sabbath 0 Aontributor
4 Co!er 2ain noplacelike "ULL "ULL
"ULL "ULL "ULL "ULL -+ Ad!inistrator
SQL Insert
:he SQL #"S;B: co!!and allows you to insert a record into a table in your database. As with the
S;L;A: 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
IndiidualId !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
"ow if we do a S;L;A: on the #ndi$idual table, we can see the new record added to the botto! of
the result set.
IndiidualId !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 3enny Cill hillbenny
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;A: state!ent.
SQL statement
UPDATE !nd*,*d9al
SET UserName = #)9nnyman#
34ERE !nd*,*d9al!d = #@#
Source a!le
IndiidualId !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 3enny Cill hillbenny
Result
"ow if we select this record, we can see the updated $alue.
IndiidualId !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 statement
UPDATE !nd*,*d9al
SET UserName = #(etser*o9s#, *rstName = #Onetree#
34ERE !nd*,*d9al!d = #@#
Result
IndiidualId !irstName LastName UserName
5 Enetree Cill getserious
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 be
deleted. Again, as with the UF%A:; state!ent, the synta' for a basic %;L;:; state!ent is si!ilar
to a S;L;A: state!ent.
SQL statement
DE"ETE
ROM !nd*,*d9al
34ERE !nd*,*d9al!d = #@#
Source a!le
IndiidualId !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 3enny Cill funny!an
Result
"ow if we select all records fro! the table, we see that record 5 has been deleted.
IndiidualId !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

You might also like