Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

7 - Relational Databases and SQL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.

net

7 – Relational databases and SQL


Throughout this chapter, these icons will be used to link to database files and SQL
queries.

The database files are in .db format which will work with SQLite which is
free to use at https://sqliteonline.com/ and an installable tool (DB4S) can
be downloaded for free from http://tiny.cc/sqldb

The SQL files are just text files with a .sql extension so they can be imported
into SQLite or any other database software.

The files are also available in Microsoft Access format where the tables will
be stored as tables and the SQL will be stored as queries. There is also an
excellent SQL tutorial that you can follow at http://tiny.cc/sqltutor

Database terminology
From the AQA specification:

“Note that whilst the terms entity, attribute and entity identifier are more
commonly used when an abstract model of a database is being
considered, the terms given here will be used for both implementations of
and abstract models of databases.”

© paullong.net 2021 Page 1 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Contents

1) Databases ................................................................................................................... 3
Database structure ................................................................................................. 3
Table .............................................................................................................. 3
Record........................................................................................................... 4
Field ............................................................................................................... 4
Primary Key ................................................................................................... 5
Relational databases ............................................................................................. 7
Foreign Key ................................................................................................... 7
One to one relationships ............................................................................. 8
One to many relationships ........................................................................ 10
Advantages of relational databases ................................................................. 14
Redundant data ........................................................................................ 14
Inconsistent data ....................................................................................... 14
Eliminating redundant data and inconsistency...................................... 15
Advantages of eliminating redundant data .......................................... 17
2) SQL ............................................................................................................................. 18
Selecting data ...................................................................................................... 18
Select fields ................................................................................................. 18
Ordering data ............................................................................................ 19
Select records............................................................................................. 20
Wild cards ................................................................................................... 22
IN .................................................................................................................. 23
BETWEEN ...................................................................................................... 24
Multiple tables ............................................................................................ 26
Inserting data ........................................................................................................ 29
Updating data ...................................................................................................... 31
Deleting data ........................................................................................................ 33

© paullong.net 2021 Page 2 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net
#

1) Databases

Database structure
Databases are a structured method of storing data. Data is stored in tables and
each set of data about one thing is known as a record. Each category of
information is known as a field. Tables can have fields with different data types,
unlike an array, and the fields can be referenced by a field name instead of a
number. Records can also be added to, or deleted from, a table, unlike an array.
When looking at a table, records are in rows and fields are in columns. Each field is
identified by a fieldname.

Example – database table


Registration Make Model Colour Reg Year Transmission
BX03HMW Ford Focus Blue 2003 M
BR54URS Vauxhall Astra Red 2004 M
BA55WEP Volkswagon Beetle Blue 2005 M
BC13PRS Mini Cooper Green 2013 A
BD07ABC Nissan Almera Red 2007 M
BE14RTJ Nissan Leaf Blue 2014 A
The title row represents the field names such as Make, Model and Colour. Each
field is in a column, such as the Model.

The rows are records, such as the record for BA55WEP which is a Volkswagon
Beetle.

The table above is a flat file (single table) database. You will find out about
problems that can be caused by flat files later in this chapter.

Note: The software used to manage a database is known as database


management software (DBMS). The database is where the database is
stored. For example, Microsoft Access is a DBMS, not a database.

Table
A table stores data about things that exist. The example above is a table that
stores data about cars. Things that exist can be:
• people (e.g. driving instructors)
• places (e.g., towns)
• objects (e.g. cars)
• events (e.g. lessons)

Tables have a structure that includes rows (records) and columns (fields). Each
table must have:
• a unique name (e.g. CARS)
• unique records (each record must be unique and not repeated)
• unique fields (each field must have a unique field name)
© paullong.net 2021 Page 3 of 35 by Paul Long
The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Record
Each record stores data about an individual thing that exists. These things could
include a:
• person
• place
• object
• event

Notice how these are singular occurrences of the group names used to name
tables. Each record is a row within a table and each record must be unique within
the table - it must not be repeated.

Example – car
There are 6 records in this table below. Two of those records have been
highlighted and each record is for an individual car – a single thing that exists.
One of the records is for a Mini Cooper with a registration number of BC53PRS.

Field
A field is a category of information. Imagine the phrase ‘field of study’ which
means ‘area of study’. Fields are columns within a table and have titles which are
known as field names.

Example
Two fields are highlighted below. They have field names of Make and Reg Year
which are categories of information about the cars. Ford, Mini and 2003 are
examples of data items.

Data items are the individual items of data for each field and record. They are
found where a field (column) and record (row) meet. Each field must have a
unique field name so that no two fields within the same table have the same field
name. Data types can be set for each field such as text, number and date/time.
Validation can be applied to fields so that data must meet certain criteria to be
accepted.
© paullong.net 2021 Page 4 of 35 by Paul Long
The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Primary Key
A primary key is a field that is a unique identification for each record. Within the
primary key field, each value can only appear once.

Activity - bad primary keys


Why is surname not a good primary key?

It is good practice to always use some sort of ID or Code that is unique and will not
change. In the table above, a Customer ID field would be an appropriate primary
key.

Example - good primary keys

In the first table above, VIN is used as the primary key instead of registration
because the registration number could be changed. In the second table, an ID
number is used instead of Course_Title because in the future additional courses
could be added that have the same names as existing courses.

