Upload
anuja-lad
View
8.533
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Citation preview
Structured Query Language
Introduction to SQLIntroduction to SQL
What is SQL?
– When a user wants to get some information from a database file, he can issue a query.
11
– A query is a user–request to retrieve data or information with a certain condition.
– SQL is a query language that allows user to specify the conditions. (instead of algorithms)
Introduction to SQLIntroduction to SQL
Concept of SQL
– The user specifies a certain condition.
11
– The result of the query will then be stored in form of a table.
– Statistical information of the data.
– The program will go through all the records in the database file and select those records that satisfy the condition.(searching).
Introduction to SQLIntroduction to SQL
How to involve SQL in FoxPro
– Before using SQL, the tables should be opened.
11
– The SQL command can be entered directly in the Command Window
– To perform exact matching, we shouldSET ANSI ON
Basic structure of an SQL queryBasic structure of an SQL query22GeneralStructure
SELECT, ALL / DISTINCT, *,AS, FROM, WHERE
Comparison IN, BETWEEN, LIKE "% _"
Grouping GROUP BY, HAVING,COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )
Display Order ORDER BY, ASC / DESC
LogicalOperators
AND, OR, NOT
Output INTO TABLE / CURSORTO FILE [ADDITIVE], TO PRINTER, TO SCREEN
Union UNION
fieldfield typetype widthwidth contentscontentsid numeric 4 student id numbername character 10 namedob date 8 date of birthsex character 1 sex: M / Fclass character 2 classhcode character 1 house code: R, Y, B, Gdcode character 3 district coderemission logical 1 fee remissionmtest numeric 2 Math test score
22 The Situation:Student ParticularsThe Situation:Student Particulars
General StructureGeneral StructureII
SELECTSELECT [[ALL / DISTINCTALL / DISTINCT] ] expr1expr1 [ [ASAS col1col1], ], expr2expr2 [ [ASAS col2col2] ] ;;
FROMFROM tablenametablename WHEREWHERE conditioncondition
SELECT ...... FROM ...... WHERE ......SELECT ...... FROM ...... WHERE ......
General StructureGeneral StructureII– The query will select rows from the source tablename and
output the result in table form.
– Expressions expr1, expr2 can be :
• (1) a column, or
• (2) an expression of functions and fields.
SELECTSELECT [[ALL / DISTINCTALL / DISTINCT] ] expr1expr1 [ [ASAS col1col1], ], expr2expr2 [ [ASAS col2col2] ] ;;
FROMFROM tablenametablename WHEREWHERE conditioncondition
– And col1, col2 are their corresponding column names in the output table.
General StructureGeneral StructureII– DISTINCT will eliminate duplication in the output while
ALL will keep all duplicated rows.
– condition can be :
• (1) an inequality, or
• (2) a string comparison
• using logical operators AND, OR, NOT.
SELECTSELECT [[ALL / DISTINCTALL / DISTINCT] ] expr1expr1 [ [ASAS col1col1], ], expr2expr2 [ [ASAS col2col2] ] ;;
FROMFROM tablenametablename WHEREWHERE conditioncondition
General StructureGeneral StructureIIBefore using SQL, open the student file:
USE studentUSE studenteg. 1eg. 1 List all the student records.List all the student records.
SELECT * FROM student
id name dob sex class mtest hcode dcode remission9801 Peter 06/04/86 M 1A 70 R SSP .F.9802 Mary 01/10/86 F 1A 92 Y HHM .F.9803 Johnny 03/16/86 M 1A 91 G SSP .T.9804 Wendy 07/09/86 F 1B 84 B YMT .F.9805 Tobe 10/17/86 M 1B 88 R YMT .F.: : : : : : : : :
Result
General StructureGeneral StructureIIeg. 2eg. 2 List the names and house code of 1A students.List the names and house code of 1A students.
SELECT name, hcode, class FROM student ;
WHERE class="1A"
Class
11AA
11AA
11AA
11BB
11BB
::
Class
11AA
11AA
11AA
11BB
11BB
::
class="1A"
General StructureGeneral StructureII
name hcode classPeter R 1AMary Y 1AJohnny G 1ALuke G 1ABobby B 1AAaron R 1A: : :
Result
eg. 2eg. 2 List the names and house code of 1A students.List the names and house code of 1A students.
General StructureGeneral StructureIIeg. 3eg. 3 List the residential district of the Red House List the residential district of the Red House
members.members.
SELECT DISTINCT dcode FROM student ;
WHERE hcode="R"
dcodeHHMKWCMKKSSPTSTYMT
Result
General StructureGeneral StructureIIeg. 4eg. 4 List the names and ages (1 d.p.) of 1B girls.List the names and ages (1 d.p.) of 1B girls.
11B Girls ?B Girls ?
Condition for "1B Condition for "1B Girls":Girls":
1)1) class = class = "1B""1B"
2)2) sex = sex = "F""F"
3)3) Both ( AND operator)Both ( AND operator)
General StructureGeneral StructureIIeg. 4eg. 4 List the names and ages (1 d.p.) of 1B girls.List the names and ages (1 d.p.) of 1B girls.
General StructureGeneral StructureIIeg. 4eg. 4 List the names and ages (1 d.p.) of 1B girls.List the names and ages (1 d.p.) of 1B girls.
What is "age"?What is "age"?
Functions:Functions:
# days :# days : DATE( ) – dobDATE( ) – dob
# years :(DATE( ) – dob) / 365# years :(DATE( ) – dob) / 365
1 d.p.:1 d.p.: ROUND(__ , 1)ROUND(__ , 1)
General StructureGeneral StructureIIeg. 4eg. 4 List the names and ages (1 d.p.) of 1B girls.List the names and ages (1 d.p.) of 1B girls.
General StructureGeneral StructureIIeg. 4eg. 4 List the names and ages (1 d.p.) of 1B girls.List the names and ages (1 d.p.) of 1B girls.
SELECT name, ROUND((DATE( )-dob)/365,1) AS age ;
FROM student WHERE class="1B" AND sex="F"
name ageWendy 12.1Kitty 11.5Janet 12.4Sandy 12.3Mimi 12.2
Result
General StructureGeneral StructureIIeg. 5eg. 5 List the names, id of 1A students with no fee List the names, id of 1A students with no fee
remission.remission.
SELECT name, id, class FROM student ;
WHERE class="1A" AND NOT remission
name id classPeter 9801 1AMary 9802 1ALuke 9810 1ABobby 9811 1AAaron 9812 1ARon 9813 1AGigi 9824 1A: : :
Result
ComparisonComparisonIIIIexprexpr IN ( IN ( value1value1, , value2value2, , value3value3))
exprexpr BETWEEN BETWEEN value1value1 AND AND value2value2
exprexpr LIKE "%_" LIKE "%_"
ComparisonComparisonIIIIeg. 6eg. 6 List the students who were born on Wednesday List the students who were born on Wednesday or or
Saturdays.Saturdays.
SELECT name, class, CDOW(dob) AS bdate ; FROM student ;
WHERE DOW(dob) IN (4,7)
name class bdatePeter 1A WednesdayWendy 1B WednesdayKevin 1C SaturdayLuke 1A WednesdayAaron 1A Saturday: : :
Result
ComparisonComparisonIIIIeg. 7eg. 7 List the students who were not born in January, List the students who were not born in January,
March, June, September.March, June, September.
SELECT name, class, dob FROM student ;
WHERE MONTH(dob) NOT IN (1,3,6,9)
name class dobWendy 1B 07/09/86Tobe 1B 10/17/86Eric 1C 05/05/87Patty 1C 08/13/87Kevin 1C 11/21/87Bobby 1A 02/16/86Aaron 1A 08/02/86: : :
Result
ComparisonComparisonIIIIeg. 8eg. 8 List the 1A students whose Math test score is List the 1A students whose Math test score is
between 80 and 90 (incl.)between 80 and 90 (incl.)
SELECT name, mtest FROM student ;
WHERE class="1A" AND ;
mtest BETWEEN 80 AND 90
name mtestLuke 86Aaron 83Gigi 84
Result
ComparisonComparisonIIIIeg. 9eg. 9 List the students whose names start with "T".List the students whose names start with "T".
SELECT name, class FROM student ;
WHERE name LIKE "T%"
name classTobe 1BTeddy 1BTim 2A
Result
ComparisonComparisonIIII eg. 10eg. 10 List the Red house members whose names contain List the Red house members whose names contain "a" as "a" as
the 2nd letter.the 2nd letter.
SELECT name, class, hcode FROM student ;
WHERE name LIKE "_a%" AND hcode="R"
name class hcodeAaron 1A RJanet 1B RPaula 2A R
Result
GroupingGroupingIIIIIISELECT ...... FROM ...... WHERE SELECT ...... FROM ...... WHERE conditioncondition ; ;GROUP BY GROUP BY groupexprgroupexpr [HAVING [HAVING requirementrequirement]]
Group functions:Group functions:
COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )
– groupexpr specifies the related rows to be grouped as one entry. Usually it is a column.
– WHERE condition specifies the condition of individual rows before the rows are group. HAVING requirement specifies the condition involving the whole group.
GroupingGroupingIIIIII eg. 11eg. 11 List the number of students of each class.List the number of students of each class.
COUNT( )COUNT( )
Group By ClassGroup By Class
11AA
COUNT( )COUNT( )11BB
COUNT( )COUNT( )11CC
11AA
11BB
11CCStudentStudent
class11AA
11AA
11AA
11BB
11BB
11BB
11BB
11BB
11BB
11CC
11CC
11CC
GroupingGroupingIIIIIISELECT class, COUNT(*) FROM student ;
GROUP BY class
class cnt1A 101B 91C 92A 82B 82C 6
eg. 11eg. 11 List the number of students of each class.List the number of students of each class.
Result
GroupingGroupingIIIIII eg. 12eg. 12 List the average Math test score of each class.List the average Math test score of each class.
Group By ClassGroup By Class
AVG( )AVG( )
AVG( )AVG( )
AVG( )AVG( )
11AA
11BB
11CCStudentStudent
class11AA
11AA
11AA
11BB
11BB
11BB
11BB
11BB
11BB
11CC
11CC
11CC
GroupingGroupingIIIIII eg. 12eg. 12 List the average Math test score of each class.List the average Math test score of each class.
SELECT class, AVG(mtest) FROM student ;GROUP BY class
class avg_mtest1A 85.901B 70.331C 37.892A 89.382B 53.132C 32.67
Result
GroupingGroupingIIIIII eg. 13eg. 13 List the number of girls of each district.List the number of girls of each district.
SELECT dcode, COUNT(*) FROM student ;
WHERE sex="F" GROUP BY dcode
dcode cntHHM 6KWC 1MKK 1SSP 5TST 4YMT 8
Result
GroupingGroupingIIIIII eg. 14eg. 14 List the max. and min. test score of Form 1 List the max. and min. test score of Form 1
students of each district.students of each district.
SELECT MAX(mtest), MIN(mtest), dcode ;
FROM student ;
WHERE class LIKE "1_" GROUP BY dcode
max_mtest min_mtest dcode92 36 HHM91 19 MKK91 31 SSP92 36 TST75 75 TSW88 38 YMT
Result
GroupingGroupingIIIIII eg. 15eg. 15 List the average Math test score of the boys in List the average Math test score of the boys in each each
class. The list should not contain class with class. The list should not contain class with less than 3 boys.less than 3 boys.
SELECT AVG(mtest), class FROM student ;
WHERE sex="M" GROUP BY class ;
HAVING COUNT(*) >= 3
avg_mtest class86.00 1A77.75 1B35.60 1C86.50 2A56.50 2B
Result
Display OrderDisplay OrderIVIVSELECT ...... FROM ...... WHERE ...... SELECT ...... FROM ...... WHERE ......
GROUP BY ..... ;GROUP BY ..... ;
ORDER BY ORDER BY colnamecolname ASC / DESC ASC / DESC
Display OrderDisplay OrderIVIVSELECT name, id FROM student ;
WHERE sex="M" AND class="1A" ORDER BY name
eg. 16eg. 16 List the boys of class 1A, order by their names.List the boys of class 1A, order by their names.
name idPeter 9801Johnny 9803Luke 9810Bobby 9811Aaron 9812Ron 9813
ORDER BY
dcode
name idAaron 9812Bobby 9811Johnny 9803Luke 9810Peter 9801Ron 9813
Result
Display OrderDisplay OrderIVIVSELECT name, id, class, dcode FROM
student ;
WHERE class="2A" ORDER BY dcode
eg. 17eg. 17 List the 2A students by their residential district.List the 2A students by their residential district.
name id class dcodeJimmy 9712 2A HHMTim 9713 2A HHMSamual 9714 2A SHTRosa 9703 2A SSPHelen 9702 2A TSTJoseph 9715 2A TSWPaula 9701 2A YMTSusan 9704 2A YMT
Result
Display OrderDisplay OrderIVIV
SELECT COUNT(*) AS cnt, dcode FROM student ;
GROUP BY dcode ORDER BY cnt DESC
eg. 18eg. 18 List the number of students of each districtList the number of students of each district
(in desc. order).(in desc. order).
cnt docode11 YMT10 HHM10 SSP9 MKK5 TST2 TSW1 KWC1 MMK1 SHT
Result
Display OrderDisplay OrderIVIV
SELECT name, class, hcode FROM student ;
WHERE sex="M" ORDER BY hcode, class
eg. 19eg. 19 List the boys of each house order by theList the boys of each house order by the classes. (2-level ordering)classes. (2-level ordering)
Display OrderDisplay OrderIVIVname hcode classBobby B 1ATeddy B 1BJoseph B 2AZion B 2BLeslie B 2CJohnny G 1ALuke G 1AKevin G 1CGeorge G 1C: : :
Result
Order by
class
BlueHouse
GreenHouse
::
Order by
hcode
OutputOutputVVINTO TABLE tablename the output table is saved as a
database file in the disk.
INTO CURSOR temp the output is stored in theworking memory temporarily.
TO FILE filename [ADDITIVE] output to a text file.(additive = append)
TO PRINTER send to printer.
TO SCREEN display on screen.
OutputOutputVVeg. 20eg. 20 List the students in desc. order of their names and List the students in desc. order of their names and save the save the
result as a database file name.dbf.result as a database file name.dbf.
SELECT * FROM student ;
ORDER BY name DESC INTO TABLE name.dbf
id name dob sex class mtest hcode dcode remission9707 Zion 07/29/85 M 2B 51 B MKK .F.9709 Yvonne 08/24/85 F 2C 10 R TST .F.9804 Wendy 07/09/86 F 1B 84 B YMT .F.9819 Vincent 03/15/85 M 1C 29 Y MKK .F.9805 Tobe 10/17/86 M 1B 88 R YMT .F.9713 Tim 06/19/85 M 2A 91 R HHM .T.9816 Teddy 01/30/86 M 1B 64 B SSP .F.: : : : : : : : :
Result
OutputOutputVVeg. 21eg. 21 Print the Red House members by their classes, sex Print the Red House members by their classes, sex and and
name.name.
SELECT class, name, sex FROM student ;
WHERE hcode="R" ;
ORDER BY class, sex DESC, name TO PRINTERclass name sex1A Aaron M1A Peter M1A Ron M1B Tobe M1B Janet F1B Kitty F1B Mimi F: : :
Result
Union, Intersection and Union, Intersection and Difference of TablesDifference of Tables33
A B
The union of A and B (AB)
A table containing all the rows from A and B.
Union, Intersection and Union, Intersection and Difference of TablesDifference of Tables33
The intersection of A and B (AB)
A table containing only rows that appear in both A and B.
A B
Union, Intersection and Union, Intersection and Difference of TablesDifference of Tables33
The difference of A and B (A–B)
A table containing rows that appear in A but not in B.
A B
33Consider the members of the Bridge Club and Consider the members of the Bridge Club and the Chess Club. The two database files have the Chess Club. The two database files have the same structure:the same structure:
The Situation: Bridge Club & Chess ClubThe Situation: Bridge Club & Chess Club
field type width contentsid numeric 4 student id numbername character 10 namesex character 1 sex: M / Fclass character 2 class
Union, Intersection and Union, Intersection and Difference of TablesDifference of Tables33
Before using SQL, open the two tables:Before using SQL, open the two tables:
Bridge [A] Chess [B]
id name sex class id name sex class
1 9812 Aaron M 1A 1 9802 Mary F 1A
2 9801 Peter M 1A 2 9801 Peter M 1A
3 9814 Kenny M 1B 3 9815 Eddy M 1B
4 9806 Kitty F 1B 4 9814 Kenny M 1B
5 9818 Edmond M 1C 5 9817 George M 1C: : : : : : : :
SELECT ASELECT AUSE bridgeUSE bridgeSELECT BSELECT BUSE chessUSE chess
Union, Intersection and Union, Intersection and Difference of TablesDifference of Tables33
SELECT * FROM bridge ;
UNION ;
SELECT * FROM chess ;
ORDER BY class, name INTO TABLE party
eg. 22eg. 22 The two clubs want to hold a joint party.The two clubs want to hold a joint party. Make Make a list of all students. (Union)a list of all students. (Union)
SELECT ...... FROM ...... WHERE ...... ;SELECT ...... FROM ...... WHERE ...... ;
UNION ;UNION ;
SELECT ...... FROM ...... WHERE ......SELECT ...... FROM ...... WHERE ......
Result
Union, Intersection and Union, Intersection and Difference of TablesDifference of Tables33
SELECT * FROM bridge ;
WHERE id IN ( SELECT id FROM chess ) ;
TO PRINTER
eg. 23eg. 23 Print a list of students who are members of both Print a list of students who are members of both clubs. clubs. (Intersection)(Intersection)
SELECT ...... FROM SELECT ...... FROM table1table1 ; ;
WHERE WHERE colcol IN ( SELECT IN ( SELECT colcol FROM FROM table2table2 ) )
Result
Union, Intersection and Union, Intersection and Difference of TablesDifference of Tables33
SELECT * FROM bridge ;
WHERE id NOT IN ( SELECT id FROM chess ) ;
INTO TABLE diff
eg. 24eg. 24 Make a list of students who are members of the Make a list of students who are members of the Bridge Bridge Club but not Chess Club. (Difference)Club but not Chess Club. (Difference)
SELECT ...... FROM SELECT ...... FROM table1table1 ; ;
WHERE WHERE colcol NOT IN ( SELECT NOT IN ( SELECT colcol FROM FROM table2table2 ) )
Result
Multiple Tables:Multiple Tables:44• SQL provides a convenient operation to SQL provides a convenient operation to
retrieve information from multiple retrieve information from multiple tables. tables. • This operation is called This operation is called joinjoin. .
• The join operation will The join operation will combinecombine the tables the tables into into one large table with all possible one large table with all possible combinations combinations (Math: Cartesian Product), and then (Math: Cartesian Product), and then it will filter it will filter the rows of this combined table to the rows of this combined table to yield useful yield useful information.information.
Multiple Tables:Multiple Tables:44field1
A
B
field21
2
3
field1 field2A
A
A
1
2
3
B
B
B
1
2
3
44Each student should learn a musical instrument.Each student should learn a musical instrument.Two database files:Two database files: student.dbfstudent.dbf && music.dbfmusic.dbfThe common field: The common field: student idstudent id
fieldfield typetype widthwidth contentscontents idid numeric numeric 4 4 student id number student id number typetype character character 10 10 type of the music instrument type of the music instrument
The Situation:Music LessonThe Situation:Music Lesson
SELECT ASELECT AUSE studentUSE studentSELECT BSELECT BUSE musicUSE music
Natural JoinNatural Join44A A Natural JoinNatural Join is a join operation that joins two is a join operation that joins two tables bytables by their common column. This their common column. This operation is similar to the setting relation of two operation is similar to the setting relation of two tables.tables.
SELECT a.comcol, a.SELECT a.comcol, a.col1col1, b., b.col2col2, , expr1expr1, , expr2expr2 ; ;
FROM FROM table1table1 a, a, table2table2 b ; b ;
WHERE a.WHERE a.comcolcomcol = b. = b.comcolcomcol
Natural JoinNatural Join44
MusicMusic
idid
98019801
typetype
StudentStudent
98019801
idid namename classclass
98019801
ProductProduct
idid namename classclass typetype
Same idSame id
JoinJoin
eg. 25eg. 25 Make a list of students and the instruments Make a list of students and the instruments they they learn. (Natural Join)learn. (Natural Join)
SELECT s.class, s.name, s.id, m.type ;
FROM student s, music m ;
WHERE s.id=m.id ORDER BY class, name
Natural JoinNatural Join44
class name id type1A Aaron 9812 Piano1A Bobby 9811 Flute1A Gigi 9824 Recorder1A Jill 9820 Piano1A Johnny 9803 Violin1A Luke 9810 Piano1A Mary 9802 Flute: : : :
Result
eg. 25eg. 25 Make a list of students and the instruments they Make a list of students and the instruments they learn. learn. (Natural Join)(Natural Join)
eg. 26eg. 26 Find the number of students learning piano in Find the number of students learning piano in each each class.class.
Natural JoinNatural Join44
Three Parts :Three Parts :
(1)(1) Natural Join.Natural Join.
(2)(2) Condition: Condition: m.type="Piano"m.type="Piano"
(3)(3) GROUP BY classGROUP BY class
Natural JoinNatural Join44
MusicMusic
StudentStudent
ProductProduct
JoinJoin ConditionConditionm.type= "Piano"m.type= "Piano"
Group ByGroup By
classclass
eg. 26eg. 26
eg. 26eg. 26 Find the number of students learning piano in Find the number of students learning piano in each each class.class.
SELECT s.class, COUNT(*) ;
FROM student s, music m ;
WHERE s.id=m.id AND m.type="Piano" ;
GROUP BY class ORDER BY class
Natural JoinNatural Join44
class cnt1A 41B 21C 1
Result
An An Outer JoinOuter Join is a join operation that includes is a join operation that includes rows that have a match, plus rows that do not rows that have a match, plus rows that do not have a match in the other table.have a match in the other table.
Outer JoinOuter Join44
eg. 27eg. 27 List the students who have not yet chosen an List the students who have not yet chosen an instrument. (No match)instrument. (No match)
Outer JoinOuter Join44
No matchNo match
MusicMusic
idid typetype
StudentStudent
98019801
idid namename classclass
eg. 27eg. 27 List the students who have not yet chosen an List the students who have not yet chosen an instrument. (No match)instrument. (No match)
SELECT class, name, id FROM student ;
WHERE id NOT IN ( SELECT id FROM music ) ;
ORDER BY class, name
Outer JoinOuter Join44
Resultclass name id1A Mandy 98211B Kenny 98141B Tobe 98051C Edmond 98181C George 9817: : :
eg. 28eg. 28 Make a checking list of students and the Make a checking list of students and the instruments they learn. instruments they learn. The list should also The list should also contain the students without an instrument.contain the students without an instrument.
(Outer Join)(Outer Join)
Outer JoinOuter Join44
Outer JoinOuter Join44Natural JoinNatural Join
No MatchNo Match
Outer JoinOuter Join
eg. 28eg. 28
SELECT s.class, s.name, s.id, m.type ;
FROM student s, music m ;
WHERE s.id=m.id ;
Outer JoinOuter Join44UNION ;
SELECT class, name, id, "" ;
FROM student ;
WHERE id NOT IN ( SELECT id FROM music ) ;
ORDER BY 1, 2
eg. 28eg. 28
Outer JoinOuter Join44
emptyclass name id1A Mandy 98211B Kenny 98141B Tobe 98051C Edmond 98181C George 9817: : :
No Match
class name id type1A Aaron 9812 Piano1A Bobby 9811 Flute1A Gigi 9824 Recorder1A Jill 9820 Piano1A Johnny 9803 Violin1A Luke 9810 Piano1A Mary 9802 Flute: : : :
Natural Join
class name id type
1A Aaron 9812 Piano
1A Bobby 9811 Flute
1A Gigi 9824 Recorder
1A Jill 9820 Piano
1A Johnny 9803 Violin
1A Luke 9810 Piano
1A Mandy 9821
1A Mary 9802 Flute
1A Peter 9801 Piano
1A Ron 9813 Guitar
1B Eddy 9815 Piano
1B Janet 9822 Guitar
1B Kenny 9814
1B Kitty 9806 Recorder
: : : :
Outer Join