SQL Summary Notes
SQL Summary Notes
SQL (Structured Query Language) is a special language used to manipulate and query
data in a database.
Examples used in this document will reference this table (CD) that contains the following fields:
• Artist (text)
• CD_name (text)
• Genre (text)
• ReplacementValue (Currency)
• OwnerID (Number)
Examples:
SQL Statement Description
SELECT * FROM CD Display all the fields of the CD table.
1
Different types of criteria
The following section will cover examples of criteria that are used in the WHERE clause.
NOTE: Assume that these queries have a SELECT * FROM CD above the where clause.
• WHERE clause with normal operators ( = , <> , >= , <= , > and < )
Examples Description
Where the replacement value is EQUAL to
WHERE ReplacementValue = 100 R100.
• WHERE clause with multiple criteria using the AND and OR operators
Examples Description
WHERE ReplacementValue = 100 AND
Genre = “Rock” All Rock CD’s with a replacement value of R100.
2
• WHERE clause with the NOT operator
Examples Description
Where genre is NOT equal to Pop.
WHERE NOT Genre = “Pop” (Same as Genre <> “Pop” )
WHERE Genre IN (“Rock”, “Jazz”, “Pop”) Where the genre is either Rock or Jazz or Pop.
• WHERE clause with the LIKE operator o * (star symbol) means nothing or
anything (any amount of characters) o ? means any ONE character (Can not be
empty)
Examples Description
WHERE Artist LIKE “M*” Where the artist starts with the letter ‘M’.
WHERE Artist LIKE “*son” Where the artist ends with an ‘son’.
3
Where the artist has M as a first character & then
WHERE Artist LIKE “M???” any 3 other characters after it. (In other words,
where artist is any 4 letter beginning with an M)
Examples Description
ORDER BY ReplacementValue Sort by replacement value in ascending order
For unique values in a field of duplicates you use the keyword DISTINCT before the field
names in the SELECT clause.
Examples Description
Display all the genres in the CD table with no
SELECT DISTINCT Genre FROM CD duplicates.
4
Calculations in a query
You may add a calculated field to your query in the SELECT clause.
• You may give this calculated field a name by following the calculation with the AS
operator and then the name of the calculated field.
• If you use current fields in your calculations, make sure they are spelt as they are
in the database table.
• If a field contains spaces in its name, use square brackets around the full field
name when referring to it.
Examples Description
SELECT Artist, ReplacementValue, Displays a third field called VAT that is 15% of
15/100 * ReplacementValue AS VAT the replacement value.
SELECT Artist,CD_name, ReplacementValue, Displays a fourth field called Final Cost that is
ReplacementValue + 30 AS [Final Cost] the replacement value plus an additional R30.
You can’t use the calculated fields name in the WHERE or ORDER BY clause.
• If you need a criteria based on the calculation field then restate the calculation in
the WHERE clause.
• If you need to sort by the calculated field, you can refer to the calculated field by
the number of that field in the query. Every field mentioned in the SELECT clause
is numbered, starting at 1. So with the following select statement:
SELECT Artist, ReplacementValue, 15/100 * ReplacementValue AS VAT
Artist is field 1, ReplacementValue is field 2 and VAT is field 3.
To sort by VAT you refer to it’s number and whether you want ASC or DESC
SELECT Artist, CD_name, FORMAT( Displays the replacement value to ONE decimal
ReplacementValue , “0.0” ) AS Value place with the field name: Value.
5
• ROUND function rounds off the field or calculation.
o Parameters are first the field name or calculation followed by the number of
decimal places to be returned.
ROUND ( 25.756 , 2 ) returns a value of 25.76
ROUND ( 25.753 , 2 ) returns a value of 25.75
ROUND ( 25.753 , 0 ) returns a value of 26
Examples Description
SELECT Artist, ReplacementValue,
Displays the calculated field rounded to 2
ROUND(15/100 * ReplacementValue , 2 ) AS
decimal places.
VAT
SELECT Artist, CD_name, Displays the replacement value rounded to zero
ROUND( ReplacementValue , 0 ) AS Value decimal places.
Examples Description
SELECT Artist, ReplacementValue, Displays the calculated field as a whole number
INT(15/100 * ReplacementValue) AS VAT (NOT rounded).
• STR function converts a numerical field or calculation into text to be used with text
functions.
Examples Description
Displays the second field (called Details) in the
SELECT Artist, STR(ReplacementValue) + “ format of the replacement value with text
per order” AS Details added at the end:
Example: 130 per order
• LEN function returns the number of characters in the given text parameter.
LEN ( “Hello” ) returns a value of 5
LEN ( “Hello World” ) returns a value of 11
Examples Description
Displays the second field (called Chars In Name)
SELECT Artist, LEN( Artist ) AS [Chars with the number of characters in each artist
In Name] field
• UCASE function returns all the letters in the text field as upper case letters.
• LCASE function returns all the letters in the text field as lower case letters.
UCASE ( “Hello” ) returns a value of HELLO
LCASE ( “Pop Rock” ) returns a value of pop rock
6
Examples Description
SELECT Artist, UCASE( CD_name ) Displays the CD names in all capital letters.
SELECT Artist, LCASE( Genre ) Displays the genres in all small letters.
• LEFT function copies a specific number of characters from the left side of the
given text parameter.
• RIGHT function copies a specific number of characters from the right side of the
given text parameter.
o Parameters are first the text field name or calculation followed by the
number of characters to copy.
LEFT ( “Hello World” , 4 ) returns a value of Hell
RIGHT ( “Hello World” , 4 ) returns a value of orld
Examples Description
SELECT Artist, LEFT( Artist , 1 ) AS Displays the second field (called Artist Initial)
[Artist Initial] with the first character of the artist field.
SELECT Artist, RIGHT( Genre , 4 ) AS Displays the second field (called Last_Value)
Last_Value with the last 4 characters of the genre field.
Aggregate functions
These functions can be used to perform statistical or aggregate summaries on multiple
records in a database table.
• They are used in the SELECT clause and need a field name with the AS operator.
• Use the function name with a field name as a parameter.
• The following functions can ONLY be used on numerical fields (Fields that contain
numbers: integers, currency, etc):
7
o SUM – returns the sum of the values in the specified field. o AVG –
returns the average of the values in a specified field. o MIN –
returns the smallest value in a specified field.
o MAX – returns the largest value in a specified field.
Examples Description
SELECT SUM( ReplacementValue ) AS Total Displays the total replacement value of ALL
FROM CD CD’s in the table.
Examples Description
SELECT COUNT( * ) AS TotalRecords FROM Displays the total number (how many) of
CD records in the CD table.
SELECT COUNT( * ) AS [Total Rock] Displays the total number (how many) of Rock
FROM CD WHERE Genre = “Rock” CD’s.
NOTE: The examples shown above will only display ONE block with ONE value in it.
Grouping results
There aggregate functions mentioned above only display ONE result. If you want to
display multiple results, based on groups of records, then you add the GROUP BY
clause after the WHERE clause.
• If you use the ORDER BY clause, then it will appear AFTER the GROUP BY
clause.
8
• Rule: the moment you have more than one field in the SELECT clause with an
aggregate function, then you will always use the GROUP BY clause with the fields
that are NOT in the aggregate function.
Examples Description
SELECT Genre , Displays the average replacement value for each
AVG( ReplacementValue ) AS Average_Cost genre.
FROM CD Example: Rock R123.00
GROUP BY Genre Jazz R150.00…..
SELECT Artist , Displays the cheapest replacement value for
MIN ( ReplacementValue ) AS Cheapest_CD each artist.
FROM CD Example: Aaliyah R125.00
GROUP BY Artist Akon R160.00….
SELECT Genre , Displays the most expensive replacement value
MAX(ReplacementValue) AS MostExpensive for each genre (ordered from most expensive
FROM CD to least expensive).
GROUP BY Genre Example: Pop R200.00
ORDER BY MAX(ReplacementValue) DESC Rap R190.00….
NOTE: For the last query, you could also have used ORDER BY 2 DESC
(Order by 2nd field listed in SELECT clause)
If you want to apply a criteria to the aggregate function, then you can’t use that aggregate
function in the WHERE clause. Instead you have to make use of the HAVING clause.
• The HAVING clause comes after the GROUP BY clause but before the ORDER
BY clause.
9
Examples Description
SELECT Genre ,
AVG( ReplacementValue ) AS Average_Cost Displays the average replacement value for
FROM CD each genre but only the ones where the
GROUP BY Genre average replacement value is R150 or more.
HAVING AVG( ReplacementValue ) >= 150
SELECT Artist ,
Displays the most expensive replacement value
MAX(ReplacementValue) AS MostExpensive
for each artist (ordered from most expensive to
FROM CD
least expensive) but only those that have a
GROUP BY Artist
most expensive replacement value less than
HAVING MAX(ReplacementValue) < 150
R150.
ORDER BY MAX(ReplacementValue) DESC
When using a Date/Time data type, you refer to the values with a has symbol (#) on
either side of the data type.
• Remember to include the year, month and day when referring to a date. Can
NOT have DateOfBirth = 1990 <wrong>
Examples used below will refer to queries using the DateOfBirth field from the Owner
table.
Examples Description
SELECT * FROM Owner Display all the owners that were born on the 1
WHERE DateOfBirth = #1990/01/01# January 1990.
WHERE DateOfBirth >= #2001/01/01# AND Display the owners that were born in 2001 or
DateOfBirth <= #2002/12/31# 2002.
WHERE DateOfBirth BETWEEN Display the owners that were born in the first 6
#2001/01/01# AND #2001/06/30# months of 2001.
SELECT #2021/01/01# - DATE() AS Displays the number of days from NOW till New
DaysTilNewYear Year 2021 (This is if today is a day in 2020).
• DAY, MONTH and YEAR function returns the numerical value of day, month or
year for a date respectively. o Parameter is a date field.
Examples Description
SELECT OwnerName, Grade, Class, Displays the day (number value) that the owner
DAY( DateOfBirth ) AS Day_Of_BirthDate was born.
11
Queries using multiple tables
When multiple tables are linked by a common field (normally the primary key of one table
is used as a foreign key in another table) you can query information from both tables as
long as you take note of the following:
• All the tables used must be mentioned in the FROM clause separated by commas.
• You must specify which fields link to each other in the WHERE clause.
• If you have fields with the same name in both tables, you refer to a field by using
the table name <dot> field name. Example CD.OwnerID
For the following examples, we will use the CD and Owner table. The common field is the
OwnerID field in the Owner table (primary key) links to the OwnerID field in the CD table
(foreign key).
You can refer to each field in the format: table name <dot> field name (see bold).
12
Subqueries
When you want to use a value in a criteria for a query that is based on another query’s
result from an aggregate function, you can use that second query as a subquery in the
main query.
The SQL statement is written in the SQL string property of the ADOQuery:
• This can either be done in one line using the Text sub property Example:
AdoQuery1.SQL.Text := ‘SELECT * FROM CD’ ;
13
• Or it can be used like a memo control where you add multiple lines:
Example: AdoQuery1.Clear ;
AdoQuery1.SQL.Add( ‘SELECT *’ ) ;
AdoQuery1.SQL.Add( ‘FROM CD’ ) ;
Example
qryCDDatabase.SQL.Clear ;
qryCDDatabase.SQL.Add ( ‘SELECT CD_Name, Artist, ReplacementValue FROM CD’ ) ;
qryCDDatabase.SQL.Add ( ‘WHERE Genre = “Rock” ORDER BY Artist ASC ‘ ) ;
qryCDDatabase.Open ;
showmessage( IntToStr( qryCDDatabase.RecordCount ) + ‘ records’ ) ;
You can use data from Delphi components or variables in your SQL queries.
• The SQL property is a string field.
• All your text fields in the database must be contained in double quotes (“) and all
the date fields must be contained in hash symbols (#).
Example
iValue := 150 ; //integer variable
qryCDDatabase.SQL.Clear ;
qryCDDatabase.SQL.Add ( ‘SELECT CD_Name, Artist, ReplacementValue FROM CD’ ) ;
qryCDDatabase.SQL.Add ( ‘WHERE Replacement Value >= ‘ + IntToStr( iValue ) ) ;
qryCDDatabase.Open ;
showmessage( IntToStr( qryCDDatabase.RecordCount ) + ‘ records’ ) ;
Added the iValue integer value to the query but converted it to a string because the SQL
property requires a string value.
14
Example
sName := edtInput.Text ; //string variable
qryCDDatabase.SQL.Clear ;
qryCDDatabase.SQL.Add ( ‘SELECT CD_Name, Artist, ReplacementValue FROM CD’ );
qryCDDatabase.SQL.Add ( ‘WHERE Artist = “‘ + sName + ‘”’) ;
qryCDDatabase.Open ;
showmessage( IntToStr( qryCDDatabase.RecordCount ) + ‘ records’ ) ;
Added the sName string value to the query so no converting is needed, however the string
variable needs to be contained in double quotes, then the string variable followed by the ‘.
‘WHERE Artist = “‘ + sName + ‘”’
If the use of double quotes is confusing then you can make use of the QuotedStr function:
qryCDDatabase.SQL.Clear ;
qryCDDatabase.SQL.Add ( ‘SELECT * FROM CD WHERE Genre LIKE “%Rock%” ’ ) ;
qryCDDatabase.Open ;
showmessage( IntToStr( qryCDDatabase.RecordCount ) + ‘ records’ ) ;
Example
SELECT * FROM CD WHERE Artist LIKE “M???”
qryCDDatabase.SQL.Clear ;
qryCDDatabase.SQL.Add ( ‘SELECT * FROM CD WHERE Artist LIKE “M_ _ _” ’ ) ;
qryCDDatabase.Open ;
showmessage( IntToStr( qryCDDatabase.RecordCount ) + ‘ records’ ) ;
Example
sInput := edtInput.Text ; //string variable
qryCDDatabase.SQL.Clear ;
qryCDDatabase.SQL.Add ( ‘SELECT * FROM CD WHERE Genre LIKE “%’ + sInput + ‘%”’) ;
qryCDDatabase.Open ;
showmessage( IntToStr( qryCDDatabase.RecordCount ) + ‘ records’ ) ;
15
Note: The % symbol is inside the string quotes when using a variable.
INSERT statements
INSERT statement is used to add a new record in one of the tables in a database.
NOTE: Values must follow the rules for their data type: text to be contained in double quotes and
dates to be contained in hash symbols. Numbers and Booleans can be used as is.
Add the following details into the corresponding fields as a new record in the Owner table.
16
UPDATE statements
UPDATE statement is used to make changes to values in a record or records that
currently exist in a database table.
Examples Description
UPDATE Owner
Change the e-mail address of the record with
SET Email = “[email protected]”
an Owner ID of 10 in the Owner table.
WHERE OwnerID = 10
UPDATE CD
SET Increase the replacement value by 15 of al the
ReplacementValue = ReplacementValue+15 Rock CD’s in the CD table.
WHERE Genre = “Rock”
UPDATE Owner
Change all the Disc Jockeys in Grade 11 to
SET Grade = 12, Class = “A”
Grade 12 class A in the Owner table.
WHERE Grade = 11 AND DiscJockey = TRUE
DELETE statements
DELETE statement is used to remove records from a table in a database.
17
Examples Description
DELETE FROM Owner WHERE Delete record where Owner ID is 10 in the
OwnerID = 10 Owner table.
DELETE FROM CD
WHERE Genre = “Rock” Delete all the Rock CD’s from the CD table.
DELETE FROM CD Delete all the CD’s that cost over R200 to
WHERE ReplacementValue > 200 AND replace and where the artist starts with the
Artist LIKE “B*” letter “B” in the CD table.
DELETE FROM CD Delete ALL the records in the CD table.
Example
qryCDDatabase.SQL.Clear ;
qryCDDatabase.SQL.Add ( ‘DELETE FROM CD WHERE Genre = “Rock” ’ ) ;
qryCDDatabase.ExecSQL ;
//Once DELETE is complete, then run a SELECT query so user can observe the results of the
//delete
qryCDDatabase.SQL.Clear ;
qryCDDatabase.SQL.Add ( ‘SELECT * FROM CD ’ ) ;
qryCDDatabase.SQL.Open ;
You can use data from Delphi components or variables in your SQL queries.
• The SQL property is a string field.
• All your text fields in the database must be contained in double quotes (“) and all
the date fields must be contained in hash symbols (#).
• Remember the special rule: When using the LIKE operator in Delphi o Use the %
symbol in place of the * (star symbol) o Use the _ symbol (underscore) in place of
the ?
18
Example
iValue := StrToInt( InputBox( ‘ID’, ‘Enter your Owner ID’ , ‘10’ ) ); //integer var for Owner ID
sNewEmail := InputBox( ‘E-Mail’, ‘Enter NEW e-mail:’ , ‘’ ) ; //string var for new email
qryCDDatabase.SQL.Clear ;
qryCDDatabase.SQL.Add ( ‘UPDATE Owner SET Email = “’ + sNewEmail +’”’ ) ;
qryCDDatabase.SQL.Add ( ‘WHERE OwnerID = ‘ + IntToStr( iValue ) ) ; qryCDDatabase.ExecSQL
;
• Added the iValue integer value to the query but converted it to a string because the SQL
property requires a string value.
• Added the sNewEmail string value to the query so no converting is needed, however the
string variable needs to be contained in double quotes, hence the double quotes before the
first string is concluded, then the string variable followed by the ending double quotes as a
string.
Example
sOwnID := edtOwnerID.Text ; //ALL are string variables
sName := edtOwnerName.Text ;
sGrade := edtGrade.Text ;
sClass := edtClass.Text ;
sDJockey := edtDiscJockey.Text ;
sDOB := edtDOB.Text ;
19
NOTE:
• Inputs are stored in string values because the SQL property is a string. If you had variables of
other types, they would need to be converted to string (e.g. IntToStr, BoolToStr, etc)
• String commas are added between each field in the VALUES brackets.
• Each variable for number fields (sOwnID & sGrade) are added as is.
• Variable for Boolean field (sDJockey) is added
as is. string double quotes
• Each variable for string fields (sName & sClass)
are added with . string hash symbols .
• Variable for date field (sDOB) is added with
If the use of double quotes is confusing then you can make use of the QuotedStr function:
20