Activity - Olympic events


OLYMPIC EVENT

Event Event Description Date Time Venue


Number

J237AP Men’s Beach Volleyball 28/7/12 11:00 Horse Guards


Preliminary Round 1 Parade
T217BP Men’s Beach Volleyball 28/7/12 12:00 Horse Guards
Preliminary Round 2 Parade
W827TR Women’s 100m Relay 4/8/12 21:55 Olympic Stadium
Final

1. Identify two fields in this table.


2. Describe one record in this table.
3. Identify the primary key for this table.

© paullong.net 2021 Page 5 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity - driving school terminology


1) Open the driving school database.

a) Name the four tables in this database.


b) For each table, state whether it is a person, object, place or event.

2) Open the customer table


a) Identify the primary key.
b) Explain why Date of Birth would be an unsuitable primary key.
c) How many records are there in the customer table?
d) What is the database terminology for “Surname”?

3) Open the instructor table.


a) Explain why Instructor ID is a suitable primary key.
b) Explain why Surname would be an unsuitable primary key.
c) Identify three fields in this table.

© paullong.net 2021 Page 6 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Relational databases
Relationships exist between records within tables. A relationship is between a
record from one table and a record(s) from another table. There are 2 types of
relationships that can be created:
• One to One
• One to Many

Example - relationships
One to One - e.g. one CAR has one INSURANCE_POLICY

CAR INSURANCE POLICY


One to Many - eg one INSTRUCTOR has many LESSONS

INSTRUCTOR LESSON

Note: Many to Many relationships cannot be implemented within a database.


They are a conceptual idea as part of an abstract model of a database.
This can be ignored at GCSE level.

Foreign Key

A foreign key is a field in one table that links to a primary key in another table using
a relationship.

Example - foreign key


In the LESSON table below, each lesson needs an instructor. The Instructor ID field
is the foreign key because it is ‘foreign’ to the LESSON table and links to the
primary key in the INSTRUCTOR table.

© paullong.net 2021 Page 7 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

One to one relationships


This type of relationship is used when only ONE record from one table relates to
only ONE record from another table.

Example – one to one relationship


Cars need to have an insurance policy although some cars are not actually
insured. A car only has one insurance policy at a time and an insurance policy is
only ever for one car.

CAR INSURANCE_POLICY
VIN PolicyNumber
Registration Type
Make Start Date
Model End Date
VIN

One CAR has one INSURANCE_POLICY and one INSURANCE_POLICY has one CAR.
The foreign key from one table links to the primary key of another table.

INSURANCE_POLICY CAR

Policy Start VIN VIN Make


Number Date

123 5/10/12 456 123 Ford


234 3/5/12 890 234 Vauxhall
456 15/9/12 234 456 Volkswagen
789 3/10/12 123 567 Mini
789 Nissan
890 Renault

Activity - primary and foreign key


In the tables above, which fields are the primary keys?
In which table do you find the foreign key?
What is the name of the field that is the foreign key?

© paullong.net 2021 Page 8 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity – one to one relationships


For each relationship below, suggest suitable:
• field names
• primary keys
• foreign keys (choose the entity that will always have a link to the other entity)

HUSBAND WIFE

COUNCIL MAYOR

PERSON BAPTISM

For the first two relationships, assume that data is not stored about previous
marriages or previous mayors.

© paullong.net 2021 Page 9 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

One to many relationships


This type of relationship is used when ONE record from one table relates to MANY
records from another table.

Example - one to many relationship


Tutor groups have several students. Each student is a member of one tutor group.

STUDENT
TUTOR GROUP Student Number
Tutor Group Name Surname
Classroom Forename
Teacher Date of Birth
Tutor Group Name
One TUTOR group has many STUDENTS but each STUDENT has one TUTOR group
making this a one to many relationship.

The foreign key (Tutor Group Name) from the STUDENT table links to the primary key
(Tutor Group Name) of another table (TUTOR GROUP).

STUDENT TUTOR GROUP

Student Surname Tutor Tutor Classroom


Number Group Group
Name Name
123 Smith 13A 13A ES1
234 Jones 13A 11B ES2
345 Brown 11B 13S ES3
456 White 11B 11I ES4
567 Jamieson 13S
678 Jones 13S
789 Black 13A

© paullong.net 2021 Page 10 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity – driving school terminology 2


1) Open the driving school database and open the CUSTOMER table.

a) Identify the field which could be used as a foreign key.


b) Identify the table this foreign key would point to.

2) Open the LESSON table.


a) Identify the foreign key that is used in the relationship with the INSTRUCTOR
table.
b) Identify the foreign key that is used in the relationship with the VEHICLE
table.
c) The relationship between INSTRUCTOR and LESSON is one INSTRUCTOR to
many LESSONs. State the relationship between LESSON and CUSTOMER.

There is a rule for determining which side of the one to many relationship the
foreign key will go on. The foreign key always goes on the many side of the
relationship so that it points to one single record in the other table:

ONE SIDE ENTITY MANY SIDE ENTITY


Primary Key Primary Key
Attribute One Attribute One
Attribute Two Attribute Two
Attribute Three Attribute Three
Foreign Key

