Upload
suranga-sampath
View
219
Download
0
Embed Size (px)
Citation preview
8/9/2019 1-SQL-Basics.ppt
1/114
Database Access using SQL
A basic introduction
James Brucker
8/9/2019 1-SQL-Basics.ppt
2/114
Database Management System
Database: astructured, self-describing collectionof data.
Control access tothe database.
• authentication
• enforcepermissions
• data integrity
• access services
Databas
eManage
r
User
Interface communication protocol
SELECT * FROMcity WHERE nameLIKE Ban%
Client
8/9/2019 1-SQL-Basics.ppt
3/114
Client - Server Databases
Database Server is a separate process on a host
Clients can be on any machine
Many programs may be clients using a standard A!"
Server mysqld
#mys$l# utility
Java App%JDBC client
&'cel client
Server sideClient side
server controlsaccess todatabase
8/9/2019 1-SQL-Basics.ppt
4/114
"nstall Client So(t)are
*or this lab+ you )ill access MySQL server on thenet)ork All you need is a client application ,ou dontneed to run a MySQL server on your computer
Client .ools
mysql!"r#$enc&'l())y!in+,)msi
"r -se "lder ./I T""ls0
mysql&-it""ls()1)2!in+,)msi
*rom/ secpekuacth0do)nload0mys$l
8/9/2019 1-SQL-Basics.ppt
5/114
Add MySQL #bin# to your !ath
.his is so you can run the #mys$l# command line
1n 2indo)s/
3 4ight-click My Computer
5 Choose !roperties
6 Click # Advanced#
7 Click #&nvironment 8ariables#
9 &dit !A.: variable and add/
C/;2indo)s;blah3C045r"&ram Files4MySql4$in
8/9/2019 1-SQL-Basics.ppt
6/114
&'ercise
8/9/2019 1-SQL-Basics.ppt
7/114
&'ercise
Connect to MySQL server on host #secpekuacth#
user/ student pass)ord/ student
2hat MySQL version is the server >
d"s6 mysql se)c'e)#-)ac)t - st-dent '
Enter 'ass!"rd0 nisit
mysql6 SELECT versi"n>?3
8/9/2019 1-SQL-Basics.ppt
8/114
Structure o( a Database
A database system may contain many databases &ach database is composed o( schema and tables
sql6 /SE $an#3
sql6SHOW ta$les3@@
A Ta$lesin$an# A@@A acc"-nts AA clients A
@@
sql6 SHOW data$ases3
@@A 9ata$ase A
@@
A mysql A
A test A
A $an# AA !"rld A
@@
MySQL only shows databases thata user has permission to access.
8/9/2019 1-SQL-Basics.ppt
9/114
A Database Structure
Database
Schema
.able(ield3/ t3(ield5/ t5(ield6/ t6
inde'es
Schema
.able(ield3/ t3(ield5/ t5(ield6/ t6
inde'es
.able(ield3/ t3(ield5/ t5(ield6/ t6
inde'es
.able(ield3/ t3(ield5/ t5(ield6/ t6
inde'es
A database contains schema+)hich describe theorgani?ation o( the database
A schema can contain/
tables - containing data
inde' (iles - (or (ast lookup o(data
stored procedures+constraints+ triggers+ andmore
8/9/2019 1-SQL-Basics.ppt
10/114
Contents o( a .able
A table contains the actual data in records @ro)s A record is composed o( (ields @columns
&ach record contains one set o( data values
@@@@@@
A I9 A ame A CC"de A 9istrict A 5"'-latn
@@@+@A ++,: A Ban"# A THD A Ban"# A ;+,:128 A
A ++,1 A "nta$-ri A THD A "nta$-ri A ,,1:: AA ++,+ A Cian& Mai A THD A Cian& Mai A 1211:: A@@@@@@
records
(rows)
fields (columns)
8/9/2019 1-SQL-Basics.ppt
11/114
ey (ield (or "denti(ying 4o)s
A table contains a primary key that uni$uely identi(iesa ro) o( data
&ach record must have a distinct value o( primary key
.he primary key is used to relate @ oin tables
@@@@@@
A I9 A ame A CC"de A 9istrict A 5"'-latn
@@@+@A ++,: A Ban"# A THD A Ban"# A ;+,:128 AA ++,1 A "nta$-ri A THD A "nta$-ri A ,,1:: AA ++,+ A Cian& Mai A THD A Cian& Mai A 1211:: A@@@@@@
ID is the primary key in ity table.
8/9/2019 1-SQL-Basics.ppt
12/114
Structure o( a .able
&very (ield has/
a name
a data type and length
.o vie) the structure o( a table use/DESCRIBE tablename
sql6 9ESCRIBE City3@@@@@@@A Field A Ty'e A -llA Key A 9e=a-lt A Etra A@@@@@@@A I9 A int>11? A O A 5RI A A a-t"increment AA ame A car>+(? A O A A A AA C"-ntryC"de A car>+? A O A A A AA 9istrict A car>,:? A O A A A AA 5"'-lati"n A int>11? A O A A : A A
@@@@@@@
8/9/2019 1-SQL-Basics.ppt
13/114
Structure o( a .able
#SHOW columns FROM tablename#
sho)s the same in(ormation
sql6 SHOW c"l-mns FROM City3@@@@@@@A Field A Ty'e A -llA Key A 9e=a-lt A Etra A@@@@@@@A I9 A int>11? A O A 5RI A A a-t"increment AA ame A car>+(? A O A A A AA C"-ntryC"de A car>+? A O A A A AA 9istrict A car>,:? A O A A A AA 5"'-lati"n A int>11? A O A A : A A@@@@@@@
!ields may have a defaultvalue to use if a value is
not assi"ned e#plicitly.
8/9/2019 1-SQL-Basics.ppt
14/114
Structured Query Language
Structured Query Language @SQL is the standardlanguage (or accessing in(ormation a database
SQL is case-insensitive and (ree (ormat
&nter commands interactively or in a script (ile
SQL statements can use multiple lines end each statement )ith a semi-colon ;
sql> /SE !"rld3
database changed.
sql> SHOW ta$les3
sql> SHOW c"l-mns FROM city3
sql> 9ECRIBE c"-ntry3
!"# statements end $ith semi-colon.
8/9/2019 1-SQL-Basics.ppt
15/114
&'ercise
3 Connect to MySQL server on host #secpekuacth#
user/ student pass)ord/ nisit
5 2hat databases are on the server>
6 2hat tables are in the !"rld database>
d"s6 mysql se)c'e)#-)ac)t - st-dent '
Enter 'ass!"rd0 nisit
mysql6 SHOW data$ases3
mysql6 /SE !"rld3
mysql6 SHOW ta$les3
8/9/2019 1-SQL-Basics.ppt
16/114
mysql6 SHOW ta$les
FROM
!"rld
3
&'ercise
%o semi-colon.
1mit the semi-colon 2hat happens> &nter a command on several lines
8/9/2019 1-SQL-Basics.ppt
17/114
D&SC4"B&
D&SC4"B& sho)s the structure o( a table same as #S:12 columns *41M tablename#
sql6 9ESCRIBE city3@@@@@@@A Field A Ty'e A -llA Key A 9e=a-lt A Etra A@@@@@@@A I9 A int>11? A O A 5RI A A a-t"increment AA ame A car>+(? A O A A A A
A C"-ntryC"de A car>+? A O A A A AA 9istrict A car>,:? A O A A A AA 5"'-lati"n A int>11? A O A A : A A@@@@@@@
8/9/2019 1-SQL-Basics.ppt
18/114
&'ercise
*or the !"rld database/
)hat (ields does the Country table have>
)hat in(ormation is in the (ields>
)hich (ields contain strings> @char or varchar
)hich (ields contain (loating point values> )hat is the primary key o( the Country table>
8/9/2019 1-SQL-Basics.ppt
19/114
&'ercise/ Case Sensitivity
"s SQL case sensitive>
Are names o( databases and tables case sensitive>
mysql6 9ESCRIBE city 3
mysql6 descri$e city 3
mysql6 -se !"rld3
mysql6 -se WORL93
mysql6 descri$e city3
mysql6 descri$e City3
8/9/2019 1-SQL-Basics.ppt
20/114
&'ercise/ 1-1 Analogy o( a .able>
Database Object Oriented
table
record @ro)
(ields @columns
@@@@@
A I9 A ame A 9istrict A 5"'-la))
@@@+@
A ++,: A Ban"# A Ban"# A ;+,:128 AA ++,1 A "nta$-ri A "nta$-ri A ,,1:: AA ++,+ A Cian& Mai A Cian& Mai A 1211:: A@@@@@
fields (columns)
records (rows)
8/9/2019 1-SQL-Basics.ppt
21/114
Quali(ying Eames
SQL uses ## to $uali(y elements o( a hierarchy
ust like most 1-1 languages
Wold.cit! #city# table in 2orld db
cit!.namename (ield in city table
Wold.cit!.name (ully $uali(ied name
sql6 9ESCRIBE W"rld)c"-ntry3)))sql6 SELECT c"-ntry)name =r"m c"-ntry3
8/9/2019 1-SQL-Basics.ppt
22/114
7 Basic Database 1perations
.he 7 most common operations/
S&L&C. $uery @search the data
"ES&4. add ne) records to a table@s
8/9/2019 1-SQL-Basics.ppt
23/114
Querying Data in a .able
S&L&C. displays (ield values (rom a table/
SELECT =ield1< =ield,< =ield+ FROM ta$le 3
displays ALL ro)s (rom the table
use L"M". number to limit ho) many results
sql6 SELECT acc"-nt-m$er< $alance FROM acc"-nts3
@@@@@
A acc"-nt-m$er A acc"-ntame A clientI9 A $alance A@@@@@
A 1111111+ A 5)Watana'"n& A ::::1::1 A +::::: A
A 11111118 A C5E F-nd A ::::1::, A 1G8:::: A
@@@@@
8/9/2019 1-SQL-Basics.ppt
24/114
S&L&C. statement )ith F
Display values (or all (ields in table/
SELECT * FROM ta$lename 3
sql6 SELECT * =r"m acc"-nts3
@@@@@
A acc"-nt-m$er A acc"-ntame A clientI9 A $alance A
@@@@@
A 1111111+ A 5)Watana'"n& A ::::1::1 A +::::: AA 11111118 A C5E F-nd A ::::1::, A 1G8:::: A
@@@@@
8/9/2019 1-SQL-Basics.ppt
25/114
Quali(ying S&L&C.
Select columns (rom a table that match some criteria/
SELECT =ield1< =ield,< =ield+
FROM ta$le
WHERE c"nditi"nOR9ER B =ield1
8/9/2019 1-SQL-Basics.ppt
26/114
Strings in SQL
8/9/2019 1-SQL-Basics.ppt
27/114
&'ercises
3 2hat are the (irst 6 cities in the database>5 2hat are the 6 most populous countries in the )orld>
6 2hat is the smallest country in the )orld> :o) big>
8/9/2019 1-SQL-Basics.ppt
28/114
&'ercises (or .hailand
3 2hat is the country code (or .hailand>S&L&C. F (rom WHERE name Tailand
5 List the cities in .hailand+ sorted by largest population
to smallest
8/9/2019 1-SQL-Basics.ppt
29/114
2:&4& conditions
name Ban"# e$uality testname LIKE Ban&% pattern match
'"'-lati"n 6 1:::::
'"'-lati"n (:::::&n' 6 :
relations
GH is not e$uals
&rade I >D
8/9/2019 1-SQL-Basics.ppt
30/114
&'ercise )ith 2:&4& I 14D&4
3 2hat is the most populous country in &urope> use WHERE c"ntinent )))
5 2hat countries have name beginning )ith >
6 "n .hailand )hat cities have names like Ban
8/9/2019 1-SQL-Basics.ppt
31/114
Count *unction
Select can be used )ith (unctions+ such as C1*? FROM acc"-nts WHERE $alance:3
sql6 SELECT CO/T>*? =r"m acc"-nts3@@
A c"-nt>*? A
@@
A 8 A
@@
sql6 SELECT CO/T>*? =r"m acc"-nts
WHERE $alance 6 1::::::3
8/9/2019 1-SQL-Basics.ppt
32/114
&'ercise
3 :o) many countries are in the database>
5 :o) many cities are in China>
6 :o) many countries are in &urope>
8/9/2019 1-SQL-Basics.ppt
33/114
1ther *unctions in SQL
*unctions can have arguments+ ust like C+ Java+ etc
S/M > expression ?
MDN> expression ?
MI> expression ?CO/T> e'ressi"n ?
sql6 SELECT MDN>S-r=aceDrea? FROM c"-ntry3
1:2(8::):: >sq)#m)?
241E=/ This will NOT find the largest country!
sql6 SELECT MDN>S-r=aceDrea?
8/9/2019 1-SQL-Basics.ppt
34/114
S&L&C. (unctions
:o) many people are in the )orld>
SELECT S/M >5"'-lati"n? FROM C"-ntry3
:o) big is the largest country in Asia>
SELECT MDN>S-r=aceDrea?
FROM C"-ntry WHERE c"ntinentDsia3
2hat is the version o( MySQL>
SELECT versi"n>?3
8/9/2019 1-SQL-Basics.ppt
35/114
&'ercise
3 2hat is the total =E! o( the entire )orld>
sql> SE#EC$ sum%&'() FROM count!
3 2hat are the richest countries @=E! per person in the
)orld>
sql> SE#EC$ name* &'(+,o,ulation
FROM count!
ORDER B" &'(+,o,ulation DESC
#IMI$ -/
2hat are the most cro)ded countries @people per sur(acearea in Asia>
8/9/2019 1-SQL-Basics.ppt
36/114
&'ercise (or *unctions
:arder /
2hat are total population and total =E! o( eachcontinent>
:int/ use .RO/5 B c"ntinent
8/9/2019 1-SQL-Basics.ppt
37/114
&'pressions and Arithmetic
,ou can use expressions in SQL
Arithmetic/ @ * % sqrt>?
=rouping/ > ?
String ops/ s-$strin&> ?< -''er>?< len&t> ?
&'ample/ display GNP per person for each country
sql6 SELECT name< &n''"'-lati"n DS ca'ita&n'
FROM c"-ntry
OR9ER B ca'ita&n' 9ESC3
*alue of +, is in millions of &S Dollars.
-ow can you show per capita +, in dollars'''
alias
8/9/2019 1-SQL-Basics.ppt
38/114
&'ercise
3 2hat countries are the richest> !oorest>
Sho) the GNP per capita @in
Cro)ding re(ers to population per surface area
8/9/2019 1-SQL-Basics.ppt
39/114
2ildcards to match patterns
!attern matches/ =ield LIKE 'attern
SELECT * FROM city
WHERE name LIKE Ban%3
K means #match anything#
8/9/2019 1-SQL-Basics.ppt
40/114
Adding Ee) 4ecords
"ES&4. adds a ne) record to a table
ISERT ITO ta$le
7DL/ES > data1< data,< )))?3
sql6 ISERT ITO Dcc"-nts 7DL/ES
>,,,,,,,,< Dm'le Ric< :::::::1 1:::::::?3
P-ery OK< 1 r"! a==ected )
@@@@@
A acc"-nt-m$er A acc"-ntame A clientI9 A $alance A@@@@@
A ,,,,,,,, A Dm'le Ric A :::::::1 A1::::::: A
@@@@@
8/9/2019 1-SQL-Basics.ppt
41/114
"ES&4. into columns by name
ISERT ITO ta$le >=ield1< =ield,< )))?
7DL/ES > data1< data,< )))?3
sql6 ISERT ITO Dcc"-nts
>acc"-nt-m$er< $alance< acc"-ntame?
7DL/ES
>,,,,,,,,< 1:::::::< Dm'le Ric?3
P-ery OK< 1 r"! a==ected )
@@@@@A acc"-nt-m$er A acc"-ntame A clientI9 A $alance A
@@@@@
A ,::::::: A Dm'le Ric A A1::::::: A
@@@@@
8/9/2019 1-SQL-Basics.ppt
42/114
&'ercise
Add your home to)n to the City table
or+ add another city to the City table
sql6 ISERT ITO city
>name< c"-ntryC"de< district< '"'-lati"n?
7DL/ES
>Ban&saen< THD< C"n$-ri< +::::?3P-ery OK< 1 r"! a==ected )
he ID field has a /ualifier 0&12I,%3M3,.
(see4 D3S%I53 ity)
his means MySQL will assi"n the ID value itself.
8/9/2019 1-SQL-Basics.ppt
43/114
&'ercise
8ie) the City data that you ust added
Correct any errors using
sql6 SELECT * FROM City
WHERE City)name Ban&saen3
sql6 /59DTE City SET '"'-lati"n ++:::
WHERE City)name Ban&saen3
P-ery OK< 1 r"! a==ected )
8/9/2019 1-SQL-Basics.ppt
44/114
2arning/ "ES&4. is immediate
Change occurs immediately
unless you are using transactions
Duplicate data is possible
8/9/2019 1-SQL-Basics.ppt
45/114
6 )ays to add data to a table
3 "ES&4. command @boring
5 2rite "ES&4. commands in a te't (ile and #source#the (ile @better
sql6 SO/RCE mydata)sql
6 "M!14. command @synta' depends on DBMS/
sql6 LOD9 9DTD IFILE filename ITO table )))
8/9/2019 1-SQL-Basics.ppt
46/114
Copying Data Bet)een .ables
Suppose )e have another table named Ee)Accts Ee)Accts has accountEumber+ accountEame+
ISERT ITO table >=ield1< =ield,< )))?
SELECT =ield1< =ield,< =ield+
FROM other_table
WHERE condition3
sql6 ISERT ITO Dcc"-nts
SELECT * FROM e!Dcc"-nts
WHERE acc"-nt-m$er OT /LL3
8/9/2019 1-SQL-Basics.ppt
47/114
Change values in one or more records/
/59DTE ta$le
SET =ield1val-e1< =ield,val-e, WHERE c"nditi"n3
sql6 /59DTE citySET '"'-lati"n8::::
WHERE nameBan&saen D9 c"-ntryc"deTHD3
P-ery OK< 1 r"! a==ected >:): sec?
A name A c"-ntryc"de A district A '"'-lati"n A@@@@@A 11111111 A THD A C"n$-ri A 8:::: A
8/9/2019 1-SQL-Basics.ppt
48/114
,ou can change multiple columns/
/59DTE ta$le
SET =ield1val-e1< =ield,val-e, WHERE c"nditi"n3
sql6 /59DTE c"-ntrySET '"'-lati"n;G1:::::< &n'+8(;::
WHERE c"deTHD3
P-ery OK< 1 r"! a==ected >:): sec?
&'ample: Update population and (%) of *hailand
!ource: CI+ orld actboo /on the $eb0
8/9/2019 1-SQL-Basics.ppt
49/114
2arning/ dont (orget 2:&4&
Ma#e s-re tat y"-r WHERE cla-se selects"nly rec"rds y"- !ant t" can&eQ
sql6 /59DTE c"-ntry
SET '"'-lati"n;G1:::::< &n'+8(;:: 3
Query 1+ 57 ro)s a((ected @37 sec
han"ed every countryin the database66
1ops6
I for"ot $-3%3 ...
8/9/2019 1-SQL-Basics.ppt
50/114
2arning/
Changes occur immediately @Cant undo )0o transBe Careful! "( you (orget the 2:&4& clause it )ill
change all the ro)s in the table
sql6 /59DTE c"-ntry SET HeadO=StateO$ama3
* O"'sQ I ="r&"t WHERE ))) *@@@@@A C"de A ame A C"ntinent A HeadO=State A@@@@@A DF. A D=&anistan A Dsia A O$ama A
A L9 A eterlands A E-r"'e A O$ama AA DLB A Dl$ania A E-r"'e A O$ama AA 9D A Dl&eria A D=rica A O$ama AA DSM A Dmerican Sam"a A Oceania A O$ama AA D9 A Dnd"rra A E-r"'e A O$ama AA D.O A Dn&"la A D=rica A O$ama A
1bama rules6
8/9/2019 1-SQL-Basics.ppt
51/114
&'ercise
8/9/2019 1-SQL-Basics.ppt
52/114
Deleting 4ecords
D&L&.& one or more records
9ELETE FROM tablename WHERE condition3
&'ample/ Delete all cities )ith ?ero population
sql6 9ELETE FROM City WHERE '"'-lati"n :3
P-ery OK< ( r"!s deleted )
8/9/2019 1-SQL-Basics.ppt
53/114
2arning/ D&L&.& can delete all
D&L&.& a((ects all ro)s that match
9ELETE FROM tablename WHERE condition3
&'ample/ Delete all cities )ith ?ero population
sql6 9ELETE FROM City
WHERE '"'-lati"n :3P-ery OK< ( r"!s deleted )
8/9/2019 1-SQL-Basics.ppt
54/114
Sa(er Delete
*irst S&L&C. the key o( the ro) you )antsql> SELECT id FROM City WHERE nameBan&saen3
;8:,
"( only one match+ then delete using primary key
sql> 9ELETE FROM City WHERE id;8:,3
8/9/2019 1-SQL-Basics.ppt
55/114
4elating .ables
.he po)er o( a relational database is theability to selectively combine data (rommany tables
select data (rom multiple tables by matching values
4elationship can be/
3-to-3 student -H photograph
3-to-many country -H city
many-to-3 city -H country
many-to-many language -H country
8/9/2019 1-SQL-Basics.ppt
56/114
eys
&very table should have a primary key that uni$uely identi(ies each ro)
City
I9 >5K? ameC"-ntryC"de >FK?5"'-lati"n9istrict
C"-ntry
C"de >5K? ameC"ntinentCa'ital)))
C"-ntryC"de
sql6 9ESCRIBE C"-ntry3@@@@@@@A Field A Ty'e A -llA Key A 9e=a-lt A Etra A
@@@@@@@A C"de A car>+? A O A 5RI A A AA ame A car>(,? A O A A A AA ))) A A A A A A
8/9/2019 1-SQL-Basics.ppt
57/114
Joining .ables
4elate or # oin# tables using a condition
8/9/2019 1-SQL-Basics.ppt
58/114
&'ample/ Join Country and City
SELECT C"-ntry)ame< City)ameFROM C"-ntry< City
WHERE C"-ntry)C"de City)C"-ntryC"de D9 C"ntinent S"-t Dmerica3
C"-ntryC"de ameC"ntinentRe&i"n
S-r=aceDrea5"'-lati"n.5L"calameCa'ital
CityI9 ameC"-ntryC"de9istrict
5"'-lati"n
CountryCode N CityCountryCode
8/9/2019 1-SQL-Basics.ppt
59/114
8/9/2019 1-SQL-Basics.ppt
60/114
&'ercise/ Cities in Laos
SELECT c")ame< c)ame< c)5"'-lati"n
FROM C"-ntry c"< City c WHERE ))) D9 )))3
List the city names and city populations in Laos
8/9/2019 1-SQL-Basics.ppt
61/114
&'ercise
3 :o) can )e (ind the name o( the capital city (or eachcountry>
C"-ntryC"de >5K?
ameC"ntinentRe&i"nS-r=aceDrea5"'-lati"n.5L"calameCa'ital
CityI9 >5K?
ameC"-ntryC"de9istrict5"'-lati"n
8/9/2019 1-SQL-Basics.ppt
62/114
&'ercise Solution
List the country name and capital city name+ (or allcountries in Asia
SELECT c")name< c)name DS Ca'italCity FROM C"-ntry c"< City c
WHERE )))
D9 ))) 3
8/9/2019 1-SQL-Basics.ppt
63/114
8/9/2019 1-SQL-Basics.ppt
64/114
&'ercise
3 "n )hat countries is the .hai language spoken>5 By )hat percentage o( the people>
&'ample/
SELECT CO)name< L)lan&-a&e< L)'ercenta&e
FROM C"-ntry CO< C"-ntryLan&-a&e L WHERE )))
D9 ))) 3
8/9/2019 1-SQL-Basics.ppt
65/114
Ans)er using Aliases
"n )hat countries is Chinese the o((icial language>
SELECT C)name< L)lan&-a&e< L)'ercenta&e
FROM C"-ntry C< C"-ntryLan&-a&e L
WHERE C)c"de L)c"-ntryc"de D9 L)lan&-a&e LIKE %Cinese
D9 isO==icial T3
alias (orCountryLanguageyou can omit table name
)hen there is no ambiguity
8/9/2019 1-SQL-Basics.ppt
66/114
&'ercise
3 2hat countries use &nglish>
14D&4 the results by percentage spoken+ (romlargest to smallest K
5 "n ho) many countries is &nglish the o((iciallanguage>
Harder
6 "n the )orld+ appro'imately ho) many people speak&nglish>
sum@ Cpopulation F Lpercentage 0 3
8/9/2019 1-SQL-Basics.ppt
67/114
J1"E
Joins tables
Many (orms/
"EE&4 J1"E @include only matching columns
1
8/9/2019 1-SQL-Basics.ppt
68/114
&'ample o( a Condition Join
J1"E the CountryLanguage and Language tablesusing the country code/
SELECT CO)ame< L)lan&-a&e< L)'ercenta&e
FROM C"-ntry COOI C"-ntryLan&-a&e L
O CO)c"de L)c"-ntryc"de
WHERE )))3
8/9/2019 1-SQL-Basics.ppt
69/114
8/9/2019 1-SQL-Basics.ppt
70/114
Multiple .able Join
,ou can oin many tables at one time/
SELECT CO)name< C)*< L)lan&-a&e
FROM C"-ntry COOI C"-ntryLan&-a&e L
O CO)c"de L)c"-ntryc"de
OI City C
O CO)c"de C)c"-ntryc"de WHERE )))3 * m"re c"nditi"ns *
8/9/2019 1-SQL-Basics.ppt
71/114
More S&L&C. Synta'
8/9/2019 1-SQL-Basics.ppt
72/114
=41
.RO/5 B ))) is used )hen you )ant to apply a(unction @count+ sum+ avg to a group o( ro)s having acommon characteristic
&'ample/ :o) many countries are in each continent>
SELECT c"ntinent< c"-nt>*? FROM c"-ntry
.RO/5 B c"ntinent
8/9/2019 1-SQL-Basics.ppt
73/114
=41
FROM )))
.RO/5 B )))
8/9/2019 1-SQL-Basics.ppt
74/114
Logical operations
14 SELECT * FROM City WHERE
9istrictS"nla OR 9istrictBan"#3
AED
SELECT ame< S-r=aceDrea FROM C"-ntry WHERE
C"ntinent D=rica D9 S-r=aceDrea 6 1::::::3
E1.
SELECT * FROM Dcc"-nts WHERE
OT Dvaila$leBalance :3
8/9/2019 1-SQL-Basics.ppt
75/114
Set operations
"E
SELECT * FROM City WHERE
9istrict I >S"nla< Ban"#?3
8/9/2019 1-SQL-Basics.ppt
76/114
&'ercise (or matching
3 :o) many countries have a government that is anyform o( monarchy>
match any government containing Monarchy
:o) many are some (orm o( monarchy+ but not aConstitutional Monarchy @like .hailand>
8/9/2019 1-SQL-Basics.ppt
77/114
=41lan&-a&e?
FROM c"-ntrylan&-a&e
UUU
8/9/2019 1-SQL-Basics.ppt
78/114
=41lan&-a&e?
FROM c"-ntrylan&-a&e
WHERE isO==icialT
.RO/5 B c"-ntryc"de
=41
8/9/2019 1-SQL-Basics.ppt
79/114
=41
SELECT c"-ntryc"de< c"-nt>lan&-a&e?
FROM c"-ntrylan&-a&e
WHERE isO==icialT
.RO/5 B c"-ntryc"de
HD7I. c"-nt>lan&-a&e? 6 1
= tti : l
8/9/2019 1-SQL-Basics.ppt
80/114
=etting :elp
1nline help (or :&L! (or the mysql command
:&L! (or SQL statements
mysql6 HEL5
mysql6 HEL5 SELECT
f "y#$l doesnt have help on #%& commands' then load the (help
tables( data onto your server) *ownload help table data from+
htt,2++de3.m!sql.com+do4nloads in the #Documentation# section
S b i
8/9/2019 1-SQL-Basics.ppt
81/114
Sub$ueries
SELECT ma>'"'-lati"n? FROM c"-ntry?3
To use sub$ueries in "y#%& you need version ,)- or newer)
Subquery
& i
8/9/2019 1-SQL-Basics.ppt
82/114
&'ercise
"n )hich country do people live the longest> :o) long to they live>
SELECT ame< Li=eE'ectancy
FROM c"-ntry
WHERE Li=eE'ectancy > insert s-$q-ery ere ?
3
L"M". i t d ( b
8/9/2019 1-SQL-Basics.ppt
83/114
L"M". instead o( sub$uery
Another )ay to get a #most# or #least# result/
14D&4 results by )hat you )ant
8/9/2019 1-SQL-Basics.ppt
84/114
&'ercise
2hich nation is the most cro)ded> *ind the country )ith ma'imum population density
@population per s$ km
Sho) the name and the population density
:int/ create an alias (or a computed (ield/
sql6 SELECT name< '"'-lati"ns-r=aceDrea DS density WHERE )))
Alias/ density /N population0sur(aceArea
& i
8/9/2019 1-SQL-Basics.ppt
85/114
&'ercise
"s .hailand richer than other countries in Southest Asia> List the name and =E!0population @N)ealth
o( countries in the same region as .hailand
use a sub$uery (or #the region of Thailand #/
SELECT )))
FROM C"-ntry
WHERE re&i"n >SELECT re&i"n WHERE )))? OR9ER B )))3
order the results by wealth
& i i i lth
8/9/2019 1-SQL-Basics.ppt
86/114
&'ercise/ increasing )ealth
*hailand has decided to anne' /invade0 eitherCambodia, #aus, 1ietnam, or Malaysia.
*he invaded country $ill become part of the ne$
*hailand.
*he government $ants the combined country to bewealthier than *hailand is no$. 2$ealth2 means(%)3population.
What country should Thailand invade?
D t D (i iti C d
8/9/2019 1-SQL-Basics.ppt
87/114
Data De(inition Commands
These commands alter the structure of a database
CREATE create a .able+ "nde'+ or Database
ATER modi(y structure o( a Database or .able
DRO delete an entire .able+ "nde'+ or Database
RE"A#E rename a .able
C ti . bl
8/9/2019 1-SQL-Basics.ppt
88/114
Creating a .able
.o add a ne) table to a database/
CREDTE TDBLE ta$lename
>=ield1< =ield,< ))) ?
"'ti"ns 3
sql6 CREDTE TDBLE C/STOMER >
acc"-nt-m$er 7DRCHDR>G? OT /LL<
clientI9 7DRCHDR>8:? OT /LL< $alance 9O/BLE 9EFD/LT :<
availa$leBalance 9O/BLE 9EFD/LT :
? 3
P-ery OK< : r"!s a==ected)
!rod cti it :int
8/9/2019 1-SQL-Basics.ppt
89/114
!roductivity :int
.ype the #C4&A.& .ABL statement into a (ile #source# the (ile in mys$l/ s"-rce =ilename3
CREDTE TDBLE C/STOMER >
acc"-nt-m$er CHDR>1:? OT /LL<clientI9 7DRCHDR>8:? OT /LL<
$alance 9O/BLE 9EFD/LT :<
availa$leBalance 9O/BLE 9EFD/LT :<
5RIMDR KE> clientI9 ?
? 3
*ile/ tem'createta$le)sql
sql6 SO/RCE tem'createta$le)sql3
P-ery OK< : r"!s a==ected)
Deleting 4ecords a .able
8/9/2019 1-SQL-Basics.ppt
90/114
Deleting 4ecords a .able
,ou must speci(y a #2:&4 clause (or ro)s to delete
"( there is no #2:&4+ it deletes all rows
9ELETE FROM ta$lename
WHERE condition 3
first use SELECT to verify condition
sql6 SELECT * FROM city
WHERE nameBan&saen3
sql6 9ELETE FROM city
WHERE nameBan&saen3
P-ery OK< 1 r"! a==ected)
&'ercise
8/9/2019 1-SQL-Basics.ppt
91/114
&'ercise
Delete the city you added to the City table
1n a (riends machine+ is it deleted immediately >
Deleting a .able
8/9/2019 1-SQL-Basics.ppt
92/114
Deleting a .able
4emove a table (rom the database
9RO5 TDBLE ta$lename 3
sql6 9RO5 TDBLE C/STOMER 3
8ie)s
8/9/2019 1-SQL-Basics.ppt
93/114
8ie)s
A 8ie) is like a #virtual table# containing selected data(rom one or more real tables
C"-ntry
ame
C"ntinentC"de
)))
C"-ntryLan
&-a&eLan&-a&e
5ercenta&e
isO==icial
)))
MyView
ame
Lan&-a&e
5ercenta&e
CREDTE 7IEW My7ie! DS )))
8ie) &'ample
8/9/2019 1-SQL-Basics.ppt
94/114
8ie) &'ample
Create a vie) (or country name+ languages+ andpercentage
sql6 CREDTE 7IEW lang
DS
SELECT name< lan&-a&e< 'ercenta&e
FROM C"-ntry C< C"-ntryLan&-a&e L
WHERE C)c"de L)c"-ntryc"de
OR9ER B lan&-a&e DSC3P-ery OK< : r"!s a==ected)
sql6 SELECT * FROM lang WHERE lan&-a&eTai3
8/9/2019 1-SQL-Basics.ppt
95/114
!roductivity :int
.ype the #C4&A.& 8"&2# statement into a (ile 4ead the (ile into mys$l/ s"-rce =ilename3
CREDTE 7IEW lang DS
SELECT name< lan&-a&e< 'ercenta&e
FROM C"-ntry C< C"-ntryLan&-a&e L
WHERE C)c"de L)c"-ntryc"de3
*ile/ lan&vie!)sql
sql6 SO/RCE lan&vie!)sql3
P-ery OK< : r"!s a==ected)
&'ercise
8/9/2019 1-SQL-Basics.ppt
96/114
&'ercise
Create a vie) that sho)s these (ields/City)name as name
C"-ntry)name as c"-ntry
Re&i"n
5"'-lati"n o( the cityO==icial lan&-a&e
id "= te city
&ach person should use a di((erent name (or his vie)+ toavoid inter(ering )ith each other
List the tables in )orld @ s"! ta$les
&'ercise
8/9/2019 1-SQL-Basics.ppt
97/114
&'ercise
List the cities in Southest Asia )here &nglish is theo((icial language and population is over 3+
&'ercise
8/9/2019 1-SQL-Basics.ppt
98/114
&'ercise
Ask MySQL to #describe# your vie)
Delete your vie)/
9RO5 7IEW viewname 3
4evie)
8/9/2019 1-SQL-Basics.ppt
99/114
4evie)
2hat is the command to
3 list all the databases that you have access to>
5 use the Bank database>
6 vie) a list o( tables in Bank>
7 vie) the structure o( the Accounts table>
8/9/2019 1-SQL-Basics.ppt
100/114
SQL Qui?
Database =ame
8ocabulary
8/9/2019 1-SQL-Basics.ppt
101/114
8ocabulary
#largest # and #smallest # re(er to si?e @sur(aceArea
#most populous#+ #least populous# re(er to populationand population H @e'clude unpopulated nations
#richest #+ # poorest # means GNP per capita not total =E!+and =E! H @=E! N means no data
#most crowded # re(ers to population0sur(aceArea
Language :ints
8/9/2019 1-SQL-Basics.ppt
102/114
Language :ints
#.ortran is an official language# means its an o((iciallanguage o( the country
#Pascal is spoken unofficially # means it is spoken+ but
not an o((icial language
#/O0O& is spoken# means C1B1L is a languageand percentage H
2hat is the 2orlds Smallest Eation>
8/9/2019 1-SQL-Basics.ppt
103/114
2hat is the 2orld s Smallest Eation>
:o) big is it>
2hat is the Largest Country in A(rica>
8/9/2019 1-SQL-Basics.ppt
104/114
2hat is the Largest Country in A(rica>
Sho) the SQL :o) big is it>
2hat are the !oorest Countries inAsia>
8/9/2019 1-SQL-Basics.ppt
105/114
Asia>
must have =E! data @=E! H
List 6 poorest nations
2hat is the =E! per person>
E1.&/ =E! is measured in O3++ Multiply yourans)er by 3++ to get
8/9/2019 1-SQL-Basics.ppt
106/114
Middle &ast @region>
2hat is the =E! per person> Sho) result is
8/9/2019 1-SQL-Basics.ppt
107/114
"n )hat countries is .hai spoken>
SE#EC$ ...
FROM Count! C
5OI' Count!#anguage #
O' C.code 6 #.count!code
WHERE ...
:o) many people speak &nglish>
8/9/2019 1-SQL-Basics.ppt
108/114
:o) many people speak &nglish>
5 $ueries/ ho) many in each country
total (or )orld
SE#EC$ ...
FROM Count! C
5OI' Count!#anguage #
O' C.code 6 #.count!code
WHERE ...
:istory o( &mpires through Language
8/9/2019 1-SQL-Basics.ppt
109/114
:istory o( &mpires through Language
Empires are cultures that spread over many countries
2e can detect past &mpires by the spread of language
2hat languages are spoken in greatest number o( countries>
Can you name the &mpire>
:istory o( &mpires through Language
8/9/2019 1-SQL-Basics.ppt
110/114
:istory o( &mpires through Language
2e can detect past &mpires by the spread of language
2hat languages are spoken in greatest number o(countries>
SELECT #.language*sum%#.,ecentage7C.,o,ulation) 8S sum
FROM Count! C
OI Count!#anguage #
O C.code 6 #.count!code
.RO/5 B #.language
OR9ER B sum DESC
2hat cities have a population H PM >
8/9/2019 1-SQL-Basics.ppt
111/114
2hat cities have a population PM >
!rint city name+ population+ and country name Sort by population -- largest (irst
9:::::::::::::::::9::::::::::::9:::::::::::::::::::::::::9
; name ; ,o,ulation ; count!
8/9/2019 1-SQL-Basics.ppt
112/114
2here is Dari the 1((icial Language>
"n )hat country is Dari the o((icial language>
7 o((icial languages>
8/9/2019 1-SQL-Basics.ppt
113/114
7 o((icial languages>
2hat country in &urope has 7 o((icial languages>
SE#EC$ ...
FROM Count! C
5OI' Count!#anguage #
O' C.code 6 #.count!code WHERE ...
&RO1( B" C.code :: gou, b! count!
H8I'& ...
4esources
8/9/2019 1-SQL-Basics.ppt
114/114
4esources
MySQL http/00devmys$lcom0tech-resources0articles0
Learning SQL
http/00))))6schoolscom0s$l0nice tutorial and command re(erence