SQL Made Simple
-
Upload
tejas-jadhav -
Category
Documents
-
view
264 -
download
0
Transcript of SQL Made Simple
-
8/12/2019 SQL Made Simple
1/107
Guide
Introduction to SQL
SQL is a standard language for accessing and manipulating databases.
What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL is an ANSI (American National Standards Institute) standard
What Can SQL do?
SQL can execute queries against a database
SQL can retriee data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create ne! databases
SQL can create ne! tables in a database
SQL can create stored procedures in a database
SQL can create ie!s in a database
SQL can set permissions on tables" procedures" and ie!s
SQL is a Standard - BUT....
Alt#oug# SQL is an ANSI (American National Standards Institute) standard" t#ere are manydifferent ersions of t#e SQL language.
$o!eer" to be compliant !it# t#e ANSI standard" t#ey all support at least t#e ma%or commands
(suc# as S&L&'" *+A&" +&L&&" INS&," -$&,&) in a similar manner.
-
8/12/2019 SQL Made Simple
2/107
Note:ost of t#e SQL database programs also #ae t#eir o!n proprietary extensions in addition
to t#e SQL standard/
Using SQL in Your Web Site
o build a !eb site t#at s#o!s some data from a database" you !ill need t#e follo!ing0
An ,+1S database program (i.e. S Access" SQL Serer" ySQL)
A serer2side scripting language" li3e *$* or AS*
SQL
$L 4 'SS
RDBMS
,+1S stands for ,elational +atabase anagement System.
,+1S is t#e basis for SQL" and for all modern database systems li3e S SQL Serer" I1+15" 6racle" ySQL" and icrosoft Access.
#e data in ,+1S is stored in database ob%ects called tables.
A table is a collections of related data entries and it consists of columns and ro!s.
Database Tabes
A database most often contains one or more tables. &ac# table is identified by a name (e.g.7'ustomers7 or 76rders7). ables contain records (ro!s) !it# data.
1elo! is an example of a table called 7*ersons70
!"#d LastNa$e %irstNa$e &ddress Cit'
8 $ansen 6la imotein 89 Sandnes
5 Sendson oe 1orgn 5: Sandnes
: *ettersen ;ari Storgt 59 Staanger
#e table aboe contains t#ree records (one for eac# person) and fie columns (*
-
8/12/2019 SQL Made Simple
3/107
SQL State$ents
ost of t#e actions you need to perform on a database are done !it# SQL statements.
#e follo!ing SQL statement !ill select all t#e records in t#e 7*ersons7 table0
S&L&' > =,6 *ersons
In t#is tutorial !e !ill teac# you all about t#e different SQL statements.
(ee) in Mind That...
SQL is not case sensitie
Se$i*oon a+ter SQL State$ents?
Some database systems require a semicolon at t#e end of eac# SQL statement.
Semicolon is t#e standard !ay to separate eac# SQL statement in database systems t#at allo!more t#an one SQL statement to be executed in t#e same call to t#e serer.
-e are using S Access and SQL Serer 5999 and !e do not #ae to put a semicolon after eac#
SQL statement" but some database programs force you to use it.
SQL DML and DDL
SQL can be diided into t!o parts0 #e +ata anipulation Language (+L) and t#e +ata+efinition Language (++L).
#e query and update commands form t#e +L part of SQL0
S,L,CT2 extracts data from a database
U!D&T,2 updates data in a database
D,L,T,2 deletes data from a database
#NS,RT #NT2 inserts ne! data into a database
#e ++L part of SQL permits database tables to be created or deleted. It also define indexes(3eys)" specify lin3s bet!een tables" and impose constraints bet!een tables. #e most important
++L statements in SQL are0
-
8/12/2019 SQL Made Simple
4/107
CR,&T, D&T&B&S,2 creates a ne! database
<,R D&T&B&S,2 modifies a database
CR,&T, T&BL,2 creates a ne! table
<,R T&BL,2 modifies a table
DR! T&BL,2 deletes a table
CR,&T, #ND,2 creates an index (searc# 3ey)
DR! #ND,2 deletes an index
SQL SELECT Statement
#is c#apter !ill explain t#e S&L&' and t#e S&L&' > statements.
The SQL S,L,CT State$ent
#e S&L&' statement is used to select data from a database.
#e result is stored in a result table" called t#e result2set.
SQL SELECT Syntax
SELECT column_name(s)FROM table_name
and
SELECT * FROM table_name
Note:SQL is not case sensitie. S&L&' is t#e same as select.
&n SQL S,L,CT ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
-
8/12/2019 SQL Made Simple
5/107
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
No! !e !ant to select t#e content of t#e columns named 7LastName7 and 7=irstName7 from t#e
table aboe.
-e use t#e follo!ing S&L&' statement0
SELECT Last'ameFi"st'ame FROM %e"sons
#e result2set !ill loo3 li3e t#is0
LastName FirstName
Hansen Ola
Svendson Tove
%ette"sen &a"i
S,L,CT 0 ,/a$)e
No! !e !ant to select all t#e columns from t#e 7*ersons7 table.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
Ti):#e asteris3 (>) is a quic3 !ay of selecting all columns/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
-
8/12/2019 SQL Made Simple
6/107
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
SQL SELECT DISTINCT Statement
#is c#apter !ill explain t#e S&L&' +ISIN' statement.
The SQL S,L,CT D#ST#NCT State$ent
In a table" some of t#e columns may contain duplicate alues. #is is not a problem" #o!eer"
sometimes you !ill !ant to list only t#e different (distinct) alues in a table.
#e +ISIN' 3ey!ord can be used to return only distinct (different) alues.
SQL SELECT DISTINCT Syntax
SELECT ST'CT column_name(s)
FROM table_name
S,L,CT D#ST#NCT ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
No! !e !ant to select only t#e distinct alues from t#e column named 7'ity7 from t#e table
aboe.
-e use t#e follo!ing S&L&' statement0
SELECT ST'CT Cit+ FROM %e"sons
-
8/12/2019 SQL Made Simple
7/107
#e result2set !ill loo3 li3e t#is0
City
Sandnes
Stavan#e"
SQL WHERE Clause
#e -$&,& clause is used to filter records.
The W1,R, Cause
#e -$&,& clause is used to extract only t#ose records t#at fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name(s)
FROM table_name,HERE column_name o-e"ato" value
W1,R, Cause ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
-
8/12/2019 SQL Made Simple
8/107
No! !e !ant to select only t#e persons liing in t#e city 7Sandnes7 from t#e table aboe.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Cit+./Sandnes/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
Quotes &round Te/t %ieds
SQL uses single quotes around text alues (most database systems !ill also accept doublequotes).
Alt#oug#" numeric alues s#ould not be enclosed in quotes.
=or text alues0
Tis is co""ect
SELECT * FROM %e"sons ,HERE Fi"st'ame./Tove/
Tis is 2"on#
SELECT * FROM %e"sons ,HERE Fi"st'ame.Tove
=or numeric alues0
Tis is co""ect
SELECT * FROM %e"sons ,HERE 3ea".1456
Tis is 2"on#
-
8/12/2019 SQL Made Simple
9/107
SELECT * FROM %e"sons ,HERE 3ea"./1456/
)erators &o2ed in the W1,R, Cause-it# t#e -$&,& clause" t#e follo!ing operators can be used0
Operator Description
. E7ual
89 'ot e7ual
9 :"eate" tan
8 Less tan
9. :"eate" tan o" e7ual
8. Less tan o" e7ual
!ET,EE
'!et2een an inclusive "an#e
L&E Sea"c ;o" a -atte"n
' ; +ou
-
8/12/2019 SQL Made Simple
10/107
#e 6, operator displays a record if eit#er t#e first condition or t#e second condition is true.
&ND )erator ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
No! !e !ant to select only t#e persons !it# t#e first name equal to 7oe7 AN+ t#e last name
equal to 7Sendson70
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Fi"st'ame./Tove/
>' Last'ame./Svendson/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
Svendson Tove !o"#vn $ Sandnes
R )erator ,/a$)e
No! !e !ant to select only t#e persons !it# t#e first name equal to 7oe7 6, t#e first name
equal to 76la70
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Fi"st'ame./Tove/
OR Fi"st'ame./Ola/
-
8/12/2019 SQL Made Simple
11/107
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
Co$bining &ND 3 R
Cou can also combine AN+ and 6, (use parent#esis to form complex expressions).
No! !e !ant to select only t#e persons !it# t#e last name equal to 7Sendson7 AN+ t#e firstname equal to 7oe7 6, to 76la70
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons ,HERE
Last'ame./Svendson/
>' (Fi"st'ame./Tove/ OR Fi"st'ame./Ola/)
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
Svendson Tove !o"#vn $ Sandnes
SQL ORDER !" #ey$ord
#e 6,+&, 1C 3ey!ord is used to sort t#e result2set.
The RD,R BY (e'2ord
#e 6,+&, 1C 3ey!ord is used to sort t#e result2set by a specified column.
#e 6,+&, 1C 3ey!ord sort t#e records in ascending order by default.
If you !ant to sort t#e records in a descending order" you can use t#e +&S' 3ey!ord.
-
8/12/2019 SQL Made Simple
12/107
SQL ORDER !" Syntax
SELECT column_name(s)
FROM table_name
ORER !3 column_name(s) >SC?ESC
RD,R BY ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
@ 'ilsen Tom Ain#vn $ Stavan#e"
No! !e !ant to select all t#e persons from t#e table aboe" #o!eer" !e !ant to sort t#e persons
by t#eir last name.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons ORER !3 Last'ame
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
@ 'ilsen Tom Ain#vn $ Stavan#e"
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
Svendson Tove !o"#vn $ Sandnes
RD,R BY D,SC ,/a$)e
-
8/12/2019 SQL Made Simple
13/107
No! !e !ant to select all t#e persons from t#e table aboe" #o!eer" !e !ant to sort t#e persons
descending by t#eir last name.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sonsORER !3 Last'ame ESC
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
@ 'ilsen Tom Ain#vn $ Stavan#e"
1 Hansen Ola Timoteivn 10 Sandnes
SQL INSERT INTO Statement
#e INS&, IN6 statement is used to insert ne! records in a table.
The #NS,RT #NT State$ent
#e INS&, IN6 statement is used to insert a ne! ro! in a table.
SQL INSERT INTO Syntax
It is possible to !rite t#e INS&, IN6 statement in t!o forms.
#e first form doesnDt specify t#e column names !#ere t#e data !ill be inserted" only t#eir
alues0
'SERT 'TO table_name
A>LBES (value1 value value$)
-
8/12/2019 SQL Made Simple
14/107
#e second form specifies bot# t#e column names and t#e alues to be inserted0
'SERT 'TO table_name (column1 column column$)
A>LBES (value1 value value$)
SQL #NS,RT #NT ,/a$)e
-e #ae t#e follo!ing 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
No! !e !ant to insert a ne! ro! in t#e 7*ersons7 table.
-e use t#e follo!ing SQL statement0
'SERT 'TO %e"sons
A>LBES (@/'ilsen/ /Doan/ /!a
-
8/12/2019 SQL Made Simple
15/107
#e follo!ing SQL statement !ill add a ne! ro!" but only add data in t#e 7*LBES (6 /Tessem/ /Da
-
8/12/2019 SQL Made Simple
16/107
SQL U!D&T, ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
@ 'ilsen Doan !aTE %e"sons
SET >dd"ess./'issestien 5/ Cit+./Sandnes/
,HERE Last'ame./Tessem/ >' Fi"st'ame./Da
-
8/12/2019 SQL Made Simple
17/107
B%>TE %e"sons
SET >dd"ess./'issestien 5/ Cit+./Sandnes/
#e 7*ersons7 table !ould #ae loo3ed li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola 'issestien 5 Sandnes
Svendson Tove 'issestien 5 Sandnes
$ %ette"sen &a"i 'issestien 5 Sandnes
@ 'ilsen Doan 'issestien 5 Sandnes
6 Tessem Da
-
8/12/2019 SQL Made Simple
18/107
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
@ 'ilsen Doan !a
-
8/12/2019 SQL Made Simple
19/107
Note:1e ery careful !#en deleting records. Cou cannot undo t#is statement/
SQL TO Clause
The T! Cause
#e 6* clause is used to specify t#e number of records to return.
#e 6* clause can be ery useful on large tables !it# t#ousands of records. ,eturning a largenumber of records can impact on performance.
Note:Not all database systems support t#e 6* clause.
SQL Ser'er SyntaxSELECT TO% numbe"?-e"cent column_name(s)
FROM table_name
SQL S,L,CT T! ,4ui5aent in M'SQL and ra*e
(ySQL Syntax
SELECT column_name(s)
FROM table_name
LMT numbe"
Examle
SELECT *
FROM %e"sons
LMT 6
Oracle Syntax
SELECT column_name(s)
FROM table_name,HERE RO,'BM 8. numbe"
Examle
SELECT *
FROM %e"sons ,HERE RO,'BM 8.6
-
8/12/2019 SQL Made Simple
20/107
SQL T! ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
@ 'ilsen Tom Ain#vn $ Stavan#e"
No! !e !ant to select only t#e t!o first records in t#e table aboe.
-e use t#e follo!ing S&L&' statement0
SELECT TO% * FROM %e"sons
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
SQL T! !,RC,NT ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
-
8/12/2019 SQL Made Simple
21/107
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
@ 'ilsen Tom Ain#vn $ Stavan#e"
No! !e !ant to select only F9 of t#e records in t#e table aboe.
-e use t#e follo!ing S&L&' statement0
SELECT TO% 60 %ERCE'T * FROM %e"sons
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
SQL LI#E Oerator
#e LI;& operator is used in a -$&,& clause to searc# for a specified pattern in a column.
The L#(, )erator
#e LI;& operator is used to searc# for a specified pattern in a column.
SQL LI#E Syntax
SELECT column_name(s)
FROM table_name
,HERE column_name L&E -atte"n
L#(, )erator ,/a$)e
#e 7*ersons7 table0
-
8/12/2019 SQL Made Simple
22/107
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
No! !e !ant to select t#e persons liing in a city t#at starts !it# 7s7 from t#e table aboe.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Cit+ L&E /sG/
#e 77 sign can be used to define !ildcards (missing letters in t#e pattern) bot# before andafter t#e pattern.
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
Next" !e !ant to select t#e persons liing in a city t#at ends !it# an 7s7 from t#e 7*ersons7 table.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Cit+ L&E /Gs/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
-
8/12/2019 SQL Made Simple
23/107
Next" !e !ant to select t#e persons liing in a city t#at contains t#e pattern 7ta7 from t#e
7*ersons7 table.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons,HERE Cit+ L&E /GtavG/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
It is also possible to select t#e persons liing in a city t#at N6 contains t#e pattern 7ta7 from
t#e 7*ersons7 table" by using t#e N6 3ey!ord.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Cit+ 'OT L&E /GtavG/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
SQL Wildcards
SQL !ildcards can be used !#en searc#ing for data in a database.
SQL Wid*ards
SQL !ildcards can substitute for one or more c#aracters !#en searc#ing for data in a database.
-
8/12/2019 SQL Made Simple
24/107
SQL !ildcards must be used !it# t#e SQL LI;& operator.
-it# SQL" t#e follo!ing !ildcards can be used0
Wildcard Description
G > substitute ;o" e"o o" mo"e ca"acte"s
_ > substitute ;o" e=actl+ one ca"acte"
Ica"listJ >n+ sin#le ca"acte" in ca"list
IKca"listJ
or
H/c#arlist
>n+ sin#le ca"acte" not in ca"list
SQL Wid*ard ,/a$)es
-e #ae t#e follo!ing 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
Using the 6 Wid*ard
No! !e !ant to select t#e persons liing in a city t#at starts !it# 7sa7 from t#e 7*ersons7 table.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Cit+ L&E /saG/
#e result2set !ill loo3 li3e t#is0
-
8/12/2019 SQL Made Simple
25/107
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
Next" !e !ant to select t#e persons liing in a city t#at contains t#e pattern 7nes7 from t#e
7*ersons7 table.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Cit+ L&E /GnesG/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
Using the " Wid*ardNo! !e !ant to select t#e persons !it# a first name t#at starts !it# any c#aracter" follo!ed by7la7 from t#e 7*ersons7 table.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Fi"st'ame L&E /_la/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
-
8/12/2019 SQL Made Simple
26/107
Next" !e !ant to select t#e persons !it# a last name t#at starts !it# 7S7" follo!ed by any
c#aracter" follo!ed by 7end7" follo!ed by any c#aracter" follo!ed by 7on7 from t#e 7*ersons7
table.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Last'ame L&E /S_end_on/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
Svendson Tove !o"#vn $ Sandnes
Using the 7*harist8 Wid*ard
No! !e !ant to select t#e persons !it# a last name t#at starts !it# 7b7 or 7s7 or 7p7 from t#e
7*ersons7 table.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Last'ame L&E /Ibs-JG/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
Next" !e !ant to select t#e persons !it# a last name t#at do not start !it# 7b7 or 7s7 or 7p7 from
t#e 7*ersons7 table.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Last'ame L&E /Ibs-JG/
-
8/12/2019 SQL Made Simple
27/107
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
SQL IN Oerator
The #N )erator
#e IN operator allo!s you to specify multiple alues in a -$&,& clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
,HERE column_name ' (value1value)
#N )erator ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
No! !e !ant to select t#e persons !it# a last name equal to 7$ansen7 or 7*ettersen7 from t#etable aboe.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons
,HERE Last'ame ' (/Hansen//%ette"sen/)
-
8/12/2019 SQL Made Simple
28/107
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
SQL !ETWEEN Oerator
#e 1&-&&N operator is used in a -$&,& clause to select a range of data bet!een t!o
alues.
The B,TW,,N )erator
#e 1&-&&N operator selects a range of data bet!een t!o alues. #e alues can be
numbers" text" or dates.
SQL !ETWEEN Syntax
SELECT column_name(s)
FROM table_name
,HERE column_name
!ET,EE' value1 >' value
B,TW,,N )erator ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
-
8/12/2019 SQL Made Simple
29/107
No! !e !ant to select t#e persons !it# a last name alp#abetically bet!een 7$ansen7 and
7*ettersen7 from t#e table aboe.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM %e"sons,HERE Last'ame
!ET,EE' /Hansen/ >' /%ette"sen/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Note:#e 1&-&&N operator is treated differently in different databases.
In some databases" persons !it# t#e LastName of 7$ansen7 or 7*ettersen7 !ill not be listed"
because t#e 1&-&&N operator only selects fields t#at are bet!een and excluding t#e testalues).
In ot#er databases" persons !it# t#e LastName of 7$ansen7 or 7*ettersen7 !ill be listed" because
t#e 1&-&&N operator selects fields t#at are bet!een and including t#e test alues).
And in ot#er databases" persons !it# t#e LastName of 7$ansen7 !ill be listed" but 7*ettersen7!ill not be listed (li3e t#e example aboe)" because t#e 1&-&&N operator selects fields
bet!een t#e test alues" including t#e first test alue and excluding t#e last test alue.
#erefore0 '#ec3 #o! your database treats t#e 1&-&&N operator.
,/a$)e 9
o display t#e persons outside t#e range in t#e preious example" use N6 1&-&&N0
SELECT * FROM %e"sons
,HERE Last'ame'OT !ET,EE' /Hansen/ >' /%ette"sen/
#e result2set !ill loo3 li3e t#is0
P_Id LastName FirstName Address City
-
8/12/2019 SQL Made Simple
30/107
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
SQL Alias
-it# SQL" an alias name can be gien to a table or to a column.
SQL &ias
Cou can gie a table or a column anot#er name by using an alias. #is can be a good t#ing to doif you #ae ery long or complex table names or column names.
An alias name could be anyt#ing" but usually it is s#ort.
SQL Alias Syntax )or Ta*les
SELECT column_name(s)
FROM table_name
>S alias_name
SQL Alias Syntax )or ColumnsSELECT column_name >S alias_name
FROM table_name
&ias ,/a$)e
Assume !e #ae a table called 7*ersons7 and anot#er table called 7*roductS -
-
8/12/2019 SQL Made Simple
31/107
%"oduct_O"de"s >S -o
,HERE -Last'ame./Hansen/ >' -Fi"st'ame./Ola/
#e same S&L&' statement !it#out aliases0
SELECT %"oduct_O"de"sO"de" %e"sonsLast'ame %e"sonsFi"st'ame
FROM %e"sons
%"oduct_O"de"s
,HERE %e"sonsLast'ame./Hansen/ >' %e"sonsFi"st'ame./Ola/
As youDll see from t#e t!o S&L&' statements aboeJ aliases can ma3e queries easier to bot#!rite and to read.
SQL +oins
SQL %oins are used to query data from t!o or more tables" based on a relations#ip bet!een
certain columns in t#ese tables.
SQL #N
#e E6IN 3ey!ord is used in an SQL statement to query data from t!o or more tables" based on
a relations#ip bet!een certain columns in t#ese tables.
ables in a database are often related to eac# ot#er !it# 3eys.
A primary 3ey is a column (or a combination of columns) !it# a unique alue for eac# ro!.
&ac# primary 3ey alue must be unique !it#in t#e table. #e purpose is to bind data toget#er"
across tables" !it#out repeating all of t#e data in eery table.
Loo3 at t#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
-
8/12/2019 SQL Made Simple
32/107
Note t#at t#e 7*
-
8/12/2019 SQL Made Simple
33/107
SQL INNER +OIN Syntax
SELECT column_name(s)
FROM table_name1
''ER DO' table_name
O' table_name1column_name.table_namecolumn_name
!S:INN&, E6IN is t#e same as E6IN.
SQL #NN,R #N ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
#e 76rders7 table0
O_Id OrderNo P_Id
1 46 $
@@5 $
$ @65 1
@ @65 1
6 $@5@ 16
No! !e !ant to list all t#e persons !it# any orders.
-e use t#e follo!ing S&L&' statement0
SELECT %e"sonsLast'ame %e"sonsFi"st'ame O"de"sO"de"'o
FROM %e"sons
''ER DO' O"de"s
O' %e"sons%_d.O"de"s%_d
-
8/12/2019 SQL Made Simple
34/107
ORER !3 %e"sonsLast'ame
#e result2set !ill loo3 li3e t#is0
LastName FirstName OrderNo
Hansen Ola @65
Hansen Ola @65
%ette"sen &a"i 46
%ette"sen &a"i @@5
#e INN&, E6IN 3ey!ord return ro!s !#en t#ere is at least one matc# in bot# tables. If t#ere
are ro!s in 7*ersons7 t#at do not #ae matc#es in 76rders7" t#ose ro!s !ill N6 be listed.
SQL LE,T +OIN #ey$ord
SQL L,%T #N (e'2ord
#e L&= E6IN 3ey!ord returns all ro!s from t#e left table (table
-
8/12/2019 SQL Made Simple
35/107
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
#e 76rders7 table0
O_Id OrderNo P_Id
1 46 $
@@5 $
$ @65 1
@ @65 1
6 $@5@ 16
No! !e !ant to list all t#e persons and t#eir orders 2 if any" from t#e tables aboe.
-e use t#e follo!ing S&L&' statement0
SELECT %e"sonsLast'ame %e"sonsFi"st'ame O"de"sO"de"'o
FROM %e"sons
LEFT DO' O"de"sO' %e"sons%_d.O"de"s%_d
ORER !3 %e"sonsLast'ame
#e result2set !ill loo3 li3e t#is0
LastName FirstName OrderNo
Hansen Ola @65
Hansen Ola @65
%ette"sen &a"i 46
%ette"sen &a"i @@5
Svendson Tove
-
8/12/2019 SQL Made Simple
36/107
#e L&= E6IN 3ey!ord returns all t#e ro!s from t#e left table (*ersons)" een if t#ere are no
matc#es in t#e rig#t table (6rders).
SQL RI-HT +OIN #ey$ord
SQL R#;1T #N (e'2ord
#e ,IG$ E6IN 3ey!ord ,eturn all ro!s from t#e rig#t table (table
-
8/12/2019 SQL Made Simple
37/107
@ @65 1
6 $@5@ 16
No! !e !ant to list all t#e orders !it# containing persons 2 if any" from t#e tables aboe.
-e use t#e follo!ing S&L&' statement0
SELECT %e"sonsLast'ame %e"sonsFi"st'ame O"de"sO"de"'o
FROM %e"sons
R:HT DO' O"de"s
O' %e"sons%_d.O"de"s%_d
ORER !3 %e"sonsLast'ame
#e result2set !ill loo3 li3e t#is0
LastName FirstName OrderNo
Hansen Ola @65
Hansen Ola @65
%ette"sen &a"i 46
%ette"sen &a"i @@5
$@5@
#e ,IG$ E6IN 3ey!ord returns all t#e ro!s from t#e rig#t table (6rders)" een if t#ere are no
matc#es in t#e left table (*ersons).
SQL ,%LL +OIN #ey$ord
SQL %ULL #N (e'2ord#e =LL E6IN 3ey!ord return ro!s !#en t#ere is a matc# in one of t#e tables.
SQL ,%LL +OIN Syntax
SELECT column_name(s)
FROM table_name1
-
8/12/2019 SQL Made Simple
38/107
FBLL DO' table_name
O' table_name1column_name.table_namecolumn_name
SQL %ULL #N ,/a$)e
#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
#e 76rders7 table0
O_Id OrderNo P_Id
1 46 $
@@5 $
$ @65 1
@ @65 1
6 $@5@ 16
No! !e !ant to list all t#e persons and t#eir orders" and all t#e orders !it# t#eir persons.
-e use t#e follo!ing S&L&' statement0
SELECT %e"sonsLast'ame %e"sonsFi"st'ame O"de"sO"de"'o
FROM %e"sonsFBLL DO' O"de"s
O' %e"sons%_d.O"de"s%_d
ORER !3 %e"sonsLast'ame
#e result2set !ill loo3 li3e t#is0
-
8/12/2019 SQL Made Simple
39/107
LastName FirstName OrderNo
Hansen Ola @65
Hansen Ola @65
%ette"sen &a"i 46
%ette"sen &a"i @@5
Svendson Tove
$@5@
#e =LL E6IN 3ey!ord returns all t#e ro!s from t#e left table (*ersons)" and all t#e ro!s fromt#e rig#t table (6rders). If t#ere are ro!s in 7*ersons7 t#at do not #ae matc#es in 76rders7" or if
t#ere are ro!s in 76rders7 t#at do not #ae matc#es in 7*ersons7" t#ose ro!s !ill be listed as!ell.
SQL %NION Oerator
#e SQL NI6N operator combines t!o or more S&L&' statements.
The SQL UN#N )erator
#e NI6N operator is used to combine t#e result2set of t!o or more S&L&' statements.
Notice t#at eac# S&L&' statement !it#in t#e NI6N must #ae t#e same number of columns.
#e columns must also #ae similar data types. Also" t#e columns in eac# S&L&' statement
must be in t#e same order.
SQL %NION Syntax
SELECT column_name(s) FROM table_name1
B'O'SELECT column_name(s) FROM table_name
Note:#e NI6N operator selects only distinct alues by default. o allo! duplicate alues"
use NI6N ALL.
-
8/12/2019 SQL Made Simple
40/107
SQL %NION ALL Syntax
SELECT column_name(s) FROM table_name1
B'O' >LL
SELECT column_name(s) FROM table_name
!S:#e column names in t#e result2set of a NI6N are al!ays equal to t#e column names in t#e
first S&L&' statement in t#e NI6N.
SQL UN#N ,/a$)e
Loo3 at t#e follo!ing tables0
-
8/12/2019 SQL Made Simple
41/107
SELECT E_'ame FROM Em-lo+ees_BS>
#e result2set !ill loo3 li3e t#is0
E_Name
Hansen Ola
Svendson Tove
Svendson Ste-en
%ette"sen &a"i
Tu"ne" Sall+
&ent Cla"LL
SELECT E_'ame FROM Em-lo+ees_BS>
Resut
E_Name
Hansen Ola
Svendson Tove
Svendson Ste-en
%ette"sen &a"i
-
8/12/2019 SQL Made Simple
42/107
Tu"ne" Sall+
&ent Cla"!LE %e"sons
(
%_d int
Last'ame va"ca"(66)
Fi"st'ame va"ca"(66)
>dd"ess va"ca"(66)
Cit+ va"ca"(66)
)
#e *
-
8/12/2019 SQL Made Simple
46/107
'onstraints are used to limit t#e type of data t#at can go into a table.
'onstraints can be specified !#en a table is created (!it# t#e ',&A& A1L& statement) or
after t#e table is created (!it# t#e AL&, A1L& statement).
-e !ill focus on t#e follo!ing constraints0
'OT 'BLL
B'NBE
%RM>R3 &E3
FORE:' &E3
CHEC&
EF>BLT
#e next c#apters !ill describe eac# constraint in details.
SQL NOT N%LL Constraint
1y default" a table column can #old NLL alues.
SQL NT NULL Constraint#e N6 NLL constraint enforces a column to N6 accept NLL alues.
#e N6 NLL constraint enforces a field to al!ays contain a alue. #is means t#at you
cannot insert a ne! record" or update a record !it#out adding a alue to t#is field.
#e follo!ing SQL enforces t#e 7*TE T>!LE %e"sons
(%_d int 'OT 'BLL
Last'ame va"ca"(66) 'OT 'BLL
Fi"st'ame va"ca"(66)
>dd"ess va"ca"(66)
Cit+ va"ca"(66)
)
-
8/12/2019 SQL Made Simple
47/107
SQL %NIQ%E Constraint
SQL UN#QU, Constraint#e NIQ& constraint uniquely identifies eac# record in a database table.
#e NIQ& and *,IA,C ;&C constraints bot# proide a guarantee for uniqueness for a
column or set of columns.
A *,IA,C ;&C constraint automatically #as a NIQ& constraint defined on it.
Note t#at you can #ae many NIQ& constraints per table" but only one *,IA,C ;&C
constraint per table.
SQL UN#QU, Constraint on CR,&T, T&BL,
#e follo!ing SQL creates a NIQ& constraint on t#e 7*dd"ess va"ca"(66)
Cit+ va"ca"(66)
-
8/12/2019 SQL Made Simple
48/107
)
o allo! naming of a NIQ& constraint" and for defining a NIQ& constraint on multiplecolumns" use t#e follo!ing SQL syntax0
M'SQL > SQL Ser5er > ra*e > MS &**ess:
CRE>TE T>!LE %e"sons
(
%_d int 'OT 'BLL
Last'ame va"ca"(66) 'OT 'BLL
Fi"st'ame va"ca"(66)
>dd"ess va"ca"(66)
Cit+ va"ca"(66)
CO'STR>'T uc_%e"son B'NBE (%_dLast'ame)
)
SQL UN#QU, Constraint on <,R T&BL,
o create a NIQ& constraint on t#e 7* B'NBE (%_d)
o allo! naming of a NIQ& constraint" and for defining a NIQ& constraint on multiplecolumns" use t#e follo!ing SQL syntax0
M'SQL > SQL Ser5er > ra*e > MS &**ess:
>LTER T>!LE %e"sons
> CO'STR>'T uc_%e"son B'NBE (%_dLast'ame)
To DR! a UN#QU, Constraint
o drop a NIQ& constraint" use t#e follo!ing SQL0
-
8/12/2019 SQL Made Simple
49/107
M'SQL:
>LTER T>!LE %e"sons
RO% 'E uc_%e"son
SQL Ser5er > ra*e > MS &**ess:
>LTER T>!LE %e"sons
RO% CO'STR>'T uc_%e"son
SQL RI(AR" #E" Constraint
SQL !R#M&RY (,Y Constraint
#e *,IA,C ;&C constraint uniquely identifies eac# record in a database table.
*rimary 3eys must contain unique alues.
A primary 3ey column cannot contain NLL alues.
&ac# table s#ould #ae a primary 3ey" and eac# table can #ae only 6N& primary 3ey.
SQL !R#M&RY (,Y Constraint on CR,&T, T&BL,
#e follo!ing SQL creates a *,IA,C ;&C on t#e 7*R3 &E3 (%_d)
)
-
8/12/2019 SQL Made Simple
50/107
SQL Ser5er > ra*e > MS &**ess:
CRE>TE T>!LE %e"sons
(
%_d int 'OT 'BLL %RM>R3 &E3
Last'ame va"ca"(66) 'OT 'BLLFi"st'ame va"ca"(66)
>dd"ess va"ca"(66)
Cit+ va"ca"(66)
)
o allo! naming of a *,IA,C ;&C constraint" and for defining a *,IA,C ;&C constraint
on multiple columns" use t#e follo!ing SQL syntax0
M'SQL > SQL Ser5er > ra*e > MS &**ess:
CRE>TE T>!LE %e"sons
(
%_d int 'OT 'BLL
Last'ame va"ca"(66) 'OT 'BLL
Fi"st'ame va"ca"(66)
>dd"ess va"ca"(66)
Cit+ va"ca"(66)
CO'STR>'T - SQL Ser5er > ra*e > MS &**ess:
-
8/12/2019 SQL Made Simple
51/107
>LTER T>!LE %e"sons
> CO'STR>'T -R3 &E3
SQL Ser5er > ra*e > MS &**ess:
>LTER T>!LE %e"sons
RO% CO'STR>'T -
-
8/12/2019 SQL Made Simple
52/107
O_Id OrderNo P_Id
1 46 $
@@5 $
$ @65
@ @65 1
Note t#at t#e 7* ra*e > MS &**ess:
CRE>TE T>!LE O"de"s
(
-
8/12/2019 SQL Made Simple
53/107
O_d int 'OT 'BLL %RM>R3 &E3
O"de"'o int 'OT 'BLL
%_d int FORE:' &E3 REFERE'CES %e"sons(%_d)
)
o allo! naming of a =6,&IGN ;&C constraint" and for defining a =6,&IGN ;&C constraint
on multiple columns" use t#e follo!ing SQL syntax0
M'SQL > SQL Ser5er > ra*e > MS &**ess:
CRE>TE T>!LE O"de"s
(
O_d int 'OT 'BLL
O"de"'o int 'OT 'BLL
%_d int
%RM>R3 &E3 (O_d)CO'STR>'T ;'T ;
-
8/12/2019 SQL Made Simple
54/107
To DR! a %R,#;N (,Y Constraint
o drop a =6,&IGN ;&C constraint" use t#e follo!ing SQL0
M'SQL:
>LTER T>!LE O"de"s
RO% FORE:' &E3 ;
-
8/12/2019 SQL Made Simple
55/107
Last'ame va"ca"(66) 'OT 'BLL
Fi"st'ame va"ca"(66)
>dd"ess va"ca"(66)
Cit+ va"ca"(66)
CHEC& (%_d90)
)
SQL Ser5er > ra*e > MS &**ess:
CRE>TE T>!LE %e"sons
(
%_d int 'OT 'BLL CHEC& (%_d90)
Last'ame va"ca"(66) 'OT 'BLL
Fi"st'ame va"ca"(66)
>dd"ess va"ca"(66)
Cit+ va"ca"(66))
o allo! naming of a '$&'; constraint" and for defining a '$&'; constraint on multiple
columns" use t#e follo!ing SQL syntax0
M'SQL > SQL Ser5er > ra*e > MS &**ess:
CRE>TE T>!LE %e"sons
(
%_d int 'OT 'BLL
Last'ame va"ca"(66) 'OT 'BLL
Fi"st'ame va"ca"(66)
>dd"ess va"ca"(66)
Cit+ va"ca"(66)
CO'STR>'T c
-
8/12/2019 SQL Made Simple
56/107
> CHEC& (%_d90)
o allo! naming of a '$&'; constraint" and for defining a '$&'; constraint on multiplecolumns" use t#e follo!ing SQL syntax0
M'SQL > SQL Ser5er > ra*e > MS &**ess:
>LTER T>!LE %e"sons
> CO'STR>'T c ra*e > MS &**ess:
>LTER T>!LE %e"sons
RO% CO'STR>'T c SQL Ser5er > ra*e > MS &**ess:
CRE>TE T>!LE %e"sons
(
%_d int 'OT 'BLL
-
8/12/2019 SQL Made Simple
57/107
Last'ame va"ca"(66) 'OT 'BLL
Fi"st'ame va"ca"(66)
>dd"ess va"ca"(66)
Cit+ va"ca"(66) EF>BLT /Sandnes/
)
#e +&=AL constraint can also be used to insert system alues" by using functions li3e
G&+A&()0
CRE>TE T>!LE O"de"s
(
O_d int 'OT 'BLL
O"de"'o int 'OT 'BLL
%_d int
O"de"ate date EF>BLT :ET>TE()
)
SQL D,%&ULT Constraint on <,R T&BL,
o create a +&=AL constraint on t#e 7'ity7 column !#en t#e table is already created" use t#efollo!ing SQL0
M'SQL:
>LTER T>!LE %e"sons
>LTER Cit+ SET EF>BLT /S>''ES/
SQL Ser5er > ra*e > MS &**ess:
>LTER T>!LE %e"sons
>LTER COLBM' Cit+ SET EF>BLT /S>''ES/
To DR! a D,%&ULT Constraint
o drop a +&=AL constraint" use t#e follo!ing SQL0
M'SQL:
-
8/12/2019 SQL Made Simple
58/107
>LTER T>!LE %e"sons
>LTER Cit+ RO% EF>BLT
SQL Ser5er > ra*e > MS &**ess:
>LTER T>!LE %e"sons
>LTER COLBM' Cit+ RO% EF>BLT
SQL CREATE INDE. Statement
#e ',&A& IN+&K statement is used to create indexes in tables.
Indexes allo! t#e database application to find data fastJ !it#out reading t#e !#ole table.
#nde/es
An index can be created in a table to find data more quic3ly and efficiently.
#e users cannot see t#e indexes" t#ey are %ust used to speed up searc#es4queries.
Note:pdating a table !it# indexes ta3es more time t#an updating a table !it#out (because t#eindexes also need an update). So you s#ould only create indexes on columns (and tables) t#at
!ill be frequently searc#ed against.
SQL CREATE INDE. Syntax
'reates an index on a table. +uplicate alues are allo!ed0
CRE>TE 'E inde=_name
O' table_name (column_name)
SQL CREATE %NIQ%E INDE. Syntax
'reates a unique index on a table. +uplicate alues are not allo!ed0
CRE>TE B'NBE 'E inde=_name
O' table_name (column_name)
-
8/12/2019 SQL Made Simple
59/107
Note:#e syntax for creating indexes aries amongst different databases. #erefore0 '#ec3 t#e
syntax for creating indexes in your database.
CR,&T, #ND, ,/a$)e
#e SQL statement belo! creates an index named 7*Index7 on t#e 7LastName7 column in t#e7*ersons7 table0
CRE>TE 'E %nde=
O' %e"sons (Last'ame)
If you !ant to create an index on a combination of columns" you can list t#e column names!it#in t#e parent#eses" separated by commas0
CRE>TE 'E %nde=O' %e"sons (Last'ame Fi"st'ame)
SQL DRO INDE./ DRO TA!LE/ and DRO DATA!ASE
Indexes" tables" and databases can easily be deleted4remoed !it# t#e +,6* statement.
The DR! #ND, State$ent
#e +,6* IN+&K statement is used to delete an index in a table.
DRO INDE. Syntax )or (S Access0
RO% 'E inde=_name O' table_name
DRO INDE. Syntax )or (S SQL Ser'er0
RO% 'E table_nameinde=_name
DRO INDE. Syntax )or D!12Oracle0
RO% 'E inde=_name
DRO INDE. Syntax )or (ySQL0
>LTER T>!LE table_name RO% 'E inde=_name
-
8/12/2019 SQL Made Simple
60/107
The DR! T&BL, State$ent#e +,6* A1L& statement is used to delete a table.
RO% T>!LE table_name
The DR! D&T&B&S, State$ent
#e +,6* +AA1AS& statement is used to delete a database.
RO% >T>!>SE database_name
The TRUNC&T, T&BL, State$ent
-#at if !e only !ant to delete t#e data inside t#e table" and not t#e table itself
#en" use t#e ,N'A& A1L& statement0
TRB'C>TE T>!LE table_name
SQL ALTER TA!LE Statement
The <,R T&BL, State$ent
#e AL&, A1L& statement is used to add" delete" or modify columns in an existing table.
SQL ALTER TA!LE Syntax
o add a column in a table" use t#e follo!ing syntax0
>LTER T>!LE table_name
-
8/12/2019 SQL Made Simple
61/107
> column_name datat+-e
o delete a column in a table" use t#e follo!ing syntax (notice t#at some database systems donDtallo! deleting a column)0
>LTER T>!LE table_name
RO% COLBM' column_name
o c#ange t#e data type of a column in a table" use t#e follo!ing syntax0
>LTER T>!LE table_name
>LTER COLBM' column_name datat+-e
SQL <,R T&BL, ,/a$)e
Loo3 at t#e 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
No! !e !ant to add a column named 7+ate6f1irt#7 in t#e 7*ersons7 table.
-e use t#e follo!ing SQL statement0
>LTER T>!LE %e"sons
> ateO;!i"t date
Notice t#at t#e ne! column" 7+ate6f1irt#7" is of type date and is going to #old a date. #e datatype specifies !#at type of data t#e column can #old. =or a complete reference of all t#e data
types aailable in S Access" ySQL" and SQL Serer" go to our complete +ata ypesreference.
#e 7*ersons7 table !ill no! li3e t#is0
P_Id LastName FirstName Address City DateO"#irt$
http://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/sql_datatypes.asp -
8/12/2019 SQL Made Simple
62/107
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
Change Data T')e ,/a$)e
No! !e !ant to c#ange t#e data type of t#e column named 7+ate6f1irt#7 in t#e 7*ersons7 table.
-e use t#e follo!ing SQL statement0
>LTER T>!LE %e"sons
>LTER COLBM' ateO;!i"t +ea"
Notice t#at t#e 7+ate6f1irt#7 column is no! of type year and is going to #old a year in a t!o2digit or four2digit format.
DR! CLUMN ,/a$)e
Next" !e !ant to delete t#e column named 7+ate6f1irt#7 in t#e 7*ersons7 table.
-e use t#e follo!ing SQL statement0
>LTER T>!LE %e"sons
RO% COLBM' ateO;!i"t
#e 7*ersons7 table !ill no! li3e t#is0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
-
8/12/2019 SQL Made Simple
63/107
SQL A%TO INCRE(ENT ,ield
Auto2increment allo!s a unique number to be generated !#en a ne! record is inserted into a
table.
&UT #NCR,M,NT a %ied
Mery often !e !ould li3e t#e alue of t#e primary 3ey field to be created automatically eerytime a ne! record is inserted.
-e !ould li3e to create an auto2increment field in a table.
S'nta/ +or M'SQL
#e follo!ing SQL statement defines t#e 7*TE T>!LE %e"sons
(
%_d int 'OT 'BLL >BTO_'CREME'T
Last'ame va"ca"(66) 'OT 'BLL
Fi"st'ame va"ca"(66)>dd"ess va"ca"(66)
Cit+ va"ca"(66)
%RM>R3 &E3 (%_d)
)
ySQL uses t#e A6LTER T>!LE %e"sons >BTO_'CREME'T.100
-
8/12/2019 SQL Made Simple
64/107
o insert a ne! record into t#e 7*ersons7 table" !e !ill not #ae to specify a alue for t#e 7*LBES (/La"s//Monsen/)
#e SQL statement aboe !ould insert a ne! record into t#e 7*ersons7 table. #e 7*dd"ess va"ca"(66)
Cit+ va"ca"(66)
)
#e S SQL Serer uses t#e I+&NIC 3ey!ord to perform an auto2increment feature.
1y default" t#e starting alue for I+&NIC is 8" and it !ill increment by 8 for eac# ne! record.
o specify t#at t#e 7*
-
8/12/2019 SQL Made Simple
65/107
-
8/12/2019 SQL Made Simple
66/107
M'A>LBE 1
ST>RT ,TH 1
'CREME'T !3 1
C>CHE 10
#e code aboe creates a sequence ob%ect called seqTE AE, vie2_name >S
SELECT column_name(s)
FROM table_name
-
8/12/2019 SQL Made Simple
67/107
,HERE condition
Note:A ie! al!ays s#o!s up2to2date data/ #e database engine recreates t#e data" using t#eie!Ds SQL statement" eery time a user queries a ie!.
SQL CR,&T, #,W ,/a$)es
If you #ae t#e Nort#!ind database you can see t#at it #as seeral ie!s installed by default.
#e ie! 7'urrent *roduct List7 lists all actie products (products t#at are not discontinued)
from t#e 7*roducts7 table. #e ie! is created !it# t#e follo!ing SQL0
CRE>TE AE, ICu""ent %"oduct ListJ >S
SELECT %"oduct%"oduct'ame
FROM %"oducts,HERE iscontinued.'o
-e can query t#e ie! aboe as follo!s0
SELECT * FROM ICu""ent %"oduct ListJ
Anot#er ie! in t#e Nort#!ind sample database selects eery product in t#e 7*roducts7 table
!it# a unit price #ig#er t#an t#e aerage unit price0
CRE>TE AE, I%"oducts >bove >ve"a#e %"iceJ >S
SELECT %"oduct'ameBnit%"ice
FROM %"oducts
,HERE Bnit%"ice9(SELECT >A:(Bnit%"ice) FROM %"oducts)
-e can query t#e ie! aboe as follo!s0
SELECT * FROM I%"oducts >bove >ve"a#e %"iceJ
Anot#er ie! in t#e Nort#!ind database calculates t#e total sale for eac# category in 8O. Notet#at t#is ie! selects its data from anot#er ie! called 7*roduct Sales for 8O70
CRE>TE AE, ICate#o"+ Sales Fo" 144J >S
SELECT ST'CT Cate#o"+'ameSum(%"oductSales) >S Cate#o"+Sales
FROM I%"oduct Sales ;o" 144J
:ROB% !3 Cate#o"+'ame
-
8/12/2019 SQL Made Simple
68/107
-e can query t#e ie! aboe as follo!s0
SELECT * FROM ICate#o"+ Sales Fo" 144J
-e can also add a condition to t#e query. No! !e !ant to see t#e total sale only for t#e category
71eerages70
SELECT * FROM ICate#o"+ Sales Fo" 144J
,HERE Cate#o"+'ame./!eve"a#es/
SQL U)dating a ie2
Cou can update a ie! by using t#e follo!ing syntax0
SQL CREATE OR RELACE 3IEW Syntax
CRE>TE OR RE%L>CE AE, vie2_name >S
SELECT column_name(s)
FROM table_name
,HERE condition
No! !e !ant to add t#e 7'ategory7 column to t#e 7'urrent *roduct List7 ie!. -e !ill update
t#e ie! !it# t#e follo!ing SQL0
CRE>TE AE, ICu""ent %"oduct ListJ >S
SELECT %"oduct%"oduct'ameCate#o"+
FROM %"oducts
,HERE iscontinued.'o
SQL Dro))ing a ie2
Cou can delete a ie! !it# t#e +,6* MI&- command.
SQL DRO 3IEW Syntax
RO% AE, vie2_name
-
8/12/2019 SQL Made Simple
69/107
SQL Date ,unctions
SQL Dates#e most difficult part !#en !or3ing !it# dates is to be sure t#at t#e format of t#e date you
are trying to insert" matc#es t#e format of t#e date column in t#e database.
As long as your data contains only t#e date portion" your queries !ill !or3 as expected.$o!eer" if a time portion is inoled" it gets complicated.
1efore tal3ing about t#e complications of querying for dates" !e !ill loo3 at t#e most important
built2in functions for !or3ing !it# dates.
M'SQL Date %un*tions
#e follo!ing table lists t#e most important built2in date functions in ySQL0
F%nction Description
'O,() Retu"ns te cu""ent date and time
CBR>TE() Retu"ns te cu""ent date
CBRTME() Retu"ns te cu""ent time
>TE() E=t"acts te date -a"t o; a date o" datePtime e=-"ession
ETR>CT() Retu"ns a sin#le -a"t o; a datePtime
>TE_>() >dds a s-eci;ied time inte"val to a date
>TE_SB!() Subt"acts a s-eci;ied time inte"val ;"om a date
>TEFF() Retu"ns te numbe" o; da+s bet2een t2o dates
>TE_FORM>T() is-la+s datePtime data in di;;e"ent ;o"mats
SQL Ser5er Date %un*tions
http://www.w3schools.com/sql/func_now.asphttp://www.w3schools.com/sql/func_curdate.asphttp://www.w3schools.com/sql/func_curtime.asphttp://www.w3schools.com/sql/func_date.asphttp://www.w3schools.com/sql/func_extract.asphttp://www.w3schools.com/sql/func_date_add.asphttp://www.w3schools.com/sql/func_date_sub.asphttp://www.w3schools.com/sql/func_datediff_mysql.asphttp://www.w3schools.com/sql/func_date_format.asphttp://www.w3schools.com/sql/func_now.asphttp://www.w3schools.com/sql/func_curdate.asphttp://www.w3schools.com/sql/func_curtime.asphttp://www.w3schools.com/sql/func_date.asphttp://www.w3schools.com/sql/func_extract.asphttp://www.w3schools.com/sql/func_date_add.asphttp://www.w3schools.com/sql/func_date_sub.asphttp://www.w3schools.com/sql/func_datediff_mysql.asphttp://www.w3schools.com/sql/func_date_format.asp -
8/12/2019 SQL Made Simple
70/107
#e follo!ing table lists t#e most important built2in date functions in SQL Serer0
F%nction Description
:ET>TE() Retu"ns te cu""ent date and time
>TE%>RT() Retu"ns a sin#le -a"t o; a datePtime
>TE>() >dds o" subt"acts a s-eci;ied time inte"val ;"om a date
>TEFF() Retu"ns te time bet2een t2o dates
CO'AERT() is-la+s datePtime data in di;;e"ent ;o"mats
SQL Date Data T')es
M'SQLcomes !it# t#e follo!ing data types for storing a date or a date4time alue in t#e
database0
>TE Q ;o"mat 3333QMMQ
>TETME Q ;o"mat 3333QMMQ HHMMSS
TMEST>M% Q ;o"mat 3333QMMQ HHMMSS
3E>R Q ;o"mat 3333 o" 33
SQL Ser5ercomes !it# t#e follo!ing data types for storing a date or a date4time alue in t#edatabase0
>TE Q ;o"mat 3333QMMQ
>TETME Q ;o"mat 3333QMMQ HHMMSS
SM>LL>TETME Q ;o"mat 3333QMMQ HHMMSS
TMEST>M% Q ;o"mat a uni7ue numbe"
Note:#e date types are c#osen for a column !#en you create a ne! table in your database/
=or an oerie! of all data types aailable" go to our complete +ata ypes reference.
SQL Wor=ing 2ith Dates
Cou can compare t!o dates easily if t#ere is no time component inoled/
http://www.w3schools.com/sql/func_getdate.asphttp://www.w3schools.com/sql/func_datepart.asphttp://www.w3schools.com/sql/func_dateadd.asphttp://www.w3schools.com/sql/func_datediff.asphttp://www.w3schools.com/sql/func_convert.asphttp://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/sql_datatypes.asphttp://www.w3schools.com/sql/func_getdate.asphttp://www.w3schools.com/sql/func_datepart.asphttp://www.w3schools.com/sql/func_dateadd.asphttp://www.w3schools.com/sql/func_datediff.asphttp://www.w3schools.com/sql/func_convert.asphttp://www.w3schools.com/sql/sql_datatypes.asp -
8/12/2019 SQL Made Simple
71/107
Assume !e #ae t#e follo!ing 76rders7 table0
OrderId Prod%ctName OrderDate
1 :eitost 00Q11Q11
Camembe"t %ie""ot 00Q11Q04
$ Moa"ella di :iovanni 00Q11Q11
@ Masca"-one Fabioli 00Q10Q4
No! !e !ant to select t#e records !it# an 6rder+ate of 7599P2882887 from t#e table aboe.
-e use t#e follo!ing S&L&' statement0
SELECT * FROM O"de"s ,HERE O"de"ate./00Q11Q11/
#e result2set !ill loo3 li3e t#is0
OrderId Prod%ctName OrderDate
1 :eitost 00Q11Q11
$ Moa"ella di :iovanni 00Q11Q11
No!" assume t#at t#e 76rders7 table loo3s li3e t#is (notice t#e time component in t#e
76rder+ate7 column)0
OrderId Prod%ctName OrderDate
1 :eitost 00Q11Q11 1$$@@
Camembe"t %ie""ot 00Q11Q04 16@61
$ Moa"ella di :iovanni 00Q11Q11 11101
@ Masca"-one Fabioli 00Q10Q4 1@6564
If !e use t#e same S&L&' statement as aboe0
SELECT * FROM O"de"s ,HERE O"de"ate./00Q11Q11/
-
8/12/2019 SQL Made Simple
72/107
!e !ill get no result/ #is is because t#e query is loo3ing only for dates !it# no time portion.
Ti):If you !ant to 3eep your queries simple and easy to maintain" do not allo! time
components in your dates/
SQL N%LL 3alues
NLL alues represent missing un3no!n data.
1y default" a table column can #old NLL alues.
#is c#apter !ill explain t#e IS NLL and IS N6 NLL operators.
SQL NULL aues
If a column in a table is optional" !e can insert a ne! record or update an existing record !it#out
adding a alue to t#is column. #is means t#at t#e field !ill be saed !it# a NLL alue.
NLL alues are treated differently from ot#er alues.
NLL is used as a place#older for un3no!n or inapplicable alues.
Note:It is not possible to compare NLL and 9J t#ey are not equialent.
SQL Wor=ing 2ith NULL aues
Loo3 at t#e follo!ing 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Stavan#e"
Suppose t#at t#e 7Address7 column in t#e 7*ersons7 table is optional. #is means t#at if !e
insert a record !it# no alue for t#e 7Address7 column" t#e 7Address7 column !ill be saed !it#
a NLL alue.
-
8/12/2019 SQL Made Simple
73/107
$o! can !e test for NLL alues
It is not possible to test for NLL alues !it# comparison operators" suc# as " ?" or ?@.
-e !ill #ae to use t#e IS NLL and IS N6 NLL operators instead.
SQL #S NULL
$o! do !e select only t#e records !it# NLL alues in t#e 7Address7 column
-e !ill #ae to use t#e IS NLL operator0
SELECT Last'ameFi"st'ame>dd"ess FROM %e"sons
,HERE >dd"ess S 'BLL
#e result2set !ill loo3 li3e t#is0
LastName FirstName Address
Hansen Ola
%ette"sen &a"i
Ti):Al!ays use IS NLL to loo3 for NLL alues.
SQL #S NT NULL
$o! do !e select only t#e records !it# no NLL alues in t#e 7Address7 column
-e !ill #ae to use t#e IS N6 NLL operator0
SELECT Last'ameFi"st'ame>dd"ess FROM %e"sons
,HERE >dd"ess S 'OT 'BLL
#e result2set !ill loo3 li3e t#is0
LastName FirstName Address
Svendson Tove !o"#vn $
-
8/12/2019 SQL Made Simple
74/107
In t#e next c#apter !e !ill loo3 at t#e ISNLL()" NML()" I=NLL() and '6AL&S'&()
functions.
SQL N%LL ,unctions
SQL #SNULL@A NL@A #%NULL@A and C&L,SC,@A
%un*tions
Loo3 at t#e follo!ing 7*roducts7 table0
P_Id Prod%ctName !nitPrice !nitsIn&toc' !nitsOnOrder
1 Da"lsbe"# 10@6 15 16
Masca"-one $65 $
$ :o"#onola 165 4 0
Suppose t#at t#e 7nits6n6rder7 column is optional" and may contain NLL alues.
-e #ae t#e follo!ing S&L&' statement0
SELECT %"oduct'ameBnit%"ice*(BnitsnStoc
-
8/12/2019 SQL Made Simple
75/107
ra*e
6racle does not #ae an ISNLL() function. $o!eer" !e can use t#e NML() function to
ac#iee t#e same result0
SELECT %"oduct'ameBnit%"ice*(BnitsnStocllo2s 2ole numbe"s ;"om 0 to 66 1 b+te
-
8/12/2019 SQL Made Simple
76/107
nte#e" >llo2s 2ole numbe"s bet2een Q$5 and $5 b+tes
Lon# >llo2s 2ole numbe"s bet2een Q1@@$5@ and 1@@$5@ @ b+tes
Sin#le Sin#le -"ecision ;loatin#Q-oint ,ill andle most decimals @ b+tes
ouble ouble -"ecision ;loatin#Q-oint ,ill andle most decimals b+tes
Cu""enc+ Bse ;o" cu""enc+ Holds u- to 16 di#its o; 2ole dolla"s -lus @
decimal -laces Tip)3ou can coose 2ic count"+/s cu""enc+ to
use
b+tes
>uto'umbe" >uto'umbe" ;ields automaticall+ #ive eac "eco"d its o2n numbe"
usuall+ sta"tin# at 1
@ b+tes
atePTime Bse ;o" dates and times b+tes
3esP'o > lo#ical ;ield can be dis-la+ed as 3esP'o T"uePFalse o" OnPO;;
n code use te constants T"ue and False (e7uivalent to Q1 and 0)
Note)'ull values a"e not allo2ed in 3esP'o ;ields
1 bit
Ole Obect Can sto"e -ictu"es audio video o" ote" !LO!s (!ina"+ La"#e
O!ects)
u- to
1:!
H+-e"lin< Contain lin
-
8/12/2019 SQL Made Simple
77/107
ca"acte"s) Te ma=imum sie is s-eci;ied in -a"entesis Can sto"e u- to
66 ca"acte"s Note); +ou -ut a #"eate" value tan 66 it 2ill be conve"ted
to a TET t+-e
T'3TET Holds a st"in# 2it a ma=imum len#t o; 66 ca"acte"s
TET Holds a st"in# 2it a ma=imum len#t o; 566$6 ca"acte"s
!LO! Fo" !LO!s (!ina"+ La"#e O!ects) Holds u- to 566$6 b+tes o; data
MEBMTET Holds a st"in# 2it a ma=imum len#t o; 1516 ca"acte"s
MEBM!LO! Fo" !LO!s (!ina"+ La"#e O!ects) Holds u- to 1516 b+tes o; data
LO':TET Holds a st"in# 2it a ma=imum len#t o; @4@4546 ca"acte"s
LO':!LO! Fo" !LO!s (!ina"+ La"#e O!ects) Holds u- to @4@4546 b+tes o; data
E'BM(=+etc) Let +ou ente" a list o; -ossible values 3ou can list u- to 566$6 values in an
E'BM list ; a value is inse"ted tat is not in te list a blan< value 2ill be
inse"ted
Note:#e alues are sorted in t#e order you enter t#em.
Cou enter t#e possible alues in t#is format0 &N(DKD"DCD"DRD)
SET Simila" to E'BM e=ce-t tat SET ma+ contain u- to 5@ list items and can
sto"e mo"e tan one coice
Nu$ber t')es:
Data type Description
T'3'T(sie) Q1 to 1 no"mal 0 to 66 B'S:'E* Te ma=imum numbe" o; di#its
ma+ be s-eci;ied in -a"entesis
SM>LL'T(sie) Q$5 to $5 no"mal 0 to 566$6 B'S:'E* Te ma=imum numbe" o;
di#its ma+ be s-eci;ied in -a"entesis
MEBM'T(sie) Q$50 to $50 no"mal 0 to 1516 B'S:'E* Te ma=imumnumbe" o; di#its ma+ be s-eci;ied in -a"entesis
'T(sie) Q1@@$5@ to 1@@$5@ no"mal 0 to @4@4546 B'S:'E* Te
ma=imum numbe" o; di#its ma+ be s-eci;ied in -a"entesis
!:'T(sie) Q4$$0$56@60 to 4$$0$56@60 no"mal 0 to
1@@5@@0$04661516 B'S:'E* Te ma=imum numbe" o; di#its ma+
-
8/12/2019 SQL Made Simple
78/107
be s-eci;ied in -a"entesis
FLO>T(sied) > small numbe" 2it a ;loatin# decimal -oint Te ma=imum numbe" o; di#its
ma+ be s-eci;ied in te sie -a"amete" Te ma=imum numbe" o; di#its to te
"i#t o; te decimal -oint is s-eci;ied in te d -a"amete"
OB!LE(sied) > la"#e numbe" 2it a ;loatin# decimal -oint Te ma=imum numbe" o; di#its
ma+ be s-eci;ied in te sie -a"amete" Te ma=imum numbe" o; di#its to te
"i#t o; te decimal -oint is s-eci;ied in te d -a"amete"
ECM>L(sied) > OB!LE sto"ed as a st"in# allo2in# ;o" a ;i=ed decimal -oint Te
ma=imum numbe" o; di#its ma+ be s-eci;ied in te sie -a"amete" Te
ma=imum numbe" o; di#its to te "i#t o; te decimal -oint is s-eci;ied in te
d -a"amete"
>#e integer types #ae an extra option called NSIGN&+. Normally" t#e integer goes from annegatie to positie alue. Adding t#e NSIGN&+ attribute !ill moe t#at range up so it starts
at ero instead of a negatie number.
Date t')es:
Data type Description
>TE() > date Fo"mat 3333QMMQ
Note:#e supported range is from D8999298298D to D2852:8D
>TETME() *> date and time combination Fo"mat 3333QMMQ HHMMSS
Note:#e supported range is from D8999298298 99099099D to D2852:85:0F0FD
TMEST>M%() *> timestam- TMEST>M% values a"e sto"ed as te numbe" o; seconds
since te Bni= e-oc (/140Q01Q01 000000/ BTC) Fo"mat 3333QMMQ
HHMMSS
Note:#e supported range is from D8O9298298 99099098D ' to D59:P2982
9 9:0809OD '
TME() > time Fo"mat HHMMSS
Note:#e supported range is from D2P:P0F0FD to DP:P0F0FD
3E>R() > +ea" in t2oQdi#it o" ;ou"Qdi#it ;o"mat
Note:Malues allo!ed in four2digit format0 898 to 58FF. Malues allo!ed in
t!o2digit format0 O9 to T" representing years from 8O9 to 59T
-
8/12/2019 SQL Made Simple
79/107
>&en if +A&I& and I&SA* return t#e same format" t#ey !or3 ery differently. In
an INS&, or *+A& query" t#e I&SA* automatically set itself to t#e current date and
time. I&SA* also accepts arious formats" li3e CCCC++$$SS"CC++$$SS" CCCC++" or CC++.
SQL Ser5er Data T')es
Chara*ter strings:
Data type Description &tora(e
ca"(n) Fi=edQlen#t ca"acte" st"in# Ma=imum 000 ca"acte"s n
va"ca"(n) Aa"iableQlen#t ca"acte" st"in# Ma=imum 000 ca"acte"s
va"ca"(ma=) Aa"iableQlen#t ca"acte" st"in# Ma=imum 10$@1@
ca"acte"s
te=t Aa"iableQlen#t ca"acte" st"in# Ma=imum :! o; te=t data
Uni*ode strings:
Data type Description &tora(e
nca"(n) Fi=edQlen#t Bnicode data Ma=imum @000 ca"acte"s
nva"ca"(n) Aa"iableQlen#t Bnicode data Ma=imum @000 ca"acte"s
nva"ca"(ma=) Aa"iableQlen#t Bnicode data Ma=imum 6$5041 ca"acte"s
nte=t Aa"iableQlen#t Bnicode data Ma=imum :! o; te=t data
Binar' t')es:
Data type Description &tora(e
bit >llo2s 0 1 o" 'BLL
bina"+(n) Fi=edQlen#t bina"+ data Ma=imum 000 b+tes
va"bina"+(n) Aa"iableQlen#t bina"+ data Ma=imum 000 b+tes
va"bina"+(ma=) Aa"iableQlen#t bina"+ data Ma=imum :!
-
8/12/2019 SQL Made Simple
80/107
ima#e Aa"iableQlen#t bina"+ data Ma=imum :!
Nu$ber t')es:
Data type Description &tora(e
tin+int >llo2s 2ole numbe"s ;"om 0 to 66 1 b+te
smallint >llo2s 2ole numbe"s bet2een Q$5 and $5 b+tes
int >llo2s 2ole numbe"s bet2een Q1@@$5@ and 1@@$5@ @ b+tes
bi#int >llo2s 2ole numbe"s bet2een Q4$$0$56@60 and
4$$0$56@60
b+tes
decimal(-s) Fi=ed -"ecision and scale numbe"s
Allo!s numbers from 289U:P V8 to 89U:P W8.
#e p parameter indicates t#e maximum total number of digits t#at
can be stored (bot# to t#e left and to t#e rig#t of t#e decimal point).p must be a alue from 8 to :P. +efault is 8P.
#e s parameter indicates t#e maximum number of digits stored to
t#e rig#t of t#e decimal point. s must be a alue from 9 to p. +efault
alue is 9
6Q1
b+tes
nume"ic(-s) Fi=ed -"ecision and scale numbe"s
Allo!s numbers from 289U:P V8 to 89U:P W8.
#e p parameter indicates t#e maximum total number of digits t#atcan be stored (bot# to t#e left and to t#e rig#t of t#e decimal point).
p must be a alue from 8 to :P. +efault is 8P.
#e s parameter indicates t#e maximum number of digits stored to
t#e rig#t of t#e decimal point. s must be a alue from 9 to p. +efaultalue is 9
6Q1b+tes
smallmone+ Moneta"+ data ;"om Q1@@$5@ to 1@@$5@ @ b+tes
mone+ Moneta"+ data ;"om Q4$$0$56@60 to
4$$0$56@60
b+tes
;loat(n) Floatin# -"ecision numbe" data ;"om Q14E $0 to 14E $0
#e n parameter indicates !#et#er t#e field s#ould #old or P
@ o"
b+tes
-
8/12/2019 SQL Made Simple
81/107
bytes. float(5) #olds a 2byte field and float(F:) #olds an P2bytefield. +efault alue of n is F:.
"eal Floatin# -"ecision numbe" data ;"om Q$@0E $ to $@0E $ @ b+tes
Date t')es:
Data type Description &tora(e
datetime F"om Danua"+ 1 16$ to ecembe" $1 4444 2it an accu"ac+ o;
$$$ milliseconds
b+tes
datetime F"om Danua"+ 1 0001 to ecembe" $1 4444 2it an accu"ac+ o;
100 nanoseconds
5Q b+tes
smalldatetime F"om Danua"+ 1 1400 to Dune 5 04 2it an accu"ac+ o; 1minute
@ b+tes
date Sto"e a date onl+ F"om Danua"+ 1 0001 to ecembe" $1 4444 $ b+tes
time Sto"e a time onl+ to an accu"ac+ o; 100 nanoseconds $Q6 b+tes
datetimeo;;set Te same as datetime 2it te addition o; a time one o;;set Q10
b+tes
timestam- Sto"es a uni7ue numbe" tat #ets u-dated eve"+ time a "o2 #ets
c"eated o" modi;ied Te timestam- value is based u-on an inte"nal
cloc< and does not co""es-ond to "eal time Eac table ma+ ave
onl+ one timestam- va"iable
ther data t')es:
Data type Description
s7l_va"iant Sto"es u- to 000 b+tes o; data o; va"ious data t+-es e=ce-t te=t nte=t and
timestam-
uni7ueidenti;ie" Sto"es a #loball+ uni7ue identi;ie" (:B)
=ml Sto"es ML ;o"matted data Ma=imum :!
cu"so" Sto"es a "e;e"ence to a cu"so" used ;o" database o-e"ations
table Sto"es a "esultQset ;o" late" -"ocessin#
-
8/12/2019 SQL Made Simple
82/107
SQL ,unctions
SQL #as many built2in functions for performing calculations on data.
SQL &ggregate %un*tions
SQL aggregate functions return a single alue" calculated from alues in a column.
seful aggregate functions0
>A:() Q Retu"ns te ave"a#e value COB'T() Q Retu"ns te numbe" o; "o2s
FRST() Q Retu"ns te ;i"st value
L>ST() Q Retu"ns te last value
M>() Q Retu"ns te la"#est value
M'() Q Retu"ns te smallest value
SBM() Q Retu"ns te sum
SQL S*aar +un*tions
SQL scalar functions return a single alue" based on t#e input alue.
seful scalar functions0
BC>SE() Q Conve"ts a ;ield to u--e" case
LC>SE() Q Conve"ts a ;ield to lo2e" case
M() Q E=t"act ca"acte"s ;"om a te=t ;ield
LE'() Q Retu"ns te len#t o; a te=t ;ield
ROB'() Q Rounds a nume"ic ;ield to te numbe" o; decimals s-eci;ied
'O,() Q Retu"ns te cu""ent s+stem date and time
FORM>T() Q Fo"mats o2 a ;ield is to be dis-la+ed
-
8/12/2019 SQL Made Simple
83/107
Ti):#e aggregate functions and t#e scalar functions !ill be explained in details in t#e next
c#apters.
SQL A3-45 ,unction
The &;@A %un*tion
#e AMG() function returns t#e aerage alue of a numeric column.
SQL A3-45 Syntax
SELECT >A:(column_name) FROM table_name
SQL &;@A ,/a$)e
-e #ae t#e follo!ing 76rders7 table0
O_Id OrderDate OrderPrice C%stomer
1 00P11P1 1000 Hansen
00P10P$ 1500 'ilsen
$ 00P04P0 00 Hansen
@ 00P04P0$ $00 Hansen
6 00P0P$0 000 Densen
5 00P10P0@ 100 'ilsen
No! !e !ant to find t#e aerage alue of t#e 76rder*rice7 fields.
-e use t#e follo!ing SQL statement0
SELECT >A:(O"de"%"ice) >S O"de">ve"a#e FROM O"de"s
#e result2set !ill loo3 li3e t#is0
-
8/12/2019 SQL Made Simple
84/107
OrderA*era(e
460
No! !e !ant to find t#e customers t#at #ae an 6rder*rice alue #ig#er t#an t#e aerage6rder*rice alue.
-e use t#e follo!ing SQL statement0
SELECT Custome" FROM O"de"s
,HERE O"de"%"ice9(SELECT >A:(O"de"%"ice) FROM O"de"s)
#e result2set !ill loo3 li3e t#is0
C%stomer
Hansen
'ilsen
Densen
SQL CO%NT45 ,unction
#e '6N() function returns t#e number of ro!s t#at matc#es a specified criteria.
SQL CO%NT4column6name5 Syntax
#e '6N(column) function returns t#e number of records in a table0
SELECT COB'T(*) FROM table_name
-
8/12/2019 SQL Made Simple
85/107
-
8/12/2019 SQL Made Simple
86/107
-
8/12/2019 SQL Made Simple
87/107
SQL ,IRST45 Syntax
SELECT FRST(column_name) FROM table_name
SQL %#RST@A ,/a$)e
-e #ae t#e follo!ing 76rders7 table0
O_Id OrderDate OrderPrice C%stomer
1 00P11P1 1000 Hansen
00P10P$ 1500 'ilsen
$ 00P04P0 00 Hansen
@ 00P04P0$ $00 Hansen
6 00P0P$0 000 Densen
5 00P10P0@ 100 'ilsen
No! !e !ant to find t#e first alue of t#e 76rder*rice7 column.
-e use t#e follo!ing SQL statement0
SELECT FRST(O"de"%"ice) >S Fi"stO"de"%"ice FROM O"de"s
Ti):-or3around if =I,S() function is not supported0
SELECT O"de"%"ice FROM O"de"s ORER !3 O_d LMT 1
#e result2set !ill loo3 li3e t#is0
FirstOrderPrice
1000
-
8/12/2019 SQL Made Simple
88/107
SQL LAST45 ,unction
The L&ST@A %un*tion#e LAS() function returns t#e last alue of t#e selected column.
SQL LAST45 Syntax
SELECT L>ST(column_name) FROM table_name
SQL L&ST@A ,/a$)e
-e #ae t#e follo!ing 76rders7 table0
O_Id OrderDate OrderPrice C%stomer
1 00P11P1 1000 Hansen
00P10P$ 1500 'ilsen
$ 00P04P0 00 Hansen
@ 00P04P0$ $00 Hansen
6 00P0P$0 000 Densen
5 00P10P0@ 100 'ilsen
No! !e !ant to find t#e last alue of t#e 76rder*rice7 column.
-e use t#e follo!ing SQL statement0
SELECT L>ST(O"de"%"ice) >S LastO"de"%"ice FROM O"de"s
Ti):-or3around if LAS() function is not supported0
SELECT O"de"%"ice FROM O"de"s ORER !3 O_d ESC LMT 1
#e result2set !ill loo3 li3e t#is0
-
8/12/2019 SQL Made Simple
89/107
LastOrderPrice
100
SQL (A.45 ,unction
The M&@A %un*tion
#e AK() function returns t#e largest alue of t#e selected column.
SQL (A.45 Syntax
SELECT M>(column_name) FROM table_name
SQL M&@A ,/a$)e
-e #ae t#e follo!ing 76rders7 table0
O_Id OrderDate OrderPrice C%stomer
1 00P11P1 1000 Hansen
00P10P$ 1500 'ilsen
$ 00P04P0 00 Hansen
@ 00P04P0$ $00 Hansen
6 00P0P$0 000 Densen
5 00P10P0@ 100 'ilsen
No! !e !ant to find t#e largest alue of t#e 76rder*rice7 column.
-e use t#e follo!ing SQL statement0
SELECT M>(O"de"%"ice) >S La"#estO"de"%"ice FROM O"de"s
-
8/12/2019 SQL Made Simple
90/107
-
8/12/2019 SQL Made Simple
91/107
SELECT M'(O"de"%"ice) >S SmallestO"de"%"ice FROM O"de"s
#e result2set !ill loo3 li3e t#is0
&mallestOrderPrice
100
SQL S%(45 ,unction
The SUM@A %un*tion
#e S() function returns t#e total sum of a numeric column.
SQL S%(45 Syntax
SELECT SBM(column_name) FROM table_name
SQL SUM@A ,/a$)e
-e #ae t#e follo!ing 76rders7 table0
O_Id OrderDate OrderPrice C%stomer
1 00P11P1 1000 Hansen
00P10P$ 1500 'ilsen
$ 00P04P0 00 Hansen
@ 00P04P0$ $00 Hansen
6 00P0P$0 000 Densen
5 00P10P0@ 100 'ilsen
No! !e !ant to find t#e sum of all 76rder*rice7 fields7.
-
8/12/2019 SQL Made Simple
92/107
-e use t#e follo!ing SQL statement0
SELECT SBM(O"de"%"ice) >S O"de"Total FROM O"de"s
#e result2set !ill loo3 li3e t#is0
OrderTotal
600
SQL -RO% !" Statement
Aggregate functions often need an added G,6* 1C statement.
The ;RU! BY State$ent
#e G,6* 1C statement is used in con%unction !it# t#e aggregate functions to group t#e
result2set by one or more columns.
SQL -RO% !" Syntax
SELECT column_name a##"e#ate_;unction(column_name)FROM table_name
,HERE column_name o-e"ato" value
:ROB% !3 column_name
SQL ;RU! BY ,/a$)e
-e #ae t#e follo!ing 76rders7 table0
O_Id OrderDate OrderPrice C%stomer
1 00P11P1 1000 Hansen
00P10P$ 1500 'ilsen
$ 00P04P0 00 Hansen
-
8/12/2019 SQL Made Simple
93/107
@ 00P04P0$ $00 Hansen
6 00P0P$0 000 Densen
5 00P10P0@ 100 'ilsen
No! !e !ant to find t#e total sum (total order) of eac# customer.
-e !ill #ae to use t#e G,6* 1C statement to group t#e customers.
-e use t#e follo!ing SQL statement0
SELECT Custome"SBM(O"de"%"ice) FROM O"de"s
:ROB% !3 Custome"
#e result2set !ill loo3 li3e t#is0
C%stomer &!,-OrderPrice.
Hansen 000
'ilsen 100
Densen 000
Nice/ IsnDt it 0)
LetDs see !#at #appens if !e omit t#e G,6* 1C statement0
SELECT Custome"SBM(O"de"%"ice) FROM O"de"s
#e result2set !ill loo3 li3e t#is0
C%stomer &!,-OrderPrice.
Hansen 600
'ilsen 600
Hansen 600
Hansen 600
-
8/12/2019 SQL Made Simple
94/107
Densen 600
'ilsen 600
#e result2set aboe is not !#at !e !anted.
,/)anation o+ 2h' the abo5e S,L,CT state$ent *annot be used:#e S&L&' statement
aboe #as t!o columns specified ('ustomer and S(6rder*rice). #e 7S(6rder*rice)7
returns a single alue (t#at is t#e total sum of t#e 76rder*rice7 column)" !#ile 7'ustomer7returns T alues (one alue for eac# ro! in t#e 76rders7 table). #is !ill t#erefore not gie us t#e
correct result. $o!eer" you #ae seen t#at t#e G,6* 1C statement soles t#is problem.
;RU! BY More Than ne Cou$n
-e can also use t#e G,6* 1C statement on more t#an one column" li3e t#is0
SELECT Custome"O"de"ateSBM(O"de"%"ice) FROM O"de"s
:ROB% !3 Custome"O"de"ate
SQL HA3IN- Clause
The 1N; Cause
#e $AMING clause !as added to SQL because t#e -$&,& 3ey!ord could not be used !it#
aggregate functions.
SQL HA3IN- Syntax
SELECT column_name a##"e#ate_;unction(column_name)
FROM table_name
,HERE column_name o-e"ato" value
:ROB% !3 column_name
H>A': a##"e#ate_;unction(column_name) o-e"ato" value
SQL 1N; ,/a$)e
-
8/12/2019 SQL Made Simple
95/107
-e #ae t#e follo!ing 76rders7 table0
O_Id OrderDate OrderPrice C%stomer
1 00P11P1 1000 Hansen
00P10P$ 1500 'ilsen
$ 00P04P0 00 Hansen
@ 00P04P0$ $00 Hansen
6 00P0P$0 000 Densen
5 00P10P0@ 100 'ilsen
No! !e !ant to find if any of t#e customers #ae a total order of less t#an 5999.
-e use t#e follo!ing SQL statement0
SELECT Custome"SBM(O"de"%"ice) FROM O"de"s
:ROB% !3 Custome"
H>A': SBM(O"de"%"ice)8000
#e result2set !ill loo3 li3e t#is0
C%stomer &!,-OrderPrice.
'ilsen 100
No! !e !ant to find if t#e customers 7$ansen7 or 7Eensen7 #ae a total order of more t#an
8F99.
-e add an ordinary -$&,& clause to t#e SQL statement0
SELECT Custome"SBM(O"de"%"ice) FROM O"de"s
,HERE Custome"./Hansen/ OR Custome"./Densen/:ROB% !3 Custome"
H>A': SBM(O"de"%"ice)91600
#e result2set !ill loo3 li3e t#is0
C%stomer &!,-OrderPrice.
-
8/12/2019 SQL Made Simple
96/107
Hansen 000
Densen 000
SQL %CASE45 ,unction
The UC&S,@A %un*tion
#e 'AS&() function conerts t#e alue of a field to uppercase.
SQL %CASE45 Syntax
SELECT BC>SE(column_name) FROM table_name
Syntax )or SQL Ser'er
SELECT B%%ER(column_name) FROM table_name
SQL UC&S,@A ,/a$)e
-e #ae t#e follo!ing 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
No! !e !ant to select t#e content of t#e 7LastName7 and 7=irstName7 columns aboe" and
conert t#e 7LastName7 column to uppercase.
-e use t#e follo!ing S&L&' statement0
SELECT BC>SE(Last'ame) as Last'ameFi"st'ame FROM %e"sons
-
8/12/2019 SQL Made Simple
97/107
#e result2set !ill loo3 li3e t#is0
LastName FirstName
H>'SE' Ola
SAE'SO' Tove
%ETTERSE' &a"i
SQL LCASE45 ,unction
The LC&S,@A %un*tion
#e L'AS&() function conerts t#e alue of a field to lo!ercase.
SQL LCASE45 Syntax
SELECT LC>SE(column_name) FROM table_name
Syntax )or SQL Ser'erSELECT LO,ER(column_name) FROM table_name
SQL LC&S,@A ,/a$)e
-e #ae t#e follo!ing 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
-
8/12/2019 SQL Made Simple
98/107
-
8/12/2019 SQL Made Simple
99/107
-
8/12/2019 SQL Made Simple
100/107
-e #ae t#e follo!ing 7*ersons7 table0
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Svendson Tove !o"#vn $ Sandnes
$ %ette"sen &a"i Sto"#t 0 Stavan#e"
No! !e !ant to select t#e lengt# of t#e alues in t#e 7Address7 column aboe.
-e use t#e follo!ing S&L&' statement0
SELECT LE'(>dd"ess) as Len#tO;>dd"ess FROM %e"sons
#e result2set !ill loo3 li3e t#is0
Len(t$O"Address
1
4
4
SQL RO%ND45 ,unction
The RUND@A %un*tion
#e ,6N+() function is used to round a numeric field to t#e number of decimals specified.
SQL RO%ND45 SyntaxSELECT ROB'(column_namedecimals) FROM table_name
Parameter Description
column_name Re7ui"ed Te ;ield to "ound
-
8/12/2019 SQL Made Simple
101/107
decimals Re7ui"ed S-eci;ies te numbe" o; decimals to be "etu"ned
SQL RUND@A ,/a$)e
-e #ae t#e follo!ing 7*roducts7 table0
Prod_Id Prod%ctName !nit !nitPrice
1 Da"lsbe"# 1000 # 10@6
Masca"-one 1000 # $65
$ :o"#onola 1000 # 165
No! !e !ant to display t#e product name and t#e price rounded to t#e nearest integer.
-e use t#e follo!ing S&L&' statement0
SELECT %"oduct'ame ROB'(Bnit%"ice0) as Bnit%"ice FROM %"oducts
#e result2set !ill loo3 li3e t#is0
Prod%ctName !nitPrice
Da"lsbe"# 10
Masca"-one $$
:o"#onola 15
SQL NOW45 ,unction
The NW@A %un*tion
#e N6-() function returns t#e current system date and time.
-
8/12/2019 SQL Made Simple
102/107
SQL NOW45 Syntax
SELECT 'O,() FROM table_name
SQL NW@A ,/a$)e
-e #ae t#e follo!ing 7*roducts7 table0
Prod_Id Prod%ctName !nit !nitPrice
1 Da"lsbe"# 1000 # 10@6
Masca"-one 1000 # $65
$ :o"#onola 1000 # 165
No! !e !ant to display t#e products and prices per todayDs date.
-e use t#e follo!ing S&L&' statement0
SELECT %"oduct'ame Bnit%"ice 'o2() as %e"ate FROM %"oducts
#e result2set !ill loo3 li3e t#is0
Prod%ctName !nitPrice PerDate
Da"lsbe"# 10@6 10PP00 1160 >M
Masca"-one $65 10PP00 1160 >M
:o"#onola 165 10PP00 1160 >M
SQL ,OR(AT45 ,unction
The %RM&T@A %un*tion
#e =6,A() function is used to format #o! a field is to be displayed.
-
8/12/2019 SQL Made Simple
103/107
SQL ,OR(AT45 Syntax
SELECT FORM>T(column_name;o"mat) FROM table_name
Parameter Description
column_name Re7ui"ed Te ;ield to be ;o"matted
;o"mat Re7ui"ed S-eci;ies te ;o"mat
SQL %RM&T@A ,/a$)e
-e #ae t#e follo!ing 7*roducts7 table0
Prod_Id Prod%ctName !nit !nitPrice
1 Da"lsbe"# 1000 # 10@6
Masca"-one 1000 # $65
$ :o"#onola 1000 # 165
No! !e !ant to display t#e products and prices per todayDs date (!it# todayDs date displayed int#e follo!ing format 7CCCC22++7).
-e use t#e follo!ing S&L&' statement0
SELECT %"oduct'ame Bnit%"ice FORM>T('o2()/3333QMMQ/) as %e"ate
FROM %"oducts
#e result2set !ill loo3 li3e t#is0
Prod%ctName !nitPrice PerDate
Da"lsbe"# 10@6 00Q10Q0
Masca"-one $65 00Q10Q0
:o"#onola 165 00Q10Q0
-
8/12/2019 SQL Made Simple
104/107
SQL Quic8 Re)erence ,rom W9Sc:ools
&/L &tatement &ynta0
>' P OR SELECT column_name(s)
FROM table_name
,HERE condition
>'?OR condition
>LTER T>!LE >LTER T>!LE table_name
> column_name datat+-e
or
AL&, A1L& table' value
CRE>TE >T>!>SE CRE>TE >T>!>SE database_name
CRE>TE T>!LE CRE>TE T>!LE table_name
(
column_name1 data_t+-e
column_name data_t+-e
column_name data_t+-e
)
CRE>TE 'E CRE>TE 'E inde=_name
O' table_name (column_name)
or
-
8/12/2019 SQL Made Simple
105/107
-
8/12/2019 SQL Made Simple
106/107
A>LBES (value1 value value$)
or
INS&, IN6 table
-
8/12/2019 SQL Made Simple
107/107
FROM old_table_name
or
S&L&' columnLL SELECT column_name(s) FROM table_name1B'O' >LL
SELECT column_name(s) FROM table_name
B%>TE B%>TE table_name
SET column1.value column.value
,HERE some_column.some_value
,HERE SELECT column_name(s)
FROM table_name
,HERE column_name o-e"ato" value