If the foreign key is put on the wrong side of the relationship (the one side), then it is
impossible to store the related data properly because it will result in non-atomic
data (multiple data items in one field for a record):

TUTOR GROUP STUDENT

Tutor Classroom Student Student Surname


Group Number Number
Name
123 Smith
13A ES1 123, 234,
789 234 Jones

11B ES2 345, 456 345 Brown

13S ES3 567, 678 456 White

11I ES4 567 Jamieson


678 Jones
789 Black

© paullong.net 2021 Page 11 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity – veterinary surgery


A veterinary surgery stores data about pets and their owners:

PET OWNER

Pet Microchip Name DoB Owner Owner Surname


Code Code ID

9172 WIOCJBLWI Scrumpy 3/7/1992 238 827 Bulmer


3892 SLVMWKW Jack 3/7/1992 238 238 Gaymer
4729 QPCIWUQC Jill 5/1/2010 238 029 Strong
1037 EIUCSLAWI Fluffy 6/8/2012 108 108 Bow
1038 CNWDKSJL Paws 12/9/1999 029
1039 QUNCBSDL Ben 15/4/2011 108

1. Identify three fields.


2. Suggest three other suitable fields that could be used for the PET table.
3. Describe one record in the PET table.
4. Identify the primary key for each table.
5. Identify the foreign key and give reasons for your choice.
6. Describe the relationship between the PET and OWNER tables.

Activiy – one to many relationships


For each relationship below, identify suitable:
• fields
• primary keys
• foreign keys (remember the rule for which side to use)

VEHICLE LESSON

SCHOOL TEACHER

DIRECTOR FILM

© paullong.net 2021 Page 12 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity - scuba diving


Scuba divers keep a log of each of their dives. A database can be used to store
this information. One table that is used is called SITES which is the location of the
dive. The divers need to store data about each dive including when they dived,
the location of the dive, how deep the dive was and how long they were under
water.

A table called DIVERS already exists. A table called DIVES will be used to store
information about each diver’s dives.

1. Suggest four fields that could be used in the DIVES table.


2. Describe one record that could be included in the table.
3. Suggest a suitable primary key for the table.
4. Suggest a suitable foreign key for the table.
5. Describe the relationship between the DIVES table and the SITES table.

© paullong.net 2021 Page 13 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Advantages of relational databases

Redundant data
Redundant data can occur when relationships have not been set up correctly.
Data is duplicated. The data exists more than once, so it is classed as being
redundant (not needed).

Example - redundant data


Employee Department Manager
Fred Bloggs Sales John Marshall
Bill Goaty Marketing Fred Parkes
Andrew Adams Sales John Marshall
Paul Simons Sales John Marshall

Each department only has one manager and we can see that the Sales
department is managed by John Marshall and the Marketing department is being
managed by Fred Parkes. Three of these employees work in the same
department. The information about John Marshall being the manager for the sales
department has been repeated twice and this is unnecessary. This makes the
duplicated data about John Marshall redundant (not needed).

Inconsistent data

Example – inconsistent data


Redundant data can lead to inconsistent data:

Employee Department Manager


Fred Bloggs Sales John Marshall
Bill Goaty Marketing Fred Parkes
Andrew Adams Sales John Marshal
Paul Simons Sales Jon Marshall
Amy Harper Advertising Fred Parkes
The duplication of the department data has led to inconsistency with the spelling
of John Marshall. A search for John Marshall would only return one record.

The redundant data has also led to the marketing department being incorrectly
called the Advertising department for Amy Harper. A search for employees in the
Marketing department would only return Bill Goaty and not Amy Harper.

© paullong.net 2021 Page 14 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Eliminating redundant data and inconsistency

Example – eliminating redundant data


A new table should be created for the departments with fields of Dept_ID,
Department and Manager. This will mean that the Employee table can have a
foreign key of Dept_ID that points to the Dept_ID in the Sales table and there is no
longer any unnecessarily duplicated data:

Employee Dept_ ID Dept_ID Department Manager


Fred Bloggs 3 1 Marketing Fred Parkes
Bill Goaty 1 2 Purchasing Sandra Bullock
Andrew Adams 3 3 Sales John Marshall
Paul Simons 3
Amy Harper 1
The new table means that each manager is only stored once. The redundancy
has been removed. This has also resulted in inconsistent data being removed
because John Marshall is only spelt once and the Marketing department only has
one name.

The relationship between EMPLOYEE and DEPARTMENT is many EMPLOYEES work in


one DEPARTMENT, or one DEPARTMENT has many EMPLOYEES:

EMPLOYEE DEPARTMENT

© paullong.net 2021 Page 15 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity – eliminating redundant data


1) The table below stores details of cars:

Registration Model Colour Manufacturer Manufacturer


ID Name
BX03HMW Focus Blue 2 Ford
BR54URS Almera Red 3 Nissan
BA55WEP Kuga Blue 2 Ford
BC13PRS Discovery Green 1 Landrover
BD07ABC Almera Red 2 Nisan
BE14RTJ Galaxy Blue 2 Ford

a) Using this example, explain what is meant by redundant data.


b) Using this example, explain how redundant data could lead to
inconsistent data.
c) Create a new table to eliminate the redundant data.
d) Draw or describe the relationship between the original table and the
new table.

2) The table below stores details of Olympic events:

