SlideShare a Scribd company logo
1 of 68
Download to read offline
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 should
SET ANSI ON
Basic structure of an SQLBasic structure of an SQL
queryquery22
General
Structure
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
Logical
Operators
AND, OR, NOT
Output INTO TABLE / CURSOR
TO FILE [ADDITIVE], TO PRINTER, TO SCREEN
Union UNION
fieldfield typetype widthwidth contentscontents
id numeric 4 student id number
name character 10 name
dob date 8 date of birth
sex character 1 sex: M / F
class character 2 class
hcode character 1 house code: R, Y, B, G
dcode character 3 district code
remission logical 1 fee remission
mtest numeric 2 Math test score
22 The Situation:
Student Particulars
General StructureGeneral Structure
II
SELECTSELECT [[ALL / DISTINCTALL / DISTINCT]] expr1expr1 [[ASAS col1col1],], expr2expr2 [[ASAS col2col2]] ;;
FROMFROM tablenametablename WHEREWHERE conditioncondition
SELECT ...... FROM ...... WHERE ......SELECT ...... FROM ...... WHERE ......
General StructureGeneral Structure
II
– 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 Structure
II
– 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 Structure
II Before using SQL, open the student file:
USE studentUSE student
eg. 1eg. 1 List all the student records.List all the student records.
SELECT * FROM student
id name dob sex class mtest hcode dcode remission
9801 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 Structure
IIeg. 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
1A1A
1A1A
1A1A
1B1B
1B1B
::

Class
1A1A
1A1A
1A1A
1B1B
1B1B
::




