SQL is a query language used to access and modify data in databases. It allows users to specify conditions to retrieve desired data. The basic structure of an SQL query includes SELECT, FROM, and WHERE clauses. Functions like COUNT, SUM, AVG, MAX and MIN can be used with GROUP BY to group and aggregate data. ORDER BY sorts the results. UNION combines the results of two or more queries.
1. SQL
Name of the Presenter: Devi B Date: 17-06-2011
February 11, 2013Proprietary and Confidential -1-
2. 1 Introduction to SQL
• What is SQL?
– SQL (Structured Query Language) is used to
modify and access data or information from a
storage area called database.
– When a user wants to get some information from
a database file, he can issue a query
– 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.
February 11, 2013Proprietary and Confidential -2-
3. 1 Introduction to SQL
Concept of SQL
– The user specifies a certain condition
– The program will go through all the
records in the database file and select
those records that satisfy the
condition.(searching).
– The result of the query will then be stored
in form of a table.
February 11, 2013Proprietary and Confidential -3-
4. 2 Basic structure of an SQL query
General SELECT, ALL / DISTINCT, *,
Structure AS, FROM, WHERE
Comparison IN, BETWEEN, LIKE "% _"
Grouping GROUP BY, HAVING,
COUNT( ), SUM( ), AVG( ), MAX( ), MIN( )
Display Order ORDER BY, ASC / DESC
Logical AND, OR, NOT
Operators
Output INTO TABLE , TO FILE , TO SCREEN
Union UNION
February 11, 2013Proprietary and Confidential -4-
5. The Situation: Student
2 Particulars
field type width contents
id numeric 4 student id number
name character 30 name
dob date 8 date of birth
sex enum 1 sex: M / F
class character 2 class
February 11, 2013Proprietary and Confidential -5-
6. I General Structure
SELECT ...... FROM ...... WHERE ......
SELECT [ALL / DISTINCT] expr1 [AS col1],
expr2 [AS col2] ;
FROM tablename WHERE condition
February 11, 2013Proprietary and Confidential -6-
7. I General Structure
SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS col2] ;
FROM table name WHERE condition
– The query will select rows from the source table
name and output the result in table form.
– Expressions expr1, expr2 can be :
• (1) a column, or
• (2) an expression of functions and fields.
– And col1, col2 are their corresponding column
names in the output table.
February 11, 2013Proprietary and Confidential -7-
8. I General Structure
SELECT [ALL / DISTINCT] expr1 [AS col1], expr2 [AS
col2] ;
FROM table name WHERE condition
– 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.
February 11, 2013Proprietary and Confidential -8-
9. I General Structure
Before using SQL, open the student file:
USE student
Eg. 1 List all the student records.
SELECT * FROM student
id name dob sex class
9801 Peter 06/04/86 M 1A
9802 Mary 01/10/86 F 1A
9803 Johnny 03/16/86 M 1A
9804 Wendy 07/09/86 F 1B
9805 Tobe 10/17/86 M 1B
: : : : :
February 11, 2013Proprietary and Confidential -9-
10. I General Structure
eg. 2 List the names of 1A students.
SELECT name, class FROM student ;
WHERE class="1A"
Class Class
1A 1A
class="1A"
1A 1A
1A 1A
1B 1B
1B 1B
: :
February 11, 2013Proprietary and Confidential - 10 -
11. I General Structure
eg. 2 List the names of 1A students.
Result name class
Peter 1A
Mary 1A
Johnny 1A
Luke 1A
Bobby 1A
Aaron 1A
: :
February 11, 2013Proprietary and Confidential - 11 -
12. I General Structure
eg. 3 List the names and ages of 1B girls.
1B Girls ?
February 11, 2013Proprietary and Confidential - 12 -
13. I General Structure
eg. 3 List the names and ages of 1B girls.
Condition for "1B Girls":
1) class = "1B"
2) sex = "F"
3) Both ( AND operator)
February 11, 2013Proprietary and Confidential - 13 -
14. I General Structure
eg. 3 List the names and ages of 1B girls.
What is "age"?
February 11, 2013Proprietary and Confidential - 14 -
15. I General Structure
eg. 3 List the names and ages of 1B girls.
Functions:
# Diff b/w two dates in days :
DATEDIFF(NOW() – dob)
# Returns Years , Month , Days :
FROM_DAYS(DATEDIFF(NOW() ) – dob)
February 11, 2013Proprietary and Confidential - 15 -
16. I General Structure
eg. 3 List the names and ages of 1B girls.
SELECT DATE_FORMAT
(FROM_DAYS(DATEDIFF(NOW(),dob)), '%Y') AS
age FROM student WHERE class='1B' AND sex='F'
Result
name age
Wendy 12.0
Kitty 11.0
Janet 12.0
Sandy 12.0
Mimi 12.0
February 11, 2013Proprietary and Confidential - 16 -
17. II Comparison
expr IN ( value1, value2, value3)
expr BETWEEN value1 AND value2
expr LIKE "%_"
February 11, 2013Proprietary and Confidential - 17 -
18. II Comparison
eg. 4 List the students who were born on
Wednesday or Saturday.
SELECT name, class, DAYNAME(dob)
AS bdate FROM student ;
WHERE weekday(dob) IN (2,5)
Result name class bdate
Peter 1A Wednesday
Wendy 1B Wednesday
Kevin 1C Saturday
Luke 1A Wednesday
Aaron 1A Saturday
: : :
February 11, 2013Proprietary and Confidential - 18 -
19. II Comparison
eg. 5 List the students who were not born in
January, March, June, September.
SELECT name, class, dob FROM student ;
WHERE MONTH(dob) NOT IN (1,3,6,9)
name class dob
Result
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
: : :
February 11, 2013Proprietary and Confidential - 19 -
20. II Comparison
eg. 6 List the id students whose total score is
between 200 and 300 (incl.)
SELECT student_id, total_marks FROM
student ;
WHERE total_marks BETWEEN 80 AND
90
Result
Student_id total_marks
9000 210
9810 250
9201 260
February 11, 2013Proprietary and Confidential - 20 -
21. II Comparison
eg. 7 List the students whose names start with "T".
SELECT name, class FROM student ;
WHERE name LIKE "T%"
Result name class
Tobe 1B
Teddy 1B
Tim 2A
February 11, 2013Proprietary and Confidential - 21 -
22. III Grouping
SELECT ...... FROM ...... WHERE condition ;
GROUP BY groupexpr [HAVING requirement]
Group functions:
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.
February 11, 2013Proprietary and Confidential - 22 -
23. III Grouping
eg. 8 List the number of students of each class.
February 11, 2013Proprietary and Confidential - 23 -
24. Group By Class
class
1A
1A 1A
1A
COUNT( )
1B
1B
1B COUNT( )
1B 1B
1B
1B
1C
1C 1C
1C
COUNT( )
Student
February 11, 2013Proprietary and Confidential - 24 -
25. III Grouping
eg. 8 List the number of students of each class.
SELECT class, COUNT(*) FROM student ;
GROUP BY class
Result class cnt
1A 10
1B 9
1C 9
2A 8
2B 8
2C 6
February 11, 2013Proprietary and Confidential - 25 -
26. III Grouping
eg. 9 List the average score of each class.
February 11, 2013Proprietary and Confidential - 26 -
27. Group By Class
class
1A
1A
1A 1A
AVG( )
1B
1B
1B
1B AVG( )
1B
1B
1B
1C
1C 1C AVG( )
1C
Student
February 11, 2013Proprietary and Confidential - 27 -
28. III Grouping
eg. 9 List the average total score of each
class.
SELECT class, AVG(total_marks) as Average
FROM student GROUP BY class
Result class Average
1A 85.90
1B 70.33
1C 37.89
2A 89.38
2B 53.13
2C 32.67
February 11, 2013Proprietary and Confidential - 28 -
29. III Grouping
eg. 10 List the max. and min. total of
students in each class.
SELECT MAX(total_marks) as max_total,
MIN(total_marks) as min_total,class
FROM student WHERE GROUP BY class
max_total min_total Class
Result 300 200 IA
289 195 IB
250 150 IC
225 125 2A
300 207 2B
289 100 2C
February 11, 2013Proprietary and Confidential - 29 -
30. III Grouping
eg. 11 List the average score of the boys in each
class. The list should not contain class with
less than 3 boys.
SELECT AVG(total_marks), class FROM
student WHERE sex="M" GROUP BY class
HAVING COUNT(*) >= 3
Result avg_marks class
86.00 1A
77.75 1B
35.60 1C
86.50 2A
56.50 2B
February 11, 2013Proprietary and Confidential - 30 -
31. IV Display Order
SELECT ...... FROM ...... WHERE ......
GROUP BY ..... ;
ORDER BY colname ASC / DESC
February 11, 2013Proprietary and Confidential - 31 -
32. IV Display Order
eg. 12 List the boys of class 1A, order by their
names.
SELECT name, id FROM student ;
WHERE sex="M" AND class="1A" ORDER BY name
name id Result name id
Peter 9801 Aaron 9812
Johnny 9803 Bobby 9811
ORDER BY
Luke 9810 Johnny 9803
Bobby 9811 Luke 9810
Aaron 9812 Peter 9801
Ron 9813 Ron 9813
February 11, 2013Proprietary and Confidential - 32 -
33. V Output
INTO TABLE tablename the output table is saved as a
database file in the disk.
TO FILE filename [ADDITIVE] output to a text file.
(additive = append)
TO SCREEN display on screen.
February 11, 2013Proprietary and Confidential - 33 -
34. Union, Intersection and
3 Difference of Tables
The union of A and B (A B)
A B
A table containing all the rows from A and B.
February 11, 2013Proprietary and Confidential - 34 -
35. Union, Intersection and
3 Difference of Tables
The intersection of A and B (A B)
A B
A table containing only rows tht appear in both A and B.
February 11, 2013Proprietary and Confidential - 35 -
36. Union, Intersection and
3 Difference of Tables
The difference of A and B (A–B)
A B
A table containing rows that appear in A but not in B.
February 11, 2013Proprietary and Confidential - 36 -
37. The Situation:
3 Bridge Club & Chess Club
Consider the members of the Bridge Club
and the Chess Club. The two database
files have the same structure:
field type width contents
id numeric 4 student id number
name character 10 name
sex character 1 sex: M / F
class character 2 class
February 11, 2013Proprietary and Confidential - 37 -
38. Union, Intersection and
3 Difference of 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
: : : : : : : :
Before using SQL, open the two tables:
SELECT A
USE bridge
SELECT B
USE chess
February 11, 2013Proprietary and Confidential - 38 -
39. Union, Intersection and
3 Difference of Tables
SELECT ...... FROM ...... WHERE ...... ;
UNION ;
SELECT ...... FROM ...... WHERE ......
eg. 13 The two clubs want to hold a joint party.
Make a list of all students. (Union)
SELECT * FROM student ;
UNION ;
SELECT * FROM student_temp ;
February 11, 2013Proprietary and Confidential - 39 -
40. Union, Intersection and
3 Difference of Tables
SELECT ...... FROM table1 ;
WHERE col IN ( SELECT col FROM table2 )
eg. 14 List of students who are members of both clubs.
(Intersection)
SELECT * FROM bridge ;
Result
WHERE id IN ( SELECT id FROM chess ) ;
TO PRINTER
February 11, 2013Proprietary and Confidential - 40 -
41. Union, Intersection and
3 Difference of Tables
SELECT ...... FROM table1 ;
WHERE col NOT IN ( SELECT col FROM table2 )
eg. 14 Make a list of students who are members of the
Bridge Club but not Chess Club. (Difference)
SELECT * FROM bridge ;
Result
WHERE id NOT IN ( SELECT id FROM chess ) ;
February 11, 2013Proprietary and Confidential - 41 -
42. 4 MultipleTables
• SQL provides a convenient operation to
retrieve information from multiple tables.
• This operation is called join.
• The join operation will combine the tables
into one large table with all possible
combinations and then it will filter the rows of
this combined table to yield useful information.
February 11, 2013Proprietary and Confidential - 42 -
43. 4 MultipleTables
field1 field2
A 1
field1 field2
A 2
A 1
A 3
B 2
B 1
3
B 2
B 3
February 11, 2013Proprietary and Confidential - 43 -
44. 4 The Situation Music Lesson
Each student should learn a musical instrument.
Two database files: student.dbf & music.dbf
The common field: student id
field type width contents
id numeric 4 student id number
type character 10 type of the music instrument
SELECT A
USE student
SELECT B
USE music
February 11, 2013Proprietary and Confidential - 44 -
45. 4 Natural Join
A Natural Join is a join operation that joins two
tables by their common column. This operation
is similar to the setting relation of two tables.
SELECT a.comcol, a.col1, b.col2, expr1, expr2 ;
FROM table1 a, table2 b ;
WHERE a.comcol = b.comcol
February 11, 2013Proprietary and Confidential - 45 -
46. 4 Natural Join
eg. 15 Make a list of students and the instruments
they learn. (Natural Join)
id name class id type
Same id
9801
9801
Join
Music
Student id name class type
9801
February 11, 2013Proprietary and Confidential
Product - 46 -
47. 4 Natural Join
eg. 15 Make a list of students and the instruments
they 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
class name id type
Result 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
: : : :
February 11, 2013Proprietary and Confidential - 47 -
48. 4 Natural Join
eg. 16 Find the number of students learning piano in
each class.
Three Parts :
(1) Natural Join.
(2) Condition:
m.type="Piano"
(3) GROUP BY class
February 11, 2013Proprietary and Confidential - 48 -
49. 4 Natural Join
eg. 16
Student
Join Condition Group
m.type= "Piano" By class
Product
Music
February 11, 2013Proprietary and Confidential - 49 -
50. 4 Natural Join
eg. 16 Find the number of students learning piano in
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
Result class cnt
1A 4
1B 2
1C 1
February 11, 2013Proprietary and Confidential - 50 -
51. 4 Outer Join
An Outer Join is a join operation that
includes rows that have a match, plus rows
that do not have a match in the other table.
February 11, 2013Proprietary and Confidential - 51 -
52. 4 Outer Join
eg. 17 List the students who have not yet chosen an
instrument. (No match)
id name class id type
9801
No match
Student Music
February 11, 2013Proprietary and Confidential - 52 -
53. 4 Outer Join
eg. 17 List the students who have not yet chosen an
instrument. (No match)
SELECT class, name, id FROM student ;
WHERE id NOT IN ( SELECT id FROM music ) ;
ORDER BY class, name
Result
class name id
1A Mandy 9821
1B Kenny 9814
1B Tobe 9805
1C Edmond 9818
1C George 9817
: : :
February 11, 2013Proprietary and Confidential - 53 -
54. 4 Outer Join
eg. 18 Make a checking list of students and the
instruments they learn. The list should also
contain the students without an instrument.
(Outer Join)
February 11, 2013Proprietary and Confidential - 54 -
55. 4 Outer Join
eg. 18
Natural Join
Outer Join
No Match
February 11, 2013Proprietary and Confidential - 55 -
56. 4 Outer Join
eg. 18 SELECT s.class, s.name, s.id, m.type ;
FROM student s, music m ;
WHERE s.id=m.id ;
UNION ;
SELECT class, name, id, "" ;
FROM student ;
WHERE id NOT IN ( SELECT id FROM music ) ;
ORDER BY 1, 2
February 11, 2013Proprietary and Confidential - 56 -
57. 4 Outer Join
class name id type
1A Aaron 9812 Piano class name id type
1A Bobby 9811 Flute 1A Aaron 9812 Piano
1A Gigi 9824 Recorder 1A Bobby 9811 Flute
1A Jill 9820 Piano 1A Gigi 9824 Recorder
1A Johnny 9803 Violin 1A Jill 9820 Piano
1A Luke 9810 Piano
1A Johnny 9803 Violin
1A Mary 9802 Flute
1A Luke 9810 Piano
: : : :
1A Mandy 9821
Natural Join 1A Mary 9802 Flute
1A Peter 9801 Piano
class name id
1A Mandy 9821 1A Ron 9813 Guitar empty
1B Kenny 9814 1B Eddy 9815 Piano
1B Tobe 9805 1B Janet 9822 Guitar
1C Edmond 9818 1B Kenny 9814
1C George 9817 1B Kitty 9806 Recorder
: : :
: : : :
No Match Outer Join
February 11, 2013Proprietary and Confidential - 57 -
58. 4 SQL CREATE TABLE Statement
The CREATE TABLE Statement is used to
create tables to store data. Integrity
Constraints like
- Primary key
- Unique key
- Foreign key
can be defined for the columns while
creating the table.
February 11, 2013Proprietary and Confidential - 58 -
59. Syntax for the CREATE TABLE
4 Statement
CREATE TABLE table_name
(column_name1 datatype,
column_name2 datatype,
... column_nameN datatype
);
table_name - is the name of the table.
column_name1, column_name2.... - is the name of
the columns
datatype - is the datatype for the column like char,
date, number etc.
February 11, 2013Proprietary and Confidential - 59 -
60. 4 SQL ALTER TABLE Statement
The SQL ALTER TABLE command is used to modify
the definition (structure) of a table by modifying
the definition of its columns.
February 11, 2013Proprietary and Confidential - 60 -
61. 5Database Testing
SQL – Part of
DB testing
February 11, 2013Proprietary and Confidential - 61 -