Event Event Description Date Time Venue


Number
J237AP Men’s Beach Volleyball 28/7/12 11:00 Horse Guard’s
Preliminary Round 1 Parade
T217BP Men’s Beach Volleyball 28/7/12 12:00 Horse Guards
Preliminary Round 2 Parade
W827TR Women’s 100m Relay Final 4/8/12 21:55 Olympic Stadium

a) Using this example, explain what is meant by redundant data.


b) Using this example, explain how redundant data could lead to
inconsistent data.
c) Create a new table to eliminate the redundant data.
d) Draw or describe the relationship between the original table and the
new table.

© paullong.net 2021 Page 16 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Advantages of eliminating redundant data

✓ No redundant saves storage space


✓ The problem of inconsistent data is eliminated
✓ Searches will provide more reliable results because data is consistent

Note: eliminating inconsistent data does not eliminate errors. For example, if
Marketing had been spelt “Marketting” in the DEPARTMENT table then it
would consistently incorrect.

Questions – follow me
1) The tables below store data about books and their authors. Assume that each
book only has one author.

BOOKS AUTHORS
Book_ID Title Author_ID Author_ID Forename Surname
1 The Twits 3 1 Anna Sewell
2 Black Beauty 1 2 Charles Dickens
3 A Christmas Carol 2 3 Roald Dahl
4 Oliver Twist 2
5 The BFG 3

a) Using the example above, describe the purpose of a primary key. [2]
b) Using the example above, describe the purpose of a foreign key. [3]
c) Using the example above, suggest another field for the table BOOKS. [1]
d) Draw or describe the relationship between BOOKS and AUTHORS. [1]

2) The following data is stored about films:


Film ID Film Name Duration Rating Studio
SF928 Skyfall 143 12A MGMS
MG289 Madagascar 3 93 PG DWKS
TKN219 Taken 2 91 12A 20CF
RR391 River Rats 67 U DVKS

a) Give an example of a field from the table above. [1]


b) Identify the field that might contain redundant data. [1]
c) Using the example above, explain one problem that can be caused by
redundant data. [2]
d) Explain how the use of a relational database would eliminate data
redundancy in the table above. [4]

© paullong.net 2021 Page 17 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

2) SQL

SQL (Structured Query Language) is a language used to retrieve data from a


database and to manipulate data within a database. For AQA GCSE Computer
Science, you will use SQL to:

• Select data to extract from one or two tables


• Insert data into a table
• Update data within a table
• Delete data from a table

Selecting data
Asking a question of a database is known as a select query:
SELECT <fieldnames>
FROM <table name>
WHERE <condition>

Select fields

Example – show all data


To show all data in the table called cars, use:
SELECT *
FROM cars

Registration Make Model Colour Reg Year Transmission


BX03HMW Ford Focus Blue 2003 M
BR54URS Vauxhall Astra Red 2004 M
BA55WEP Volkswagon Beetle Blue 2005 M
BC13PRS Mini Cooper Green 2013 A
BD07ABC Nissan Almera Red 2007 M
BE14RTJ Nissan Leaf Blue 2014 A

In the example above, * is used to represent all fields.

It is also possible to select just some of the fields to be included, by listing the
fieldnames after SELECT.

© paullong.net 2021 Page 18 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Example – selecting fields


To show all records for blue cars, use:

SELECT Registration, Make, Model


FROM cars

Registration Make Model


BX03HMW Ford Focus
BR54URS Vauxhall Astra
BA55WEP Volkswagon Beetle
BC13PRS Mini Cooper
BD07ABC Nissan Almera
BE14RTJ Nissan Leaf

Activity – SELECT tutorial


Follow through the SQLite tutorial for SELECT at http://tiny.cc/sqlselect

Ordering data
Records can be sorted into ascending (ASC) or descending (DESC) order:

SELECT <fieldnames>
FROM <table name>
ORDER BY <fieldname> ASC ¦ DESC

Example – ordering records


To show all records in ascending order of the model name:

SELECT Registration, Make, Model


FROM cars
ORDER BY cars ASC

Registration Make Model


BD07ABC Nissan Almera
BR54URS Vauxhall Astra
A-Z

BA55WEP Volkswagon Beetle


BC13PRS Mini Cooper
BX03HMW Ford Focus
BE14RTJ Nissan Leaf

Activity – ORDER BY tutorial


Follow through the SQLite tutorial for ORDER BY at http://tiny.cc/orderby

© paullong.net 2021 Page 19 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Select records
The WHERE clause can be used to specify any conditions that must be met. Only
records that meet those conditions will be displayed.

Example – selecting records


To show all records for blue cars, use:
SELECT *
FROM cars
WHERE Colour = ‘Blue’

Registration Make Model Colour Reg Year Transmission


BX03HMW Ford Focus Blue 2003 M
BA55WEP Volkswagon Beetle Blue 2005 M
BE14RTJ Nissan Leaf Blue 2014 A

It is also possible to combine selecting which fields to display and only the records
that meet a criteria.

Example – selecting fields and records


To show all records for blue cars in descending order, use:
SELECT Registration, Make, Model, Reg Year
FROM cars
WHERE Colour = ‘Blue’ AND Transmission = ‘M’
ORDER BY Make DESC

Registration Make Model Reg Year