class="1A"
General StructureGeneral Structure
II
name hcode class
Peter R 1A
Mary Y 1A
Johnny G 1A
Luke G 1A
Bobby B 1A
Aaron 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 Structure
IIeg. 3eg. 3 List the residential district of the Red HouseList the residential district of the Red House members.members.
SELECT DISTINCT dcode FROM student ;
WHERE hcode="R"
dcode
HHM
KWC
MKK
SSP
TST
YMT
Result
General StructureGeneral Structure
IIeg. 4eg. 4 List the names and ages (1 d.p.) of 1B girls.List the names and ages (1 d.p.) of 1B girls.
1B Girls ?1B Girls ?
Condition for "1BCondition 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 Structure
IIeg. 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 Structure
IIeg. 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 Structure
IIeg. 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 Structure
IIeg. 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 age
Wendy 12.1
Kitty 11.5
Janet 12.4
Sandy 12.3
Mimi 12.2
Result
General StructureGeneral Structure
IIeg. 5eg. 5 List the names, id of 1A students with no feeList 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 class
Peter 9801 1A
Mary 9802 1A
Luke 9810 1A
Bobby 9811 1A
Aaron 9812 1A
Ron 9813 1A
Gigi 9824 1A
: : :
Result
ComparisonComparison
IIII exprexpr IN (IN ( value1value1,, value2value2,, value3value3))
exprexpr BETWEENBETWEEN value1value1 ANDAND value2value2
exprexpr LIKE "%_"LIKE "%_"
ComparisonComparison
IIIIeg. 6eg. 6 List the students who were born on WednesdayList the students who were born on Wednesday or Saturdays.or Saturdays.
SELECT name, class, CDOW(dob) AS bdate ;
FROM student ;
WHERE DOW(dob) IN (4,7)
name class bdate
Peter 1A Wednesday
Wendy 1B Wednesday
Kevin 1C Saturday
Luke 1A Wednesday
Aaron 1A Saturday
: : :
Result
ComparisonComparison
IIIIeg. 7eg. 7 List the students who were not born in January,List the students who were not born in January, March, June,March, June,
September.September.
SELECT name, class, dob FROM student ;
WHERE MONTH(dob) NOT IN (1,3,6,9)
name class dob
Wendy 1B 07/09/86
Tobe 1B 10/17/86
Eric 1C 05/05/87
Patty 1C 08/13/87
Kevin 1C 11/21/87
Bobby 1A 02/16/86
Aaron 1A 08/02/86
: : :
Result
ComparisonComparison
IIIIeg. 8eg. 8 List the 1A students whose Math test score isList the 1A students whose Math test score is between 80 and 90between 80 and 90
(incl.)(incl.)
SELECT name, mtest FROM student ;
WHERE class="1A" AND ;
mtest BETWEEN 80 AND 90
name mtest
Luke 86
Aaron 83
Gigi 84
Result
ComparisonComparison
IIIIeg. 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 class
Tobe 1B
Teddy 1B
Tim 2A
Result
ComparisonComparison
IIIIeg. 10eg. 10 List the Red house members whose names containList the Red house members whose names contain "a" as the 2nd"a" as the 2nd
letter.letter.
SELECT name, class, hcode FROM student ;
WHERE name LIKE "_a%" AND hcode="R"
name class hcode
Aaron 1A R
Janet 1B R
Paula 2A R
Result
GroupingGroupingIIIIII
SELECT ...... FROM ...... WHERESELECT ...... FROM ...... WHERE conditioncondition ;;
GROUP BYGROUP 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
1A1A
COUNT( )COUNT( )
1B1B
COUNT( )COUNT( )
1C1C
1A1A
1B1B
1C1C
StudentStudent
class
1A1A
1A1A
1A1A
1B1B
1B1B
1B1B
1B1B
1B1B
1B1B
1C1C
1C1C
1C1C
GroupingGroupingIIIIII
SELECT class, COUNT(*) FROM student ;
GROUP BY class
class cnt
1A 10
1B 9
1C 9
2A 8
2B 8
2C 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( )
1A1A
1B1B
1C1C
StudentStudent
class
1A1A
1A1A
1A1A
1B1B
1B1B
1B1B
1B1B
1B1B
1B1B
1C1C
1C1C
1C1C
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_mtest
1A 85.90
1B 70.33
1C 37.89
2A 89.38
2B 53.13
2C 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 cnt
HHM 6
KWC 1
MKK 1
SSP 5
TST 4
YMT 8
Result
GroupingGroupingIIIIII
eg. 14eg. 14 List the max. and min. test score of Form 1List the max. and min. test score of Form 1 students of eachstudents of each
district.district.
SELECT MAX(mtest), MIN(mtest), dcode ;
FROM student ;
WHERE class LIKE "1_" GROUP BY dcode
max_mtest min_mtest dcode
92 36 HHM
91 19 MKK
91 31 SSP
92 36 TST
75 75 TSW
88 38 YMT
Result
GroupingGroupingIIIIII
eg. 15eg. 15 List the average Math test score of the boys inList the average Math test score of the boys in each class. The listeach class. The list
should not contain class withshould 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 class
86.00 1A
77.75 1B
35.60 1C
86.50 2A
56.50 2B
Result
Display OrderDisplay OrderIVIV
SELECT ...... FROM ...... WHERE ......SELECT ...... FROM ...... WHERE ......
GROUP BY ..... ;GROUP BY ..... ;
ORDER BYORDER BY colnamecolname ASC / DESCASC / DESC
Display OrderDisplay OrderIVIV
SELECT 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 id
Peter 9801
Johnny 9803
Luke 9810
Bobby 9811
Aaron 9812
Ron 9813
ORDER BY
dcode
name id
Aaron 9812
Bobby 9811
Johnny 9803
Luke 9810
Peter 9801
Ron 9813
Result
Display OrderDisplay OrderIVIV
SELECT 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 dcode
Jimmy 9712 2A HHM
Tim 9713 2A HHM
Samual 9714 2A SHT
Rosa 9703 2A SSP
Helen 9702 2A TST
Joseph 9715 2A TSW
Paula 9701 2A YMT
Susan 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 docode
11 YMT
10 HHM
10 SSP
9 MKK
5 TST
2 TSW
1 KWC
1 MMK
1 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-levelclasses. (2-level
ordering)ordering)
Display OrderDisplay OrderIVIV
name hcode class
Bobby B 1A
Teddy B 1B
Joseph B 2A
Zion B 2B
Leslie B 2C
Johnny G 1A
Luke G 1A
Kevin G 1C
George G 1C
: : :
Result
Order
by
class
Blue
House
Green
House
:
:
Order
by
hcode
OutputOutput
VV
INTO TABLE tablename the output table is saved as a
database file in the disk.
INTO CURSOR temp the output is stored in the
working memory temporarily.
TO FILE filename [ADDITIVE] output to a text file.
(additive = append)
TO PRINTER send to printer.
TO SCREEN display on screen.
OutputOutput
VVeg. 20eg. 20 List the students in desc. order of their names andList the students in desc. order of their names and save the resultsave the result
as a database file name.dbf.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 remission
9707 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
OutputOutput
VVeg. 21eg. 21 Print the Red House members by their classes, sexPrint the Red House members by their classes, sex and name.and name.
SELECT class, name, sex FROM student ;
WHERE hcode="R" ;
ORDER BY class, sex DESC, name TO PRINTER
class name sex
1A Aaron M
1A Peter M
1A Ron M
1B Tobe M
1B Janet F
1B Kitty F
1B Mimi F
: : :
Result
Union, Intersection andUnion, Intersection and
Difference of TablesDifference of Tables33
A B
The union of A and B (A∪B)
A table containing all the rows from A and B.
Union, Intersection andUnion, Intersection and
Difference of TablesDifference of Tables33
The intersection of A and B (A∩B)
A table containing only rows that appear in both A and B.
A B
Union, Intersection andUnion, 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
33
Consider the members of the Bridge Club andConsider the members of the Bridge Club and
the Chess Club. The two database files havethe Chess Club. The two database files have
the same structure:the same structure:
The Situation:
Bridge Club & Chess Club
field type width contents
id numeric 4 student id number
name character 10 name
sex character 1 sex: M / F
class character 2 class
Union, Intersection andUnion, 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 A
USE bridgeUSE bridge
SELECT BSELECT B
USE chessUSE chess
Union, Intersection andUnion, 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 a list of allMake a list of all
students. (Union)students. (Union)
SELECT ...... FROM ...... WHERE ...... ;SELECT ...... FROM ...... WHERE ...... ;
UNION ;UNION ;
SELECT ...... FROM ...... WHERE ......SELECT ...... FROM ...... WHERE ......
Result
Union, Intersection andUnion, 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 bothPrint a list of students who are members of both clubs.clubs.
(Intersection)(Intersection)
SELECT ...... FROMSELECT ...... FROM table1table1 ;;
WHEREWHERE colcol IN ( SELECTIN ( SELECT colcol FROMFROM table2table2 ))
Result
Union, Intersection andUnion, 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 theMake a list of students who are members of the Bridge Club butBridge Club but
not Chess Club. (Difference)not Chess Club. (Difference)
SELECT ...... FROMSELECT ...... FROM table1table1 ;;
WHEREWHERE colcol NOT IN ( SELECTNOT IN ( SELECT colcol FROMFROM table2table2 ))
Result
Multiple Tables:Multiple Tables:44
• SQL provides a convenient operation toSQL provides a convenient operation to
retrieve information from multiple tables.retrieve information from multiple tables.
• This operation is calledThis operation is called joinjoin..
• The join operation willThe join operation will combinecombine the tables intothe tables into
one large table with all possible combinationsone large table with all possible combinations
(Math: Cartesian Product), and then it will(Math: Cartesian Product), and then it will
filterfilter the rows of this combined table to yieldthe rows of this combined table to yield
usefuluseful information.information.
Multiple Tables:Multiple Tables:44
field1
A
B
field2
1
2
3
field1 field2
A
A
A
1
2
3
B
B
B
1
2
3
44
Each student should learn a musical instrument.Each student should learn a musical instrument.
Two database files:Two database files: student.dbfstudent.dbf && music.dbfmusic.dbf
The common field:The common field: student idstudent id
fieldfield typetype widthwidth contentscontents
idid numericnumeric 44 student id numberstudent id number
typetype charactercharacter 1010 type of the music instrumenttype of the music instrument
The Situation:
Music Lesson
SELECT ASELECT A
USE studentUSE student
SELECT BSELECT B
USE musicUSE music
Natural JoinNatural Join44
AA Natural JoinNatural Join is a join operation that joins twois a join operation that joins two
tables bytables by their common column. This operationtheir common column. This operation
is similar to the setting relation of two tables.is similar to the setting relation of two tables.
SELECT a.comcol, a.SELECT a.comcol, a.col1col1, b., b.col2col2,, expr1expr1,, expr2expr2 ;;
FROMFROM 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 theyMake a list of students and the instruments 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 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 Mary 9802 Flute
: : : :
Result
eg. 25eg. 25 Make a list of students and the instruments theyMake a list of students and the instruments they learn.learn.
(Natural Join)(Natural Join)
eg. 26eg. 26 Find the number of students learning piano inFind the number of students learning piano in each class.each 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
ConditionCondition
m.type= "Piano"m.type= "Piano"
Group ByGroup By
classclass
eg. 26eg. 26
eg. 26eg. 26 Find the number of students learning piano inFind the number of students learning piano in each class.each 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 cnt
1A 4
1B 2
1C 1
Result
AnAn Outer JoinOuter Join is a join operation that includesis a join operation that includes
rows that have a match, plus rows that do notrows 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 anList the students who have not yet chosen an instrument. (Noinstrument. (No
match)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 anList the students who have not yet chosen an instrument. (Noinstrument. (No
match)match)
SELECT class, name, id FROM student ;
WHERE id NOT IN ( SELECT id FROM music ) ;
ORDER BY class, name
Outer JoinOuter Join44
Result
class name id
1A Mandy 9821
1B Kenny 9814
1B Tobe 9805
1C Edmond 9818
1C George 9817
: : :
eg. 28eg. 28 Make a checking list of students and theMake a checking list of students and the instruments they learn. The listinstruments they learn. The list
should alsoshould also contain the students without an instrument.contain the students without an instrument.
(Outer Join)(Outer Join)
Outer JoinOuter Join44
Outer JoinOuter Join44
Natural 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 Join44
UNION ;
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 id
1A Mandy 9821
1B Kenny 9814
1B Tobe 9805
1C Edmond 9818
1C George 9817
: : :
No Match
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 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

More Related Content

Similar to Sqlppt 120914120535-phpapp01

Similar to Sqlppt 120914120535-phpapp01 (11)

Postgresql Server Programming
Postgresql Server ProgrammingPostgresql Server Programming
Postgresql Server Programming
 
The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88
 
More SQL in MySQL 8.0
More SQL in MySQL 8.0More SQL in MySQL 8.0
More SQL in MySQL 8.0
 
SQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question BankSQL-RDBMS Queries and Question Bank
SQL-RDBMS Queries and Question Bank
 
Unit 3-Select Options and Aggregate Functions in SQL (1).pptx
Unit 3-Select Options and Aggregate Functions in SQL (1).pptxUnit 3-Select Options and Aggregate Functions in SQL (1).pptx
Unit 3-Select Options and Aggregate Functions in SQL (1).pptx
 
Sql
SqlSql
Sql
 
Dbms record
Dbms recordDbms record
Dbms record
 
SQL logical operators
SQL logical operatorsSQL logical operators
SQL logical operators
 
dbms.pdf
dbms.pdfdbms.pdf
dbms.pdf
 
STUDENT DETAILS DATABASE.pptx
STUDENT DETAILS DATABASE.pptxSTUDENT DETAILS DATABASE.pptx
STUDENT DETAILS DATABASE.pptx
 
RDBMS Algebra
RDBMS AlgebraRDBMS Algebra
RDBMS Algebra
 

More from Ankit Dubey

Unit 1 android and it's tools quiz {mad cwipedia}
Unit 1 android and it's tools quiz {mad cwipedia}Unit 1 android and it's tools quiz {mad cwipedia}
Unit 1 android and it's tools quiz {mad cwipedia}Ankit Dubey
 
Ch5 cpu-scheduling
Ch5 cpu-schedulingCh5 cpu-scheduling
Ch5 cpu-schedulingAnkit Dubey
 
Ch2 system structure
Ch2 system structureCh2 system structure
Ch2 system structureAnkit Dubey
 
Ch1 introduction-to-os
Ch1 introduction-to-osCh1 introduction-to-os
Ch1 introduction-to-osAnkit Dubey
 
Mongodb mock test_ii
Mongodb mock test_iiMongodb mock test_ii
Mongodb mock test_iiAnkit Dubey
 
Android mock test_iii
Android mock test_iiiAndroid mock test_iii
Android mock test_iiiAnkit Dubey
 
Android mock test_ii
Android mock test_iiAndroid mock test_ii
Android mock test_iiAnkit Dubey
 
Ajp notes-chapter-06
Ajp notes-chapter-06Ajp notes-chapter-06
Ajp notes-chapter-06Ankit Dubey
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05Ankit Dubey
 
Ajp notes-chapter-04
Ajp notes-chapter-04Ajp notes-chapter-04
Ajp notes-chapter-04Ankit Dubey
 
Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03Ankit Dubey
 

More from Ankit Dubey (20)

Unit 1 android and it's tools quiz {mad cwipedia}
Unit 1 android and it's tools quiz {mad cwipedia}Unit 1 android and it's tools quiz {mad cwipedia}
Unit 1 android and it's tools quiz {mad cwipedia}
 
Scheduling
Scheduling Scheduling
Scheduling
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Ch5 cpu-scheduling
Ch5 cpu-schedulingCh5 cpu-scheduling
Ch5 cpu-scheduling
 
Ch4 threads
Ch4 threadsCh4 threads
Ch4 threads
 
Ch3 processes
Ch3 processesCh3 processes
Ch3 processes
 
Ch2 system structure
Ch2 system structureCh2 system structure
Ch2 system structure
 
Ch1 introduction-to-os
Ch1 introduction-to-osCh1 introduction-to-os
Ch1 introduction-to-os
 
Android i
Android iAndroid i
Android i
 
Mongodb mock test_ii
Mongodb mock test_iiMongodb mock test_ii
Mongodb mock test_ii
 
Android mock test_iii
Android mock test_iiiAndroid mock test_iii
Android mock test_iii
 
Android mock test_ii
Android mock test_iiAndroid mock test_ii
Android mock test_ii
 
Ajp notes-chapter-06
Ajp notes-chapter-06Ajp notes-chapter-06
Ajp notes-chapter-06
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
Ajp notes-chapter-04
Ajp notes-chapter-04Ajp notes-chapter-04
Ajp notes-chapter-04
 
Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 

Sqlppt 120914120535-phpapp01

  • 2. 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)
  • 3. 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).
  • 4. 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 should SET ANSI ON
  • 5. Basic structure of an SQLBasic structure of an SQL queryquery22 General Structure 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 Logical Operators AND, OR, NOT Output INTO TABLE / CURSOR TO FILE [ADDITIVE], TO PRINTER, TO SCREEN Union UNION
  • 6. fieldfield typetype widthwidth contentscontents id numeric 4 student id number name character 10 name dob date 8 date of birth sex character 1 sex: M / F class character 2 class hcode character 1 house code: R, Y, B, G dcode character 3 district code remission logical 1 fee remission mtest numeric 2 Math test score 22 The Situation: Student Particulars
  • 7. General StructureGeneral Structure II SELECTSELECT [[ALL / DISTINCTALL / DISTINCT]] expr1expr1 [[ASAS col1col1],], expr2expr2 [[ASAS col2col2]] ;; FROMFROM tablenametablename WHEREWHERE conditioncondition SELECT ...... FROM ...... WHERE ......SELECT ...... FROM ...... WHERE ......
  • 8. General StructureGeneral Structure II – 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.
  • 9. General StructureGeneral Structure II – 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
  • 10. General StructureGeneral Structure II Before using SQL, open the student file: USE studentUSE student eg. 1eg. 1 List all the student records.List all the student records. SELECT * FROM student id name dob sex class mtest hcode dcode remission 9801 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
  • 11. General StructureGeneral Structure IIeg. 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 1A1A 1A1A 1A1A 1B1B 1B1B ::  Class 1A1A 1A1A 1A1A 1B1B 1B1B ::     class="1A"
  • 12. General StructureGeneral Structure II name hcode class Peter R 1A Mary Y 1A Johnny G 1A Luke G 1A Bobby B 1A Aaron R 1A : : : Result eg. 2eg. 2 List the names and house code of 1A students.List the names and house code of 1A students.
  • 13. General StructureGeneral Structure IIeg. 3eg. 3 List the residential district of the Red HouseList the residential district of the Red House members.members. SELECT DISTINCT dcode FROM student ; WHERE hcode="R" dcode HHM KWC MKK SSP TST YMT Result
  • 14. General StructureGeneral Structure IIeg. 4eg. 4 List the names and ages (1 d.p.) of 1B girls.List the names and ages (1 d.p.) of 1B girls. 1B Girls ?1B Girls ?
  • 15. Condition for "1BCondition 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 Structure IIeg. 4eg. 4 List the names and ages (1 d.p.) of 1B girls.List the names and ages (1 d.p.) of 1B girls.
  • 16. General StructureGeneral Structure IIeg. 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"?
  • 17. 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 Structure IIeg. 4eg. 4 List the names and ages (1 d.p.) of 1B girls.List the names and ages (1 d.p.) of 1B girls.
  • 18. General StructureGeneral Structure IIeg. 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 age Wendy 12.1 Kitty 11.5 Janet 12.4 Sandy 12.3 Mimi 12.2 Result
  • 19. General StructureGeneral Structure IIeg. 5eg. 5 List the names, id of 1A students with no feeList 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 class Peter 9801 1A Mary 9802 1A Luke 9810 1A Bobby 9811 1A Aaron 9812 1A Ron 9813 1A Gigi 9824 1A : : : Result
  • 20. ComparisonComparison IIII exprexpr IN (IN ( value1value1,, value2value2,, value3value3)) exprexpr BETWEENBETWEEN value1value1 ANDAND value2value2 exprexpr LIKE "%_"LIKE "%_"
  • 21. ComparisonComparison IIIIeg. 6eg. 6 List the students who were born on WednesdayList the students who were born on Wednesday or Saturdays.or Saturdays. SELECT name, class, CDOW(dob) AS bdate ; FROM student ; WHERE DOW(dob) IN (4,7) name class bdate Peter 1A Wednesday Wendy 1B Wednesday Kevin 1C Saturday Luke 1A Wednesday Aaron 1A Saturday : : : Result
  • 22. ComparisonComparison IIIIeg. 7eg. 7 List the students who were not born in January,List the students who were not born in January, March, June,March, June, September.September. SELECT name, class, dob FROM student ; WHERE MONTH(dob) NOT IN (1,3,6,9) name class dob Wendy 1B 07/09/86 Tobe 1B 10/17/86 Eric 1C 05/05/87 Patty 1C 08/13/87 Kevin 1C 11/21/87 Bobby 1A 02/16/86 Aaron 1A 08/02/86 : : : Result
  • 23. ComparisonComparison IIIIeg. 8eg. 8 List the 1A students whose Math test score isList the 1A students whose Math test score is between 80 and 90between 80 and 90 (incl.)(incl.) SELECT name, mtest FROM student ; WHERE class="1A" AND ; mtest BETWEEN 80 AND 90 name mtest Luke 86 Aaron 83 Gigi 84 Result
  • 24. ComparisonComparison IIIIeg. 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 class Tobe 1B Teddy 1B Tim 2A Result
  • 25. ComparisonComparison IIIIeg. 10eg. 10 List the Red house members whose names containList the Red house members whose names contain "a" as the 2nd"a" as the 2nd letter.letter. SELECT name, class, hcode FROM student ; WHERE name LIKE "_a%" AND hcode="R" name class hcode Aaron 1A R Janet 1B R Paula 2A R Result
  • 26. GroupingGroupingIIIIII SELECT ...... FROM ...... WHERESELECT ...... FROM ...... WHERE conditioncondition ;; GROUP BYGROUP 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.
  • 27. GroupingGroupingIIIIII eg. 11eg. 11 List the number of students of each class.List the number of students of each class.
  • 28. COUNT( )COUNT( ) Group By ClassGroup By Class 1A1A COUNT( )COUNT( ) 1B1B COUNT( )COUNT( ) 1C1C 1A1A 1B1B 1C1C StudentStudent class 1A1A 1A1A 1A1A 1B1B 1B1B 1B1B 1B1B 1B1B 1B1B 1C1C 1C1C 1C1C
  • 29. GroupingGroupingIIIIII SELECT class, COUNT(*) FROM student ; GROUP BY class class cnt 1A 10 1B 9 1C 9 2A 8 2B 8 2C 6 eg. 11eg. 11 List the number of students of each class.List the number of students of each class. Result
  • 30. GroupingGroupingIIIIII eg. 12eg. 12 List the average Math test score of each class.List the average Math test score of each class.
  • 31. Group By ClassGroup By Class AVG( )AVG( ) AVG( )AVG( ) AVG( )AVG( ) 1A1A 1B1B 1C1C StudentStudent class 1A1A 1A1A 1A1A 1B1B 1B1B 1B1B 1B1B 1B1B 1B1B 1C1C 1C1C 1C1C
  • 32. 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_mtest 1A 85.90 1B 70.33 1C 37.89 2A 89.38 2B 53.13 2C 32.67 Result
  • 33. 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 cnt HHM 6 KWC 1 MKK 1 SSP 5 TST 4 YMT 8 Result
  • 34. GroupingGroupingIIIIII eg. 14eg. 14 List the max. and min. test score of Form 1List the max. and min. test score of Form 1 students of eachstudents of each district.district. SELECT MAX(mtest), MIN(mtest), dcode ; FROM student ; WHERE class LIKE "1_" GROUP BY dcode max_mtest min_mtest dcode 92 36 HHM 91 19 MKK 91 31 SSP 92 36 TST 75 75 TSW 88 38 YMT Result
  • 35. GroupingGroupingIIIIII eg. 15eg. 15 List the average Math test score of the boys inList the average Math test score of the boys in each class. The listeach class. The list should not contain class withshould 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 class 86.00 1A 77.75 1B 35.60 1C 86.50 2A 56.50 2B Result
  • 36. Display OrderDisplay OrderIVIV SELECT ...... FROM ...... WHERE ......SELECT ...... FROM ...... WHERE ...... GROUP BY ..... ;GROUP BY ..... ; ORDER BYORDER BY colnamecolname ASC / DESCASC / DESC
  • 37. Display OrderDisplay OrderIVIV SELECT 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 id Peter 9801 Johnny 9803 Luke 9810 Bobby 9811 Aaron 9812 Ron 9813 ORDER BY dcode name id Aaron 9812 Bobby 9811 Johnny 9803 Luke 9810 Peter 9801 Ron 9813 Result
  • 38. Display OrderDisplay OrderIVIV SELECT 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 dcode Jimmy 9712 2A HHM Tim 9713 2A HHM Samual 9714 2A SHT Rosa 9703 2A SSP Helen 9702 2A TST Joseph 9715 2A TSW Paula 9701 2A YMT Susan 9704 2A YMT Result
  • 39. 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 docode 11 YMT 10 HHM 10 SSP 9 MKK 5 TST 2 TSW 1 KWC 1 MMK 1 SHT Result
  • 40. 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-levelclasses. (2-level ordering)ordering)
  • 41. Display OrderDisplay OrderIVIV name hcode class Bobby B 1A Teddy B 1B Joseph B 2A Zion B 2B Leslie B 2C Johnny G 1A Luke G 1A Kevin G 1C George G 1C : : : Result Order by class Blue House Green House : : Order by hcode
  • 42. OutputOutput VV INTO TABLE tablename the output table is saved as a database file in the disk. INTO CURSOR temp the output is stored in the working memory temporarily. TO FILE filename [ADDITIVE] output to a text file. (additive = append) TO PRINTER send to printer. TO SCREEN display on screen.
  • 43. OutputOutput VVeg. 20eg. 20 List the students in desc. order of their names andList the students in desc. order of their names and save the resultsave the result as a database file name.dbf.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 remission 9707 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
  • 44. OutputOutput VVeg. 21eg. 21 Print the Red House members by their classes, sexPrint the Red House members by their classes, sex and name.and name. SELECT class, name, sex FROM student ; WHERE hcode="R" ; ORDER BY class, sex DESC, name TO PRINTER class name sex 1A Aaron M 1A Peter M 1A Ron M 1B Tobe M 1B Janet F 1B Kitty F 1B Mimi F : : : Result
  • 45. Union, Intersection andUnion, Intersection and Difference of TablesDifference of Tables33 A B The union of A and B (A∪B) A table containing all the rows from A and B.
  • 46. Union, Intersection andUnion, Intersection and Difference of TablesDifference of Tables33 The intersection of A and B (A∩B) A table containing only rows that appear in both A and B. A B
  • 47. Union, Intersection andUnion, 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
  • 48. 33 Consider the members of the Bridge Club andConsider the members of the Bridge Club and the Chess Club. The two database files havethe Chess Club. The two database files have the same structure:the same structure: The Situation: Bridge Club & Chess Club field type width contents id numeric 4 student id number name character 10 name sex character 1 sex: M / F class character 2 class
  • 49. Union, Intersection andUnion, 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 A USE bridgeUSE bridge SELECT BSELECT B USE chessUSE chess
  • 50. Union, Intersection andUnion, 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 a list of allMake a list of all students. (Union)students. (Union) SELECT ...... FROM ...... WHERE ...... ;SELECT ...... FROM ...... WHERE ...... ; UNION ;UNION ; SELECT ...... FROM ...... WHERE ......SELECT ...... FROM ...... WHERE ...... Result
  • 51. Union, Intersection andUnion, 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 bothPrint a list of students who are members of both clubs.clubs. (Intersection)(Intersection) SELECT ...... FROMSELECT ...... FROM table1table1 ;; WHEREWHERE colcol IN ( SELECTIN ( SELECT colcol FROMFROM table2table2 )) Result
  • 52. Union, Intersection andUnion, 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 theMake a list of students who are members of the Bridge Club butBridge Club but not Chess Club. (Difference)not Chess Club. (Difference) SELECT ...... FROMSELECT ...... FROM table1table1 ;; WHEREWHERE colcol NOT IN ( SELECTNOT IN ( SELECT colcol FROMFROM table2table2 )) Result
  • 53. Multiple Tables:Multiple Tables:44 • SQL provides a convenient operation toSQL provides a convenient operation to retrieve information from multiple tables.retrieve information from multiple tables. • This operation is calledThis operation is called joinjoin.. • The join operation willThe join operation will combinecombine the tables intothe tables into one large table with all possible combinationsone large table with all possible combinations (Math: Cartesian Product), and then it will(Math: Cartesian Product), and then it will filterfilter the rows of this combined table to yieldthe rows of this combined table to yield usefuluseful information.information.
  • 55. 44 Each student should learn a musical instrument.Each student should learn a musical instrument. Two database files:Two database files: student.dbfstudent.dbf && music.dbfmusic.dbf The common field:The common field: student idstudent id fieldfield typetype widthwidth contentscontents idid numericnumeric 44 student id numberstudent id number typetype charactercharacter 1010 type of the music instrumenttype of the music instrument The Situation: Music Lesson SELECT ASELECT A USE studentUSE student SELECT BSELECT B USE musicUSE music
  • 56. Natural JoinNatural Join44 AA Natural JoinNatural Join is a join operation that joins twois a join operation that joins two tables bytables by their common column. This operationtheir common column. This operation is similar to the setting relation of two tables.is similar to the setting relation of two tables. SELECT a.comcol, a.SELECT a.comcol, a.col1col1, b., b.col2col2,, expr1expr1,, expr2expr2 ;; FROMFROM table1table1 a,a, table2table2 b ;b ; WHERE a.WHERE a.comcolcomcol = b.= b.comcolcomcol
  • 57. 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 theyMake a list of students and the instruments they learn. (Natural Join)learn. (Natural Join)
  • 58. 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 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 Mary 9802 Flute : : : : Result eg. 25eg. 25 Make a list of students and the instruments theyMake a list of students and the instruments they learn.learn. (Natural Join)(Natural Join)
  • 59. eg. 26eg. 26 Find the number of students learning piano inFind the number of students learning piano in each class.each 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
  • 61. eg. 26eg. 26 Find the number of students learning piano inFind the number of students learning piano in each class.each 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 cnt 1A 4 1B 2 1C 1 Result
  • 62. AnAn Outer JoinOuter Join is a join operation that includesis a join operation that includes rows that have a match, plus rows that do notrows 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
  • 63. eg. 27eg. 27 List the students who have not yet chosen anList the students who have not yet chosen an instrument. (Noinstrument. (No match)match) Outer JoinOuter Join44 No matchNo match MusicMusic idid typetype StudentStudent 98019801 idid namename classclass
  • 64. eg. 27eg. 27 List the students who have not yet chosen anList the students who have not yet chosen an instrument. (Noinstrument. (No match)match) SELECT class, name, id FROM student ; WHERE id NOT IN ( SELECT id FROM music ) ; ORDER BY class, name Outer JoinOuter Join44 Result class name id 1A Mandy 9821 1B Kenny 9814 1B Tobe 9805 1C Edmond 9818 1C George 9817 : : :
  • 65. eg. 28eg. 28 Make a checking list of students and theMake a checking list of students and the instruments they learn. The listinstruments they learn. The list should alsoshould also contain the students without an instrument.contain the students without an instrument. (Outer Join)(Outer Join) Outer JoinOuter Join44
  • 66. Outer JoinOuter Join44 Natural JoinNatural Join No MatchNo Match Outer JoinOuter Join eg. 28eg. 28
  • 67. SELECT s.class, s.name, s.id, m.type ; FROM student s, music m ; WHERE s.id=m.id ; Outer JoinOuter Join44 UNION ; SELECT class, name, id, "" ; FROM student ; WHERE id NOT IN ( SELECT id FROM music ) ; ORDER BY 1, 2 eg. 28eg. 28
  • 68. Outer JoinOuter Join44 emptyclass name id 1A Mandy 9821 1B Kenny 9814 1B Tobe 9805 1C Edmond 9818 1C George 9817 : : : No Match 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 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