SQL For Beginners
SQL For Beginners
MyServer
School Weather
1. Retrieve records
– “All the female golf players who are playing in
the tournament”
2. Retrieve summaries of the records:
– “What was the best score?”
Retrieving Info: SELECT
• SELECT queries allow us to choose records:
– What fields do we want to look at?
– What table(s) those fields come from?
– Restrictions based on field values
– Sorting the fields
– Limiting the number of rows
Some silly SQL
SELECT 5;
SELECT 5 + 5 * 5;
SELECT NOW();
Retrieving Info: SELECT / FROM
• Compulsory parts of the query: “WHAT” and
“WHERE”
• Fields what
• Table where
Retrieving Info: SELECT / FROM
• Get all the players’ last names:
SELECT lastName FROM tblPlayers;
• Delphi:
sqlQuery := ‘SELECT * FROM
tblPlayers WHERE firstName =
“John”;’;
Retrieving Info: WHERE / Comp
• Usual comparative operators:
– >, <, <=, >=
– “is equal to” =
• (not ==)
– “not equal to” <> or NOT field = value
• (not !=)
• A new one:
– “matches” LIKE
Retrieving Info: WHERE / LIKE
• Get all the players whose first names start
with “J”:
SELECT * FROM tblPlayers WHERE
firstName LIKE ‘J*’;
FROM tblPlayers
ORDER BY handicap;
FROM tblPlayers
WHERE gender = ‘F’
ORDER BY age DESC;
Retrieving Info: Multiple Tables
• If we want to link information in tables, we
can do so using SQL and the JOIN sub-clause
• Remember we need to keep data separate to
keep our tables normalised
• JOINs allow us to “pretend” that the tables are
one big thing again
• Basic idea:
SELECT <what> FROM <where>
JOIN <how>;
tblCompetition
1 John Smith
2 Mary Smith
entryID membNo paid score
3 Jeff Richardson 1 7 Yes 85
4 John Gray 2 5 Yes 81
5 Richard Jefferies 3 4 No 87
6 Bill Brianston 4 3 No 91
7 Delilah Sampson 5 12 Yes 92
8 Jane Kirk 6 11 Yes 88
7 9 Yes 79
9 Robert Cooke
10 Sean Zimmer
11 Miles Jones
12 Sarah French
JOIN types
• INNER JOIN
– Each record with a foreign key has a
corresponding record in a different table
• Outer JOIN
– Either LEFT or RIGHT – depending which table gets
the “focus”.
– The focus table has all records listed, even if there
are no related records in the other table.
Competition Results
• How do we list the players with their scores and their
handicaps so that we can work out a winner?
• Data exists in different tables though…
SELECT tblPlayers.*
FROM tblPlayers
LEFT JOIN tblCompetition ON
tblPlayers.membNo = age gender handicap membExpire
membNo firstName lastName
16 John Smith 56 M 12 2005/02/15
tblCompetition.membNo
17 Mary Smith 53 F 18 2005/02/15
21 Bill Brianston 40 M 5 2008/06/04
WHERE tblCompetition.membNo
23 Jane Kirk 34 F
IS NULL;
14 2008/07/17
25 Sean Zimmer 63 M 7 2009/12/18
Many to Many
• How many hours has each employee worked
on each project?
ageGroup avgHandicap
40 8. 7
60 11.3