BA55WEP Volkswagon Beetle 2005
BX03HMW Ford Focus 2003

The Beetle comes before the Focus because descending order of Reg Year was
chosen.

Boolean operators can be used to create more complex conditions.

Example – using Boolean operators


To show all records for blue cars with manual transmission, use:

SELECT *
FROM cars
WHERE Colour = ‘Blue’ AND Transmission = ‘M’

Registration Make Model Colour Reg Year Transmission


BX03HMW Ford Focus Blue 2003 M
BA55WEP Volkswagon Beetle Blue 2005 M

Note: transmission is the type of gearbox which can be manual or automatic.


© paullong.net 2021 Page 20 of 35 by Paul Long
The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity – select
1) Examine the countries table and SQL query below:

CountryName Population Area PopulationDensity Last


(km2) (/km2) Updated
Monaco 33,000 1.95 16,923 2013
Vatican City 826 0.44 1877 2009
United Kingdom 62,041,708 243,610 255 2010
France 62,793,432 551,500 114 2010
Sweden 9,366,092 449,964 21 2009
SELECT CountryName
FROM Countries
WHERE LastUpdated > 2009

a) Show which data will be output when the SQL query is run on the table
above.

b) Write SQL queries to find:


i) All the details for the United Kingdom.
ii) The country name and population for countries with a population
higher than one million.
iii) The country name, population and date last updated for countries
which have an area of at least 100,000 km2 and a population density
bigger than 100.

Activity – select card game

See who can get the highest score in the select card game from SQL Zoo at
http://tiny.cc/sqlcardgame

What do you think LIKE does in the WHERE condition?

© paullong.net 2021 Page 21 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Wild cards
In the activity above, you were able to select data where only part of the data in
a field met the criteria. This was done using wild cards. Wild cards replace text in
a string field to represent any character.

SELECT <fieldnames>
FROM <table name>
WHERE <fieldname> LIKE <string with wildcard>

Example – wild cards


To show all records where the Model starts with ‘A’, use:

SELECT Registration, Make, Model


FROM cars
WHERE Model LIKE ‘A%’

Registration Make Model


BD07ABC Nissan Almera
BR54URS Vauxhall Astra

This looks for any values in the Model field that start with A followed by anything
(%).

Note: if using Microsoft Access, you will need to use * instead of %.

Similarly, the wild card can be used at the beginning, in the middle or at both the
beginning and end of a string:

Wild card Example Description


End of a string Model LIKE ‘A%’ Finds all models of car that begin in A
Beginning of a string Make LIKE ‘%n’ Finds all makes of car that end in n
Middle of a string Registration Finds all cars with a registration that
LIKE ‘B%S’ starts with B and ends with S
Beginning and end Registration Finds all cars with a registration that
of a string LIKE ‘%0%’ contains a zero (0)

Activity – wild cards


Using the cars database, create the SQL queries from the table above.

Activity – wild card tutorial


Follow through the SQLite tutorial for wild cards at http://tiny.cc/sqlwild

© paullong.net 2021 Page 22 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity – currencies
Using the currencies database, create SQL queries to find:
1) Country names of any country that uses the Euro in alphabetical
order.
2) Names of countries that end in ‘land’.
3) Names of countries and their code that have a code beginning with C.
4) Names of countries that include the word ‘and’.
5) Country names and the currency of countries that use any form of dollar.
6) Country names and regions of countries in any part of Asia.
7) Country names and Income Group of countries that are classed as High
income.
8) Country names and Income Group of countries that have any variation of
middle income.

IN

Activity – IN BETWEEN tutorials

Follow through the SQLite tutorial for WHERE at http://tiny.cc/sqlwhere


which includes an introduction to IN and BETWEEN.

Amend the SQL statements at http://tiny.cc/sqlbasics to show the correct results.

Your teacher will tell you whether you need to record your answers on the
worksheet or only use SQL Zoo online.

The IN keyword will look for data in a list. The list of values that can be included will
be separated by commas.
SELECT <fieldnames>
FROM <table name>
WHERE <fieldname> IN (<values separated by commas>)

Example – IN
To show all Nissan, Ford and Volkswagen cars:
SELECT Registration, Make, Model
FROM cars
WHERE Make IN (‘Nissan’, ‘Ford’, ‘Volkswagen’)

Registration Make Model


BX03HMW Ford Focus
BA55WEP Volkswagon Beetle
BD07ABC Nissan Almera
BE14RTJ Nissan Leaf

© paullong.net 2021 Page 23 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

The IN keyword replaces the need to use lots of OR statements. The equivalent
SQL query using OR instead of IN for the example above would be:

SELECT Registration, Make, Model


FROM cars
WHERE Make = 'Nissan'
OR Make = 'Ford'
OR Make = 'Volkswagen'

Activity – IN tutorial
Follow through the SQLite tutorial for IN at http://tiny.cc/sqlin

Activity – WHERE quiz


Complete the SQL Zoo World quiz at http://tiny.cc/sqlquiz

Your teacher will tell you whether you need to record your answers on the
worksheet or only use SQL Zoo online.

BETWEEN
The BETWEEN keyword will find data between two values:

SELECT <fieldnames>
FROM <table name>
WHERE <fieldname> BETWEEN <low value> AND <high value>

This is a simpler way of writing:

SELECT <fieldnames>
FROM <table name>
WHERE <fieldname> >= <low value>
AND <fieldname> <= <high value>

Example – BETWEEN
To show all Nissan, Ford and Volkswagen cars:
SELECT Registration, Make, Model, RegYear
FROM cars
WHERE RegYear BETWEEN 2001 AND 2010

Registration Make Model RegYear


BR54URS Vauxhall Astra 2007
BC13PRS Mini Cooper 2005
BD07ABC Nissan Almera 2004
BE14RTJ Nissan Leaf 2003

© paullong.net 2021 Page 24 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity – BETWEEN tutorial


Follow through the SQLite tutorial for BETWEEN at
http://tiny.cc/sqlbetween

Activity – SELECT basics quiz


Complete the SQL Zoo SELECT basics quiz at http://tiny.cc/sqlbasicsquiz

Your teacher will tell you whether you need to record your answers on the
worksheet or only use SQL Zoo online.

Activity – Nobel Prize winners


Amend and write SQL statements for questions 1-10 of the SQL Nobel Prize winners
tutorial at http://tiny.cc/sqlnobel to show the correct results for Nobel Prize Winners.

Extension: complete questions 11-13

Your teacher will tell you whether you need to record your answers on the
worksheet or only use SQL Zoo online.

Activity – world data


Amend and write SQL statements for questions 1-2, 5-7 of the SQL world data
tutorial at http://tiny.cc/sqlworld to show the correct results.

Extension: complete questions 3-4, 8-13

Your teacher will tell you whether you need to record your answers on the
worksheet or only use SQL Zoo online.

Activity – books
Using the books database, create SQL queries to find:

1) All titles, places and dates of publication for titles published in Derby,
Swindon or Brecon in order of the date of publication with the latest
published book appearing first. Do not use OR as part of the conditional
statement.
2) All titles and dates of publication for titles published between 1980 and 1989.
3) All titles and physical descriptions for titles which include a map (ignore the
genre field, but look at the physical description field).
4) All titles and places of publication for titles which include the Welsh
language.
5) The names of authors who have had books published in Singapore in 2008.
6) All titles and countries of publication of books that include an online
resource.
© paullong.net 2021 Page 25 of 35 by Paul Long
The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Multiple tables
SQL queries can find data from more than one table. For AQA GCSE Computer
Science, you will never be asked to find data from more than two tables.

When using two tables, there may be fields that have the same name. Therefore,
each field should be prefixed by the table name:
tablename.fieldname

Data from two tables can be linked by comparing the primary key and foreign
key. If they match, then records will be linked together.
SELECT <fieldnames>
FROM <table name 1>, <table name 2>
WHERE <foreign key> = <primary key>

Example – multiple tables


A theme park requires its employees to take part in regular training courses. The
Courses table is shown below:
CourseID CourseTitle DurationHrs BonusPoints
1 1st Aid + 8 2
2 Basic 1st Aid 4 1
3 Conflict Resolution 8 3
4 Emergency Evacuation 6 1
5 Park Layout 8 1
6 Queue Management 8 2
7 Ride Specific Procedures 8 3

The primary key for the course table is CourseID.

The Employees table is shown below with a primary key of EmployeeNumber:

Employee Forename Surname Town Employment BasicSalary LoyaltyBonus


Number Date
006 Simon Jones Coventry 16/12/2009 £38,000.00 No
007 Roger Dodger Birmingham 25/01/2010 £21,000.00 No
008 Mark Barnsley Coventry 01/06/2010 £17,900.00 No
009 Diana Mander Birmingham 06/06/2010 £22,000.00 No
010 Alison Smith Coventry 07/07/2010 £31,000.00 No

The courses that an employee attends are stored in a separate table called
Attendance. This table has a primary key of QualificaitonID. A sample of records is
shown below:
QualificationID EmployeeID CourseID DateAttended Pass
1 008 1 22/07/2020 No
2 009 3 21/06/2020 No
3 006 6 17/06/2020 Yes
4 006 2 19/06/2020 Yes
5 006 1 23/06/2020 Yes

© paullong.net 2021 Page 26 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

The Attendance table has two foreign keys. EmployeeID is a foreign key that links
to the primary key EmployeeNumber in the Employees table. CourseID is a foreign
key that links to the CourseID in the Courses table.

The relationships between the tables are:

COURSE ATTENDANCE EMPLOYEE

A course can have many attendances. An employee can also have many
attendances. Each attendance only has one course and one employee.

To find the names of the employees who were in attendance, we could use:
SELECT QualificationID, EmployeeID, Forename, Surname
FROM attendance, employee
WHERE EmployeeID = EmployeeNumber

This would produce the following output:


QualificationID EmployeeID Forename Surname
3 006 Simon Jones
4 006 Simon Jones
5 006 Simon Jones
1 008 Mark Barnsley
2 009 Diana Mander

What do you think will happen if the following SQL query is run?
SELECT QualificationID, CourseID, CourseTitle
FROM attendance, course
WHERE CourseID = CourseID

The SQL query did not work. This is because there are two fields called CourseID.
One field is in the attendance table and the other in the course table. The query
for employees above worked because EmployeeID was named differently to
EmployeeNumber.

To solve this problem, the name of the table needs to prefix any fields that exist in
both tables:
SELECT QualificationID, Attendance.CourseID, CourseTitle
FROM attendance, course
WHERE Attendance.CourseID = Course.CourseID

Run the query above and experiment by including more fields.

© paullong.net 2021 Page 27 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Note: although JOIN methods could be used, at this level it is OK to just find data
by matching the foreign and primary keys.

Activity – multiple tables


Using the music database, answer the questions below:

1) Predict what the output will be for the SQL query below:

SELECT TrackID, Name, Title


FROM tracks, albums
WHERE tracks.Albumid = albums.Albumid
AND tracks.Trackid BETWEEN 22 and 24

2) Correct the SQL query below to find the title, artist ID of all the albums and
the name of the artist featured on each album in alphabetical order of the
album title.

SELECT Title, ArtistID, Name


FROM Albums, Artists
WHERE ArtistID = ArtistID
ORDER BY Name

3) Create SQL queries to find:


a) The invoice ID, invoice date of all invoices together with the first and last
names of the customer for each invoice in order of invoice ID.
b) The unit price, quantity and track ID of all invoice items together with the
invoice date and total cost of the invoice where the total cost of the
invoice is at least £20. An invoice item is a single line on an invoice.
c) The track id, name of track, unit price of track and unit price of the
invoice item for all invoice items where the unit price of the track is
different to the unit price of the invoice item. An invoice item is the sale
of an individual track.
d) The names of all tracks together with the name of the genre.
e) The names of all tracks together with the name of the media type for all
tracks that have a bracket in the name.
f) The first and last name of all French customers together with the ID of
their support rep and the first name, surname and phone number of the
employee who is their support rep.

© paullong.net 2021 Page 28 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Inserting data
Records can be insert into a table using the INSERT command:
INSERT <table name>
VALUES (<value1>, <value2>, ...)
(<value11>, <value12>, ...)
...
(<value91>, <value92>, ...)

Example – inserting records


To add a single record to the cars table, use:

INSERT INTO cars


VALUES ('DY65RTP', 'Landrover', 'Discovery', 'Black', 2015, 'A')

This will add the following record:

Registration Make Model Colour Reg Year Transmission


DY65RTP Landrover Discovery Black 2015 A

To add multiple records at the same time, separate each record using a comma:
INSERT INTO cars
VALUES ('BD71FZZ', 'Volvo', 'XC90', 'Green', 2021, 'M'),
('KB69CRH', 'Mitsubishi', 'Outlander', 'White', 2019, 'A'),
('EA55XPZ', 'Ford', 'S-Max', 'Silver', 2015, 'A')

This will add the following records:


Registration Make Model Colour Reg Year Transmission
BD71FZZ Volvo XC90 Green 2021 M
KB69CRH Mitsubishi Outlander White 2019 A
EA55XPZ Ford S-Max Silver 2015 A

Note: MS Access will only allow one record to be added at a time.

Activity – INSERT tutorial


Follow through the SQLite tutorial for INSERT at http://tiny.cc/sqlinsert

From the tutorial above, you will see that it is possible to add data without using all
the fields. To do this, the field names must be specified:
INSERT <table name> (<fieldname1>, <fieldname2>, . . .)
VALUES (<value1>, <value2>, ...)
(<value11>, <value12>, ...)
...
(<value91>, <value92>, ...)
© paullong.net 2021 Page 29 of 35 by Paul Long
The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Example – inserting some fields


To add records with just some fields use:
INSERT INTO cars (Registration, Make, Model, RegYear
VALUES ('J4MES', 'BMW', 'X5', 2021),
('P4ULL', 'Audi', 'RSQ8', 2021)

This will add the following records:

Registration Make Model Colour Reg Year Transmission


J4MES BMW X5 2021
P4ULL Audi RSQ8 2021

Note: MS Access only allows one record to be inserted at a time using SQL.

Activity – INSERT records


Using the music database (use the version named
“music for insert update delete”), answer the questions below:

1) a) Adapt the SQL query below to insert a new employee called Melissa
Stokes who is a member of the IT staff reporting to Michael Mitchell.
No other information is known about her yet.
INSERT INTO employees (LastName, FirstName, Title, ReportsTo)
VALUES ('Edwards', 'Nancy', 'SalesManager', 1)

b) What happened to the Employeeid? Why do you think this


happened?

2) Create SQL queries to insert:


a) Three new customers. Their names are Barrack Obama, Donald Trump
and George Bush. They are all from the USA and all have Michael
Mitchell (6) as their Support Rep.
Note: if using MS Access, you will need to do these one at a time.

b) A new artist called Jessie Hackett who will have an ArtistID of 276. You
should not include fieldnames after INTO.

c) A new Album called You Lift me Up by Jessie Hackett.

d) A new invoice item (ID 2241) for the sale of one track of Momentos Que
Marcam on invoice 412 for 79p. You will need to find out some of
the data needed from the tracks table. Click on the SQL link or
open the test query in MS Access to see if it has worked.
© paullong.net 2021 Page 30 of 35 by Paul Long
The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Updating data
Data values within a table can be updated. The table name should be specified
and then the new values for each field. Finally, the record(s) which should be
changed should be identified using the WHERE statement.
UPDATE <tablename>
SET <fieldname1> = value1, <fieldname2> = value2
WHERE <condition>

Example – updating data


This first example updates a single field. The colour of the Nissan
Almera was wrongly recorded as red and should be pink. This is the
table before the update:
Registration Make Model Colour Reg Year Transmission
BX03HMW Ford Focus Blue 2003 M
BR54URS Vauxhall Astra Red 2004 M
BA55WEP Volkswagon Beetle Blue 2005 M
BC13PRS Mini Cooper Green 2013 A
BD07ABC Nissan Almera Red 2007 M
BE14RTJ Nissan Leaf Blue 2014 A

Run the SQL query to update the table and watch what happens:

UPDATE cars
SET Colour = 'Pink'
WHERE Registration = 'BD07ABC'

This is the updated record:

Registration Make Model Colour Reg Year Transmission


BD07ABC Nissan Almera Pink 2007 M

Predict the effect of the following update query on more than one record:
UPDATE cars
SET Make = 'Nissan UK'
WHERE Make = 'Nissan'

Predict the effect of the following update query on more than one field:
UPDATE cars
SET Make = 'BMW', Model = 'Mini Cooper'
WHERE Model = 'Cooper'
© paullong.net 2021 Page 31 of 35 by Paul Long
The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity – UPDATE tutorial


Follow through the SQLite tutorial for UPDATE at http://tiny.cc/sqlupdate

Activity – UPDATE records


Using the music database (use the version named
“music for insert update delete”), answer the questions below:

1) Predict what the SQL query below will do:

UPDATE employees
SET LastName = 'Matthews'
WHERE EmployeeID = 2

2) Create SQL queries to make the following changes:

a) Kathy Chase, who is a customer, has married and changed her surname
to Bartholomew.

b) The price of all tracks that cost £1.99 have been reduced to £1.64.

c) The employee Steve Johnson has moved to Dawson Creek in British


Columbia (BC) which is still in Canada. His new address is 120 Quebec
Road and his postcode is V1G 0H9.

d) The track called Princess of the Dawn has changed its media type to be
an MPEG audio file. No other tracks have changed their media type.

e) All tracks composed by Billy Cobham need to have an extra 2000


milliseconds added to them which is an extra 200 bytes.

© paullong.net 2021 Page 32 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Deleting data
Records can be deleted using the DELETE command. To do this, the table needs
to be specified and the records selected for deletion using WHERE.

DELETE FROM <tablename>


WHERE <condition>

Example – deleting data


This first example will delete a single record:

DELETE FROM cars


WHERE Registration = 'BX03HMW'

Run the SQLquery and the whole record for that car will be deleted:
Registration Make Model Colour Reg Year Transmission
BX03HMW Ford Focus Blue 2003 M
BR54URS Vauxhall Astra Red 2004 M
BA55WEP Volkswagon Beetle Blue 2005 M
BC13PRS Mini Cooper Green 2013 A
BD07ABC Nissan Almera Red 2007 M
BE14RTJ Nissan Leaf Blue 2014 A

Predict the effect of the following delete query on multiple records:


DELETE FROM cars
WHERE Make = 'Nissan'

Predict the effect of the following delete query on multiple records:

DELETE FROM cars


WHERE RegYear < 2010

There should now be only one record left:

Registration Make Model Colour Reg Year Transmission


BA55WEP Volkswagen Beetle Blue 2014 M

Predict the effect of the following delete query:

DELETE FROM cars

© paullong.net 2021 Page 33 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Activity – DELETE tutorial


Follow through the SQLite tutorial for DELETE at http://tiny.cc/sqldelete

Activity – DELETE records


Using the music database (use the version named
“music for insert update delete”), answer the questions below:

Create SQL queries to delete:


1) The artist called Baby Consuelo.

2) All artists with an ID between 160 and 178.

3) All albums by Led Zeppelin.

© paullong.net 2021 Page 34 of 35 by Paul Long


The Ultimate GCSE CS Textbook for AQA – Chapter 7 Published by paullong.net

Questions – follow me
1) Examine the database tables for students and classes below:

Surname Forename DateOfBirth Gender Class


Schmidt Anna 12/05/2003 F 10TR
Abraham Aaron 14/02/2003 M 10QU
Boden Michelle 18/09/2002 F 10TR
Jones Judith 30/08/2003 F 10QU
Soni Sudhir 19/12/2002 M 10TR
Le Tissier Matthew 03/06/2003 M 10PR

Class Classroom Capacity Teacher Tier


10TR B1 30 BDE 1
10QU B3 30 MOH 2
10PR C2 28 BMO 3
10FH D4 24 JDE 4

a) Show the output of the following SQL query:


SELECT Surname, Forename
FROM students
WHERE CLASS = '10QU'
OR CLASS = '10PR' [2]

b) Write an SQL query to show only the names of all male students in 10TR.[3]

c) The capacity (maximum number of students) for each class in tiers 3 and
4 needs to be reduced by 2. Refine the SQL query below to correct the
errors.

UPDATE students
SET tier = tier - 2
WHERE tier BETWEEN (3,4) [3]

d) Write an SQL query to show the names of all students and their classroom
who have a classroom that starts with the letter B. [4]

© paullong.net 2021 Page 35 of 35 by Paul Long

You might also like