Skip to content

9618 · Unit 8 · Paper 1: Theory fundamentals

Databases.

9618 · Unit 8 · Databases
Revisionbyexamplicity

Why use a relational database?

§8.1 · Database concepts · the file-based approach

At a cookery school, the bookings program and the mailing program each keep their own copy of Mei Lin’s name, and the copies disagree. In a file-based approach each program keeps its own data files. A relational database reduces repeated facts using related tables, and every program uses it through the DBMS.

File-based approachBookings programMailing programbookings fileW01 M03 Mei LinW04 M03 Mei LinW06 M03 Mei Linmailing-list fileM01 Aisha KhanM03 Mei LinnM05 Priya ShahMei's name is stored in both files and repeated in eachbooking. One copy was typed differently, so the copiesdisagree: redundancy has caused inconsistency.Relational databaseBookings programMailing programDBMSMEMBERMemberIDFirstNameLastNameM02TomReyesM03MeiLinBOOKINGWorkshopIDMemberIDW01M03W04M03W06M03Mei's name is stored once, in MEMBER. Each booking refersto her by MemberID, so one update changes what everyprogram sees.
File-based: programs keep separate copiesBookings programbookings fileWorkshopIDMemberIDNameW01M03Mei LinW04M03Mei LinW06M03Mei LinMailing programmailing-list fileMemberIDNameM01Aisha KhanM03Mei LinnM05Priya ShahM03's copies disagree: Lin / Linn.Relational: both programs use the DBMSBookings programMailing programDBMSMEMBERFirstNameLastNameMemberIDTomReyesM02MeiLinM03BOOKINGWorkshopIDMemberIDW01M03W04M03W06M03All three M03 bookings refer to one MEMBER name.

Limitations of files, and how a relational database addresses them

Each weakness of separate files ends in wrong or wasted data somewhere. Be able to name each limitation and say how a relational database addresses it.

LimitationWhy it happens with filesHow a relational database addresses it
Data redundancythe same data is stored many times, in different filesseparate, linked tables: each fact, such as a member’s name, is stored once; related tables reuse its key
Data inconsistency (poor data integrity)data updated in one place is not updated everywhere, so copies disagreea member’s name is updated once in MEMBER; every linked booking uses that record
Program–data dependencea change to a file's structure means every program that uses it must be rewrittenprogram–data independence: programs use the DBMS rather than fixed file layouts, so storage changes need not require program rewrites
Complex searches are difficulta new program has to be written for each new searchcomplex queries are run by the query processor, for example in SQL
Lack of privacyanyone who can open a file sees all of itdifferent views and access rights: each user sees only the parts of the database they need
Several users can also work on the database at the same time: the DBMS manages concurrent access, for example with record locking.
Your turn

An orchestra keeps two files: a hire file (each instrument lent, with the player’s name and school year) and a concert file (each player in a concert, with their name and year).

1 Ana’s school year is stored in both files. Which limitation is this?

2 Her year is changed in the hire file only. What problem does this cause?

3 How would a relational database store Ana’s year?

  1. 1
    data redundancy: the same data is stored more than once
  2. 2
    data inconsistency: the two files now disagree about her year
  3. 3
    once, in one PLAYER record; the hire and concert tables refer to her by her PlayerID
Tick what you can do now
Exam focusAnswer in pairs: name the limitation, then explain how the relational database addresses it: “less data redundancy, because linked tables mean a member’s name is stored once”. Link the benefit to the actual stored facts, rather than only saying “more efficient”.
Practise with w24/11 Q2(a); w24/12 Q6(a)
1 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Tables, records and fields

§8.1 · Database concepts · relational terminology

The cookery school’s database must hold members, workshops and bookings without mixing them up. A relational database is a set of related tables. Each table holds the data about one entity, with one row for each instance of it.

MemberIDFirstNameLastNameM01AishaKhanM02TomReyesM03MeiLinM04SamOkaforM05PriyaShahM06LeoGrantMEMBERTable (relation)the data about one entityPrimary keyunique for every recordRecord (tuple)one row: one member's dataField (attribute)one column: one item of data
MEMBERMemberIDFirstNameLastNameM01AishaKhanM02TomReyesM03MeiLinM04SamOkaforM05PriyaShahM06LeoGrant12341Table: MEMBER represents the member entity.2Primary key: MemberID uniquely identifies a row.3Record: M03, Mei, Lin is one complete tuple.4Field: LastName is a column; Lin is one value.

Terms to use precisely

Define each term, then give an example from a named table.

TermDefinitionExample
Entityan object (a person, thing or event) about which data can be stored; it is represented as a tablea member; a workshop
Table (relation)the data stored about one entity, in rows and columnsMEMBER
Record (tuple)a row of data in a table about one instance of the entityM03, Mei, Lin
Field (attribute)a column in a table: one item of data about the entityLastName in MEMBER
Relational databasea collection of tables, linked by primary and foreign keysMEMBER and BOOKING, linked by MemberID

Writing a table design

Name the table, then list its fields in brackets. Underline the primary key with a solid line; if asked, mark a foreign key with a broken line.

WORKSHOP(WorkshopID, CourseCode, WorkshopDate, StartTime, Places)

Do not confuse

A relation is a table. A relationship is a link between two tables. A tuple is a whole row, not one value: Lin is one attribute value.

Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00

1 How many records (tuples) and how many fields (attributes) does INSTRUMENT have?

2 Which entity does INSTRUMENT represent?

3 Give one tuple from INSTRUMENT, and one attribute value.

4 Write the table design, with the primary key underlined.

  1. 1
    5 records, 4 fields
  2. 2
    an instrument the orchestra lends
  3. 3
    for example I3, Flute, Woodwind, 10.00 is a tuple; Woodwind is one attribute value
  4. 4
    INSTRUMENT(InstrumentID, Name, Family, HireFee)
Tick what you can do now
Exam focusDefine the term, then give an example from the database in the question, naming the table: “a field is a column in a table, for example LastName in MEMBER”. A tuple is one row about one instance, not one item of data.
Practise with w24/13 Q4(d); s21/12 Q1(a) (older paper: term with example); w22/11 Q4(c)(i) (older paper: tuple example)
2 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Keys and indexes

§8.1 · Database concepts · keys and indexing

Two members can share a name, so the database needs a value that is never repeated. A key identifies or links records. Every table has a primary key; a foreign key links a record to the primary key of a record in another table.

Keys identify records and link tables

Define each kind of key and pick it out in a table design.

KeyDefinitionExample
Primary keythe unique attribute, or combination of attributes, that identifies each record (tuple)MemberID in MEMBER
Candidate keyan attribute, or smallest set of attributes, that could be the primary key: no two tuples have the same valueWorkshopDate + StartTime: one kitchen, one workshop at a time
Secondary keyan additional search key used alongside the primary key; an unchosen candidate key is one exampleWorkshopDate + StartTime; LastName as a search key
Composite keya primary key made of two or more attributesWorkshopID + MemberID
Foreign keya field in one table that is linked to a primary key in another table; its values can repeatMemberID in BOOKING

BOOKING needs a key made of two fields. Try each field on its own, and the data soon gives a clash.

Neither field is enough by itself

Try one fieldCounterexample from BOOKING
WorkshopID W01both M01 and M02 book it
MemberID M01books both W01 and W02

A member cannot book the same workshop twice: the pair WorkshopID + MemberID identifies one booking.

Indexing

Records are stored in MemberID order, so finding a surname would mean checking every row. Follow the blue arrow from Okafor in the index to record 4.

Index on LastNameLastNamePointerGrant6Khan1Lin3Okafor4Reyes2Shah5MEMBERRecordMemberIDLastName1M01Khan2M02Reyes3M03Lin4M04Okafor5M05Shah6M06Grant
LastName indexLastNamePointerGrant6Khan1Lin3Okafor4Reyes2Shah5MEMBERRecordMemberIDLastName1M01Khan2M02Reyes3M03Lin4M04Okafor5M05Shah6M06GrantSorted Okafor entry → pointer 4 → record 4.

What an index is

A separate, smaller table: the values of one field, in order, each with a pointer to its record. To find Okafor, the DBMS searches the short sorted index, then follows the pointer to record 4.

Any field used for searching can be indexed: the primary key or a secondary key. Cost: extra storage, and the index must be updated when records change.

Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00
PLAYER
PlayerIDFirstNameInstrumentIDSchoolYear
P1AnaI110
P2BenI311
P3CaraI112
P4DevI410
P5EliI312

1 Give the primary key of PLAYER.

2 Give the foreign key in PLAYER, and the table it links to.

3 Could Family be the primary key of INSTRUMENT? Use the data.

4 A LESSON table records each player’s lessons, with one lesson per player per day. Suggest its primary key.

  1. 1
    PlayerID
  2. 2
    InstrumentID, linked to the primary key of INSTRUMENT
  3. 3
    no: String appears 2 times, so Family is not unique
  4. 4
    a composite key: PlayerID + LessonDate
Tick what you can do now
Exam focusA primary key must be unique for every possible record, not just the sample rows: a name or a title can repeat, so it is not a safe key without a uniqueness rule. Write “primary key” or “foreign key” in full: just “key” is not enough.
Practise with s25/11 Q5(b), (c); s25/12 Q5(b); w24/11 Q2(c); s22/12 Q5(b) (older paper: composite-key reason)
3 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Relationships and E-R diagrams

§8.1 · Database concepts · relationships and E-R diagrams

One course runs as many workshops, but each workshop is for one course. A relationship links two entities like these. Its degree says how many instances of one entity can be linked to one instance of the other.

One-to-one, one-to-many, many-to-many

Read each row across: the drawing, the link read both ways, then which table holds the foreign key.

DegreeE-R diagramRead it both waysHow it is implemented
One-to-one (1:1)MEMBERLOGINOne member has one login. Each login belongs to one member.The primary key of one table is a unique foreign key in the other: MemberID in LOGIN, for example also its primary key.
One-to-many (1:M)COURSEWORKSHOPOne course runs as many workshops. Each workshop is of one course.The primary key of the table at the one end is a foreign key in the table at the many end: CourseCode in WORKSHOP.
Many-to-many (M:M)WORKSHOPMEMBEROne workshop has many members. One member books many workshops.Cannot be implemented directly in a normalised relational database: add a linking table (next page).

One-to-one (1:1)

MEMBERLOGIN

One member has one login. Each login belongs to one member.

The primary key of one table is a unique foreign key in the other: MemberID in LOGIN, for example also its primary key.

One-to-many (1:M)

COURSEWORKSHOP

One course runs as many workshops. Each workshop is of one course.

The primary key of the table at the one end is a foreign key in the table at the many end: CourseCode in WORKSHOP.

Many-to-many (M:M)

WORKSHOPMEMBER

One workshop has many members. One member books many workshops.

Cannot be implemented directly in a normalised relational database: add a linking table (next page).

Draw entity links

  • One box for each entity, named as its table.
  • One line for each relationship; a plain end for one, a crow's foot for many.
  • No line between tables that are not directly linked by a key.

Follow CourseCode

WORKSHOP
WorkshopIDCourseCode
W01BRD1
W03BRD1

Both foreign-key values reference the one BRD1 primary key in COURSE: many workshops, one course.

Many-to-one (M:1) is the same link read from the other table: WORKSHOP to COURSE is M:1. The foreign key in a 1:M relationship is in the table at the many end.
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00
PLAYER
PlayerIDFirstNameInstrumentIDSchoolYear
P1AnaI110
P2BenI311
P3CaraI112
P4DevI410
P5EliI312

1 Read the link between INSTRUMENT and PLAYER both ways, using the data.

2 Give the degree of the relationship. Which table holds the foreign key?

3 At which entity does the crow’s foot go?

  1. 1
    one instrument (I1) is played by many players (P1, P3); each player has one instrument
  2. 2
    one-to-many (1:M); PLAYER holds InstrumentID as a foreign key
  3. 3
    PLAYER, the many end
Tick what you can do now
Exam focusGive the degree and the keys that make it: “one-to-many: the primary key CourseCode in COURSE is a foreign key in WORKSHOP”. Read both directions: one course, many workshops; each workshop, one course.
Practise with s24/13 Q4(a); w25/12 Q4(a); s26/11 Q4(a); s26/12 Q3(a); s21/11 Q7(b)(i) (older paper: examples of all three degrees)
4 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Linking tables and complete E-R diagrams

§8.1 · Database concepts · E-R diagrams

A member books many workshops, and each workshop has many members. That many-to-many relationship cannot be stored directly, because a foreign key holds only one value. A linking table turns it into two one-to-many relationships.

Top: the link as first drawn, with a crow’s foot at both ends. Below: BOOKING sits between the two tables, and each new link has its crow’s foot at BOOKING.

Many-to-manyWORKSHOPMEMBERadd a linking tableWORKSHOPBOOKINGMEMBERWorkshopIDMemberIDWorkshopID, MemberID, Paidtwo foreign keys = composite primary key
WORKSHOPMEMBERAdd BOOKINGWORKSHOPPrimary key: WorkshopIDBOOKINGWorkshopID + MemberIDComposite primary key · PaidMEMBERPrimary key: MemberIDWorkshopIDforeign keyMemberIDforeign keyPaid describes one workshop/member pair.
  • One WORKSHOP has many BOOKING records; each booking is for one workshop.
  • One MEMBER has many BOOKING records; each booking is by one member.

The linking table

  • It holds the primary key of each table as a foreign key.
  • Its primary key is usually those two foreign keys together (a composite key); a new single field such as BookingID can also identify it. Under this school's rule, the workshop/member pair must still not repeat.
  • It stores facts about the pair: Paid depends on both the workshop and the member.

Draw an E-R diagram from table designs

The tables already hold the relationships; the diagram makes them visible. Be able to draw every relationship from the foreign keys, with the right end for many.

Use the keys: a bike-hire scheme

STATION(StationID, StationName, Town)
BIKE(BikeID, Model, StationID)
RIDER(RiderID, FirstName, Phone)
HIRE(HireID, BikeID, RiderID, HireDate, Hours)
1
Find each foreign key and check whether it can repeat: it references a primary key in another table.
2
Draw one line between those two tables.
3
If it can repeat, put the crow's foot at the table holding the foreign key. If it must be unique, the relationship is 1:1.

HireID identifies one hire event: the same rider/bike pair can occur again.

STATIONBIKERIDERHIREStationIDBikeIDRiderID
STATIONBIKERIDERHIREStationIDBikeIDRiderID
  • One BIKE has many HIRE records: BikeID repeats in HIRE.
  • One RIDER has many HIRE records: RiderID repeats in HIRE.
  • One STATION has many BIKE records: StationID repeats in BIKE.
Your turn
ROOM(RoomID, RoomName)
ENSEMBLE(EnsembleID, EnsembleName, RoomID)
PLAYER(PlayerID, FirstName)
MEMBERSHIP(EnsembleID, PlayerID, Part)

1 A player can play in many ensembles and an ensemble has many players. Which table is the linking table?

2 List every relationship, naming the foreign key that makes it.

3 Where does the crow’s foot go on each line?

  1. 1
    MEMBERSHIP: it holds both primary keys as foreign keys
  2. 2
    ENSEMBLE to MEMBERSHIP (1:M), through EnsembleID; PLAYER to MEMBERSHIP (1:M), through PlayerID; ROOM to ENSEMBLE (1:M), through RoomID
  3. 3
    at the table holding the foreign key: MEMBERSHIP, MEMBERSHIP and ENSEMBLE
Tick what you can do now
Exam focusDraw the links supported by the foreign keys. A repeated foreign key gives the many end; a unique foreign key can make a one-to-one link. Check each line's two endpoints.
Practise with w24/11 Q2(b)(i); s25/11 Q5(a); s25/12 Q5(a); s25/13 Q6(a); w24/12 Q6(b)(i)
5 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Referential integrity

§8.1 · Database concepts · referential integrity

A booking for member M09 makes no sense if there is no member M09. Referential integrity ensures that every foreign key value has a matching primary key value in the table it refers to, so related data stays consistent.

MEMBERMemberIDFirstNameLastNameM01AishaKhanM02TomReyesM03MeiLinM04SamOkaforM05PriyaShahBOOKINGWorkshopIDMemberIDPaidW01M03FALSEW02M04FALSEW04M03TRUEW04M04TRUEW06M03TRUEW02M09FALSEno M09M04 has twobookingsorphan:rejectedEvery MemberID in BOOKING must match a MemberID in MEMBER. Grey arrows: each foreign key value and the primary key it depends on.
MEMBERFirstNameLastNameMemberIDAishaKhanM01TomReyesM02MeiLinM03SamOkaforM04PriyaShahM05BOOKINGWorkshopIDPaidMemberIDW01FALSEM03W02FALSEM04W04TRUEM03W04TRUEM04W06TRUEM03W02FALSEM09M04 has two dependent bookings.M03 has three: cascading update changes all three.M09 has no MEMBER row: reject the new booking.Delete/update behaviour depends on the configuredrestrict or cascading rule.

What the DBMS does when a link could break

For each change, say whether the DBMS accepts it, refuses it or cascades it.

Add a booking for M09

M09 is not in MEMBER, so the DBMS rejects the new record. A booking cannot refer to a member who does not exist: no orphaned record.

Delete member M04

M04 still has 2 bookings. Either the delete is refused, or, with cascading delete, those 2 bookings are deleted as well.

Change M03 to M13

With cascading update, the change to the primary key is made in all 3 bookings that refer to M03, so no booking is left pointing at M03.

Why referential integrity matters

  • Every foreign key has a corresponding primary key.
  • It prevents records being added, deleted or modified incorrectly, so there are no orphaned records (records that refer to a record that no longer exists).
  • Configured cascading update / delete rules change dependent records; restrictive rules refuse a change that would break a link.
  • So the links stay consistent; other validation and correct source data are still needed.
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00
PLAYER
PlayerIDFirstNameInstrumentIDSchoolYear
P1AnaI110
P2BenI311
P3CaraI112
P4DevI410
P5EliI312

1 A new player P6 is added with InstrumentID I9. What does the DBMS do, and why?

2 Instrument I1 is deleted with cascading delete. How many PLAYER records are deleted?

3 Instrument I2 is deleted. Why does referential integrity allow it?

  1. 1
    rejects it: I9 has no matching primary key in INSTRUMENT
  2. 2
    2: P1, P3 play I1
  3. 3
    no PLAYER record refers to I2, so no record is left orphaned
Tick what you can do now
Exam focusName the question's tables and the fields that form the link: “MemberID in BOOKING is a foreign key that depends on the primary key MemberID in MEMBER; with cascading delete, deleting a member also deletes all bookings with that MemberID”.
Practise with w24/11 Q2(c); w24/13 Q4(e); w25/11 Q2(d); s26/13 Q4(b)
6 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Normalisation: 1NF, 2NF and 3NF

§8.1 · Database concepts · normalisation

Mei Lin’s name went wrong because it was stored twice. Normalisation organises data into tables so that each fact is stored once. Each form builds on the last.

Unnormalised (0NF)repeating groupsFirst normal form1NFto reach 1NF:remove repeating groupsSecond normal form2NFto reach 2NF:remove partial dependenciesThird normal form3NFto reach 3NF:remove non-key dependencies
0NFRepeating groupsRemove repeating groups1NFAtomic fields; no repeating groupsRemove partial dependencies2NFNo partial dependenciesRemove non-key dependencies3NFNo non-key / transitive dependencies

The three normal forms

Each form catches a different way a fact can end up stored twice. Be able to state each form in one line and name the dependency it removes.

FormA table is in this form when…To reach it
1NFthere are no repeating groups of attributes; every field is atomic (holds one value); the table has a primary keymove the repeating group to a new table; its primary key includes the original key
2NFit is in 1NF and every non-key attribute is fully dependent on the whole primary key: there are no partial (key) dependenciesmove each attribute that depends on only part of a composite key to a table with that part as its key
3NFit is in 2NF and every non-key attribute depends on the primary key and no other attribute: there are no non-key (transitive) dependenciesmove attributes that depend on another non-key attribute to a new table; leave that attribute behind as a foreign key

Every rule turns on a dependency. Learn the two kinds first; then see each rule checked against the school’s final design.

Dependencies

  • B depends on A when each value of A gives exactly one value of B: MemberID → LastName.
  • Partial dependency: on only part of a composite key.
  • Non-key (transitive) dependency: on another non-key attribute, such as CourseName on CourseCode in a workshop table.

Apply each dependency rule

CheckEvidence in the final school design
1NFBOOKING has one workshop/member pair per row, with atomic fields
2NFPaid depends on the pair; names belong in MEMBER, not on part of the BOOKING key
3NFCourseName, Level and Fee belong in COURSE: they depend on CourseCode
A table in 1NF whose primary key is a single field is already in 2NF: there is no part of the key for an attribute to depend on. It can still fail 3NF.
Your turn

1 ENSEMBLE(EnsembleID, EnsembleName, (PlayerID, FirstName)): the brackets repeat for each player. Which form does it fail?

2 PART(EnsembleID, PlayerID, FirstName, Part). Which form does it fail, and why?

3 ENSEMBLE(EnsembleID, EnsembleName, RoomID, RoomName). Which form does it fail, and why?

  1. 1
    1NF: it has a repeating group
  2. 2
    2NF: FirstName depends on PlayerID only, part of the key (a partial dependency)
  3. 3
    3NF: RoomName depends on RoomID, a non-key attribute (a non-key dependency)
Tick what you can do now
Exam focusOne precise line per form. 1NF: no repeating groups. 2NF: no partial dependencies. 3NF: no non-key dependencies. Justify with a table and a field from the question: “it is in 3NF” is not a reason.
Practise with w25/11 Q2(b); w21/12 Q6(a)(i) (older paper: stage matching); s22/13 Q6(c) (older paper: normal-form definitions)
7 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Normalising the workshop registers: 1NF

§8.1 · Database concepts · normalisation

The cookery school prints a register for each workshop. Each one repeats the course details, and a member who books twice is written out twice. Turn these three into a normalised design.

W01 · 07/03/2026 · 10:00
BRD1 Bread basics
level B · fee 45.00 · 8 places
MemberPaid
M01  Aisha KhanYes
M02  Tom ReyesYes
M03  Mei LinNo
W03 · 14/03/2026 · 10:00
BRD1 Bread basics
level B · fee 45.00 · 8 places
MemberPaid
M05  Priya ShahYes
W04 · 21/03/2026 · 18:00
THA3 Thai street food
level A · fee 65.00 · 10 places
MemberPaid
M02  Tom ReyesNo
M03  Mei LinYes
M04  Sam OkaforYes
M05  Priya ShahNo

Unnormalised: list every data item

WORKSHOP(WorkshopID, WorkshopDate, StartTime, Places, CourseCode, CourseName, Level, Fee, (MemberID, FirstName, LastName, Paid))

Shaded: the repeating group (one set per attendee). Here first and last names are separate attributes used by the school.

Step 1: first normal form

Move the repeating group to its own table; its key is the original key plus the group’s own key.

WORKSHOP1NF
WorkshopIDprimary keyWorkshopDateStartTimePlacesCourseCodeCourseNameLevelFee
W0107/03/202610:008BRD1Bread basicsB45.00
W0314/03/202610:008BRD1Bread basicsB45.00
W0421/03/202618:0010THA3Thai street foodA65.00
WORKSHOP1NF · same table / rows
WorkshopIDprimary keyWorkshopDateStartTimePlaces
W0107/03/202610:008
W0314/03/202610:008
W0421/03/202618:0010
WORKSHOP1NF · continued attributes · same rows
WorkshopIDprimary keyCourseCodeCourseNameLevel
W01BRD1Bread basicsB
W03BRD1Bread basicsB
W04THA3Thai street foodA
WORKSHOP1NF · continued attributes · same rows
WorkshopIDprimary keyFee
W0145.00
W0345.00
W0465.00

BOOKING takes the repeating group: one row for each attendee at each workshop, so its key is the pair.

BOOKING1NF
WorkshopIDkey · FKMemberIDkeyFirstNameLastNamePaid
W01M01AishaKhanTRUE
W01M02TomReyesTRUE
W01M03MeiLinFALSE
W03M05PriyaShahTRUE
W04M02TomReyesFALSE
W04M03MeiLinTRUE
W04M04SamOkaforTRUE
W04M05PriyaShahFALSE
BOOKING1NF · same table / rows
WorkshopIDkey · FKMemberIDkeyFirstNameLastName
W01M01AishaKhan
W01M02TomReyes
W01M03MeiLin
W03M05PriyaShah
W04M02TomReyes
W04M03MeiLin
W04M04SamOkafor
W04M05PriyaShah
BOOKING1NF · continued attributes · same rows
WorkshopIDkey · FKMemberIDkeyPaid
W01M01TRUE
W01M02TRUE
W01M03FALSE
W03M05TRUE
W04M02FALSE
W04M03TRUE
W04M04TRUE
W04M05FALSE

What changed

One MemberID field in WORKSHOP could store only one attendee. A separate BOOKING table keeps each attendee atomic: its key is WorkshopID and MemberID. WorkshopID also links back to WORKSHOP as a foreign key.

Is it finished?

Every field is atomic and no group repeats inside a record, but the shaded names are stored once for every workshop a member books. Step 2 removes this.

Your turn

Rehearsal register R1 · 12/05/2026 · Hall A. Players: P1 Ana (Violin); P2 Ben (Flute); P3 Cara (Violin).

1 Write the unnormalised design, with the repeating group in brackets.

2 Name the repeating group.

3 Write the two tables in 1NF. What is the primary key of the new table?

  1. 1
    REHEARSAL(RehearsalID, RehearsalDate, Room, (PlayerID, FirstName, Instrument))
  2. 2
    PlayerID, FirstName, Instrument: one set for each player at the rehearsal
  3. 3
    REHEARSAL(RehearsalID, RehearsalDate, Room) and ATTENDANCE(RehearsalID, PlayerID, FirstName, Instrument); its key is RehearsalID + PlayerID
Tick what you can do now
Exam focusFor 1NF, name the repeating group, move it to a new table and give that table a primary key that includes the original key. Make fields atomic for the data items required; here first and last names are separate attributes.
Practise with s25/11 Q5(d); w23/12 Q2(c) (older paper: normalise a printed record)
8 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Normalising the workshop registers: 2NF and 3NF

§8.1 · Database concepts · normalisation

After step 1, each member’s name is still stored again for every workshop they book. Steps 2 and 3 split a table wherever a field depends on something other than the whole primary key. Each split leaves a foreign key behind, so the tables still link.

Steps 2 and 3: find each dependency that breaks the rule

Each arrow runs from a key to a field it decides. Amber arrows start from only part of the key, or from a field that is not a key: those fields must move.

BOOKING in 1NF · key: WorkshopID + MemberIDWorkshopIDMemberIDcomposite primary keyPaidFirstNameLastNamewhole keypart ofthe keyFirstName and LastName depend on MemberID only.WORKSHOP in 2NF · key: WorkshopIDWorkshopIDWorkshopDateStartTimePlacesCourseCodeCourseNameLevelFeeCourseName, Level and Fee depend on CourseCode.
BOOKING in 1NF: composite primary keyWorkshopIDMemberIDPaidwhole keyFirstNameLastNameNames depend on MemberID alone: partial dependency.WORKSHOP in 2NF: one-field primary keyWorkshopIDWorkshopDateStartTimePlacesCourseCodeCourseNameLevelFeeCourse facts depend on non-key CourseCode:a transitive dependency; separate COURSE.

Step 2: names depend on part of the key (MemberID), so they move to MEMBER

Amber marks the fields that depend on the wrong thing. Each name is now stored once.

BOOKINGbefore: 1NF
WorkshopIDMemberIDkey partFirstNameon MemberID onlyLastNameon MemberID onlyPaid
W01M01AishaKhanTRUE
W01M02TomReyesTRUE
W01M03MeiLinFALSE
W03M05PriyaShahTRUE
W04M02TomReyesFALSE
W04M03MeiLinTRUE
W04M04SamOkaforTRUE
W04M05PriyaShahFALSE
BOOKINGbefore: 1NF · same table / rows
WorkshopIDMemberIDkey partFirstNameon MemberID onlyLastNameon MemberID only
W01M01AishaKhan
W01M02TomReyes
W01M03MeiLin
W03M05PriyaShah
W04M02TomReyes
W04M03MeiLin
W04M04SamOkafor
W04M05PriyaShah
BOOKINGbefore: 1NF · continued attributes · same rows
WorkshopIDMemberIDkey partPaid
W01M01TRUE
W01M02TRUE
W01M03FALSE
W03M05TRUE
W04M02FALSE
W04M03TRUE
W04M04TRUE
W04M05FALSE
MEMBERafter
MemberIDFirstNameLastName
M01AishaKhan
M02TomReyes
M03MeiLin
M04SamOkafor
M05PriyaShah
BOOKINGafter
WorkshopIDMemberIDPaid
W01M01TRUE
W01M02TRUE
W01M03FALSE
W03M05TRUE
W04M02FALSE
W04M03TRUE
W04M04TRUE
W04M05FALSE

Step 3: course facts depend on CourseCode, a non-key field, so they move to COURSE

Bread basics, level B and 45.00 repeat for every BRD1 workshop. Moved to COURSE, each is stored once; CourseCode stays behind as the link.

WORKSHOPbefore: 2NF · the fields the split moves
WorkshopIDCourseCodenon-keyCourseNameon CourseCodeLevelon CourseCodeFeeon CourseCode
W01BRD1Bread basicsB45.00
W03BRD1Bread basicsB45.00
W04THA3Thai street foodA65.00
WORKSHOPbefore: 2NF · the fields the split moves · same table / rows
WorkshopIDCourseCodenon-keyCourseNameon CourseCodeLevelon CourseCode
W01BRD1Bread basicsB
W03BRD1Bread basicsB
W04THA3Thai street foodA
WORKSHOPbefore: 2NF · the fields the split moves · continued attributes · same rows
WorkshopIDFeeon CourseCode
W0145.00
W0345.00
W0465.00
COURSEafter
CourseCodeCourseNameLevelFee
BRD1Bread basicsB45.00
THA3Thai street foodA65.00
WORKSHOPafter · date, time and places stay
WorkshopIDCourseCode
W01BRD1
W03BRD1
W04THA3

Result of step 2

MEMBER(MemberID, FirstName, LastName)
BOOKING(WorkshopID, MemberID, Paid)

MemberID is now also a foreign key. WORKSHOP is unchanged: a single-field key cannot have a partial dependency in this primary-key model.

Result of step 3

COURSE(CourseCode, CourseName, Level, Fee)
WORKSHOP(WorkshopID, CourseCode, WorkshopDate, StartTime, Places)

CourseCode stays in WORKSHOP as a foreign key, so each workshop still links to its course.

The design in 3NF

COURSE(CourseCode, CourseName, Level, Fee)
WORKSHOP(WorkshopID, CourseCode, WorkshopDate, StartTime, Places)
MEMBER(MemberID, FirstName, LastName)
BOOKING(WorkshopID, MemberID, Paid)
COURSEWORKSHOPBOOKINGMEMBER
COURSEWORKSHOPBOOKINGMEMBER
  • One COURSE is linked to many WORKSHOP records; each WORKSHOP record to one COURSE.
  • One WORKSHOP is linked to many BOOKING records; each BOOKING record to one WORKSHOP.
  • One MEMBER is linked to many BOOKING records; each BOOKING record to one MEMBER.

Check your answer

In 1NF “Bread basics” was stored 2 times and Mei Lin's name 2 times; in 3NF each is stored once. Joining the four tables on their keys rebuilds all 8 register lines, so no data has been lost.

Your turn

1 PART(EnsembleID, PlayerID, FirstName, Part) is in 1NF. Which field breaks 2NF, and why?

2 Write the tables in 2NF.

3 ENSEMBLE(EnsembleID, EnsembleName, RoomID, RoomName). Write it in 3NF.

  1. 1
    FirstName: it depends on PlayerID only, part of the key
  2. 2
    PLAYER(PlayerID, FirstName) and PART(EnsembleID, PlayerID, Part)
  3. 3
    ROOM(RoomID, RoomName) and ENSEMBLE(EnsembleID, EnsembleName, RoomID), RoomID kept as a foreign key
Tick what you can do now
Exam focusName the dependency that breaks each form: FirstName depends only on MemberID, part of the key (fails 2NF); CourseName depends on CourseCode, a non-key field (fails 3NF). Keep a foreign key every time you split a table.
Practise with w24/13 Q4(c)(ii)
9 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Design a normalised database

§8.1 · Database concepts · producing a normalised design

Often there are no registers to start from, only a description of what must be stored. The same steps turn a description, a set of data or a set of tables into a 3NF design. Here a dance school describes its classes.

The description

A dance school records its pupils and the classes they attend. Each class has a style, a day, a start time and one teacher; a teacher can teach many classes. A pupil can attend many classes, and a class has many pupils.

The school stores each pupil's name and date of birth, each teacher's name and phone number, and the date each pupil joined each class.

  • A dance school records its pupils and the classes they attend.
  • Each class has a style, a day, a start time and one teacher; a teacher can teach many classes.
  • A pupil can attend many classes, and a class has many pupils.
  • Stored: each pupil’s name and date of birth; each teacher’s name and phone number.
  • Also stored: the date each pupil joined each class.
1
Find the entities: the things that have many instances (pupil, class, teacher).
2
Give each a primary key. Create an ID when no field is certain to be unique; a name or title is unsafe without a uniqueness rule.
3
Read each relationship both ways. For a many-to-many, add a linking table holding both primary keys as foreign keys.
4
Put each named attribute in the table whose key it depends on. A fact about a pair (the date joined) goes in the linking table.
5
Check every foreign key matches a primary key, and that no partial or non-key dependency is left.

The dance school design in 3NF

TEACHER(TeacherID, FirstName, LastName, Phone)
DANCE_CLASS(ClassID, Style, ClassDay, StartTime, TeacherID)
PUPIL(PupilID, FirstName, LastName, DateOfBirth)
ENROLMENT(PupilID, ClassID, DateJoined)
TEACHERDANCE_CLASSENROLMENTPUPIL
TEACHERDANCE_CLASSENROLMENTPUPIL
  • One TEACHER is linked to many DANCE_CLASS records; each DANCE_CLASS record to one TEACHER.
  • One DANCE_CLASS is linked to many ENROLMENT records; each ENROLMENT record to one DANCE_CLASS.
  • One PUPIL is linked to many ENROLMENT records; each ENROLMENT record to one PUPIL.

From a given table that is not in 3NF

STAFF(StaffID, StaffName, OfficeID, OfficeTown, OfficePhone): OfficeTown and OfficePhone depend on OfficeID, a non-key field.

Fix: OFFICE(OfficeID, OfficeTown, OfficePhone) and STAFF(StaffID, StaffName, OfficeID), with OfficeID as the foreign key.

What earns the marks

  • Sensible table names.
  • A suitable primary key in every table.
  • The linking table holds the primary keys of the other tables as foreign keys.
  • Every field in the description placed in the correct table.
Your turn

A choir records its singers and its concerts. Each concert is at one venue on one date. A singer sings in many concerts; a concert has many singers. Store each singer’s name and voice part, and the fee each singer is paid for each concert.

1 Name the entities.

2 Which relationship needs a linking table?

3 Write a design in 3NF, with primary keys underlined.

  1. 1
    singer and concert
  2. 2
    singer to concert, many-to-many
  3. 3
    SINGER(SingerID, SingerName, VoicePart); CONCERT(ConcertID, Venue, ConcertDate); PERFORMANCE(SingerID, ConcertID, Fee), with SingerID and ConcertID as foreign keys. The fee depends on the pair, so it goes in the linking table
Tick what you can do now
Exam focusUse the field names the question gives and a primary key in every table, based on guaranteed uniqueness, and show the foreign keys in the linking table. A table for each entity, plus one linking table for each many-to-many relationship.
Practise with s24/11 Q6(a); s26/13 Q4(a); s24/12 Q4(d); s24/13 Q4(d)
10 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

The DBMS: features and tools

§8.2 · Database management systems · features and tools

Tables do not look after themselves: something has to store them, check them and decide who sees what. A database management system (DBMS) creates a database, maintains its data and controls who can use it.

Every user and program reaches the tables only through the DBMS. Its parts are named in the boxes, and the table below says what each one does.

Database designerReception staffBooking appDBMScreates, manages and controls access to the dataDeveloper interfacecreate tables, relationships,forms, reports and menusQuery processorruns queries on criteria,returns the resultsData dictionarymetadata: dataabout the dataData integrityvalidation,referential integrityData securityaccess rights,backupsDatabasethe tables of data
DesignerdatabaseReceptionstaffBooking appDBMS: manages data and accessDeveloperinterfaceforms / reportsQuery processorcriteria → resultsData dictionaryMetadata: types, rules, keysData integrityvalidationreferential integrityData securityaccess rightsbackupsDatabasethe tables of data

Features and tools of a DBMS

Name each feature or tool, say what it does and give a specific example.

Feature or toolWhat it is or doesExample
Data managementstoring, retrieving and updating the data; maintaining the data dictionary
Data dictionarydata about the data in the database (metadata): data types, validation rules, primary and foreign keys, relationships, viewsPlaces: INTEGER, 1 to 12
Data modellingdesigning the structure of the data: the entities, their attributes and the relationships between theman E-R diagram
Logical schemaan overview of the database structure, independent of any particular DBMS; used to design the physical structureE-R diagram, table designs
Developer interfacetools to create, modify and delete tables and relationships, and to create forms (drop-down boxes, buttons), reports and menusa form for adding new members
Query processorlets the user enter criteria (or SQL), searches for the data that meets them and organises the resultsmembers who have not paid
Your turn

1 Which feature stores that HireFee is REAL and must be more than 0?

2 Which tool would staff use to build a form for lending an instrument?

3 Which tool finds every player in school year 12?

4 Give two specific items the data dictionary holds for the PLAYER table.

  1. 1
    the data dictionary
  2. 2
    the developer interface
  3. 3
    the query processor
  4. 4
    for example: PlayerID is VARCHAR(3) and the primary key; InstrumentID is a foreign key to INSTRUMENT
Tick what you can do now
Exam focusA data dictionary example must be specific: a field's data type, a validation rule, a primary key. “Metadata” is the definition, not an example, and just “key” is not enough. If the question already names the tables and fields, give other items.
Practise with s24/11 Q6(b); s25/13 Q6(d)(ii); s26/12 Q3(c); w22/13 Q2(f) (older paper: query processor)
11 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Data integrity

§8.2 · Database management systems · data integrity

A database is only as useful as the data in it. Data integrity means the data is accurate, complete, consistent and up to date. The DBMS uses rules and checks to reduce wrong or inconsistent data; it cannot guarantee that every value is correct.

How a DBMS supports data integrity

Each method stops a different way for wrong data to get in or to spread.

MethodHow it supports integrity
Validation rulesdata must meet set criteria, so inappropriate data is rejected when it is entered
Verificationcompares the data entered with the original (source) data, so copying errors are found
Referential integrityevery foreign key has a matching primary key; changes can cascade to related records
Normalisationa fact is stored once rather than copied into each related record, reducing inconsistent copies

Follow one typed value through both checks: the range check lets the mistyped 9 through, and double entry catches it.

source formPlaces: 8typedPlaces: 9Validation: range checkPlaces must be 1 to 129 passes: it is reasonablechecks the data is sensibleVerification: double entrytyped again from the form8 ≠ 9: the error is foundchecks the copy against the sourceValid data is not always correct: a value can pass every validation check and still be wrong.
source formPlaces: 8typedPlaces: 9Validation: range checkPlaces must be 1 to 129 passes: it is reasonableVerification: double entrytyped again from the form8 ≠ 9: the error is foundValid data is not always correct: a valuecan pass every validation checkand still be wrong.

Validation rules for the cookery school

Choose a check for a named field and write its rule.

CheckWhat it testsExample rule
Presence checka value must be enteredWorkshopID cannot be left empty
Range checka number lies between limitsPlaces from 1 to 12
Type checkthe value is of the right data typePlaces is a whole number
Length checkthe number of characters is allowedMemberID has exactly 3 characters
Format checkthe value follows a patternWorkshopID is W then two digits
Look-up / existence checkthe value is in a list of allowed valuesLevel is B, I or A

Verification methods

  • Double entry: the data is entered twice and the computer compares the two copies.
  • Visual check: the person compares what is on screen with the source document.

Do not confuse

Validation only checks that data is reasonable: “Places = 9” passes a range check even if the workshop has 8 places. Verification checks the entry against the original. Data can still be wrong after both if the original data was wrong.

Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00

1 Choose a check and a rule for Family.

2 Choose a check and a rule for InstrumentID.

3 A range check allows HireFee from 5.00 to 15.00. Which record fails it?

4 A clerk types 12.00 for the Flute instead of 10.00. Which method could find the error?

  1. 1
    look-up check: String, Woodwind or Brass
  2. 2
    format check: I followed by a digit (or a length check: exactly 2 characters)
  3. 3
    I2 (18.00)
  4. 4
    verification (double entry or a visual check): 12.00 passes validation because it is reasonable
Tick what you can do now
Exam focusDescribe a validation method by what it checks in the named field: “a look-up check, so Level can only be B, I or A”. A DBMS supports data integrity through validation, referential integrity (cascading update and delete) and normalisation.
Practise with s25/12 Q5(c)(ii); s26/11 Q4(d)(i), (d)(ii); w24/13 Q4(e); s23/12 Q2(c)(i) (older paper: named-field validation)
12 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Data security

§8.2 · Database management systems · data security

Reception staff need to change bookings, but a visitor to the school’s website should see far less. Data security means protecting the data from unauthorised access, and from loss or damage. The DBMS controls who can do what, and keeps copies that can be restored.

Stop unauthorised accessuserPasswordproves who you areAccess rightsread, write or noneViewonly the fields neededdatabaseEach layer can turn the user away. Encryption makes stolen data unreadable without the key.Recover from loss or damagedatabaseregular backup copyrestore after a lossoff-site copykept in a different place, in severalgenerations, and tested by restoring
Stop unauthorised accessuserdatabaseEach layer can turn the user away:Passwordproves who you areAccess rightsread, write or noneViewonly the fields neededEncryption makes stolen dataunreadable without the key.Recover from loss or damagedatabaseoff-site copyregular backuprestoreKept in a different place, in severalgenerations, and tested by restoring.

Access rights for individuals and groups of users

Read what each group may do with each table, and say why it needs no more.

User groupCOURSEWORKSHOPMEMBERBOOKING
Managerread and writeread and writeread and writeread and write
Reception staffread onlyread onlyread and writeread and write
Instructorsread onlyread onlyread onlyread only
Website visitorsread onlyread onlyno accessno access
User groupCOURSEWORKSHOP
ManagerR/WR/W
Reception staffRR
InstructorsRR
Website visitorsRR

Continued permissions for the same user groups:

User groupMEMBERBOOKING
ManagerR/WR/W
Reception staffR/WR/W
InstructorsRR
Website visitors——

R/W = read and write · R = read only · — = no access

Security methods and how each protects the data

Name a method and say how it protects the data.

MethodHow it protects the data
Access rightsset for individuals or groups of users: each account can read, read and write, or not see each table, so only users with the correct permissions can read or edit the data
Viewsa user is given a view showing only the fields and records they need; the rest of the database is hidden
Passwords / authenticationusers must log in, which stops people without a valid account reaching the data
Encryptionthe stored data cannot be understood by anyone who gains unauthorised access, without the key
Backup proceduresregular copies of the database are kept, so the data can be restored if it is lost or damaged

A backup procedure

1
Back up regularly and automatically, for example every night, when few users are working.
2
Keep the copies in a different location (off-site or in the cloud), so one event cannot destroy both the data and its backup.
3
Keep several generations of backup, and test that a backup can actually be restored.
Your turn
PLAYER
PlayerIDFirstNameInstrumentIDSchoolYear
P1AnaI110
P2BenI311
P3CaraI112
P4DevI410
P5EliI312

1 Music teachers may look at PLAYER but not change it. What access right do they need?

2 Visiting parents should see only FirstName and SchoolYear. Which method does this?

3 The server’s disk fails. Which method lets the data be recovered, and does it stop hackers?

  1. 1
    read only on PLAYER
  2. 2
    a view showing only those two fields
  3. 3
    a backup, restored from the off-site copy; it does not stop unauthorised access
Tick what you can do now
Exam focusGive the method and how it protects the data: “access rights, so only users with permission can read or edit the MEMBER table”. A backup does not stop unauthorised access: it lets the data be restored after loss or damage.
Practise with s25/12 Q5(c)(i); w25/13 Q5(d); s26/12 Q3(c)
13 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

SQL: DDL, DML and CREATE TABLE

§8.3 · DDL and DML · creating a database

A design on paper becomes a real database when you tell the DBMS what to build. It creates and changes the database structure with its DDL, and queries and maintains the data with its DML. Structured Query Language (SQL) is the industry standard for both.

LanguageUsed toStatements
DDL (Data Definition Language)creates and modifies the structure: tables, fields, types, keysCREATE DATABASE, CREATE TABLE, ALTER TABLE
DML (Data Manipulation Language)queries the data and maintains it: adds, changes, deletes recordsSELECT, INSERT INTO, UPDATE, DELETE FROM

On one table the split is easy to see: DDL builds the frame of fields, types and keys, and DML works on the rows of values inside it.

WORKSHOPWorkshopIDCourseCodeWorkshopDateW01BRD107/03/2026W02PAS207/03/2026W03BRD114/03/2026DDL: the structureCREATE TABLE, ALTER TABLEDML: the dataSELECT, INSERT INTO,UPDATE, DELETE FROMFields, types and keys are structure; each row of values is data.
DDL: the structureCREATE TABLE, ALTER TABLEWORKSHOPWorkshopIDCourseCodeWorkshopDateW01BRD107/03/2026W02PAS207/03/2026W03BRD114/03/2026DML: the dataSELECT, INSERT INTO, UPDATE, DELETE FROMFields, types and keys are structure;each row of values is data.

Data types

Choose the SQL type that fits a field’s values.

TypeHolds
CHARACTERone character; CHARACTER(n): exactly n
VARCHAR(n)text of up to n characters
BOOLEANTRUE or FALSE
INTEGERa whole number
TypeHolds
REALa number with a fractional part
DATEa date
TIMEa time of day

Create a database and a table

A database can store nothing until each table has been defined. Be able to write CREATE TABLE with each field’s type and the keys of the table.

SQL (DDL)
CREATE DATABASE COOKERY;

CREATE TABLE WORKSHOP(
WorkshopID VARCHAR(3) NOT NULL,
CourseCode VARCHAR(4) NOT NULL,
WorkshopDate DATE,
StartTime TIME,
Places INTEGER,
PRIMARY KEY (WorkshopID),
FOREIGN KEY (CourseCode) REFERENCES COURSE(CourseCode)
);

Syntax to get right

  • Field definitions go inside brackets, separated by commas; each statement ends with a semicolon.
  • NOT NULL is a constraint: the field must always have a value. When a question asks for constraints, put it on the key and other required fields.
  • PRIMARY KEY needs the field in brackets.
  • FOREIGN KEY names its field, then REFERENCES the table and field it links to; create that table first.
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00

1 Is UPDATE part of the DDL or the DML? And ALTER TABLE?

2 Write the SQL to create the INSTRUMENT table, with InstrumentID as the primary key.

3 Why is HireFee REAL and not INTEGER?

  1. 1
    UPDATE is DML (it changes data); ALTER TABLE is DDL (it changes structure)
  2. 2
    CREATE TABLE INSTRUMENT( InstrumentID VARCHAR(3) NOT NULL, Name VARCHAR(20), Family VARCHAR(10), HireFee REAL, PRIMARY KEY (InstrumentID) );
  3. 3
    fees have a fractional part, such as 12.50
Tick what you can do now
Exam focusSay what each language is for: the DBMS uses DDL to create and change the structure of the database, and DML to query and maintain the data. SQL is the industry standard for both.
Practise with s24/12 Q4(b); s24/13 Q4(b); w25/13 Q5(b); w23/11 Q3(c)(i) (older paper: CREATE DATABASE)
14 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

CREATE TABLE with keys, and ALTER TABLE

§8.3 · DDL and DML · keys and ALTER TABLE

BOOKING needs a key made of two fields, and it links to two other tables. CREATE TABLE can set a primary key of two fields and several foreign keys. Designs also change after a table is built: ALTER TABLE changes the structure of a table that already exists.

A composite primary key and two foreign keys

Read the key lines at the end: one PRIMARY KEY that lists both fields, then one FOREIGN KEY for each table that BOOKING links to.

SQL (DDL)
CREATE TABLE BOOKING(
WorkshopID VARCHAR(3) NOT NULL,
MemberID VARCHAR(3) NOT NULL,
Paid BOOLEAN,
PRIMARY KEY (WorkshopID, MemberID),
FOREIGN KEY (WorkshopID) REFERENCES WORKSHOP(WorkshopID),
FOREIGN KEY (MemberID) REFERENCES MEMBER(MemberID)
);

Change a table with ALTER TABLE

Add a field
ALTER TABLE MEMBER
ADD Email VARCHAR(40);
Add keys to existing tables
ALTER TABLE MEMBER
ADD PRIMARY KEY (MemberID);

ALTER TABLE BOOKING
ADD FOREIGN KEY (MemberID) REFERENCES MEMBER(MemberID);

These are independent examples: start with the named key absent. Do not add a second primary key to MEMBER after creating it with one.

ALTER TABLE changes the structure, for example adding a field. It does not put data into the new field: that is UPDATE.

Choose each data type from the sample data

Choose the type from what the value looks like and how it is used.

Sample valueTypeBecause
00123VARCHAR(5)an ID: as INTEGER the leading zeros would be lost
W01VARCHAR(3)letters and digits
Yes / NoBOOLEANonly two possible values
B / I / ACHARACTERalways exactly one character
2.20REALmoney: it has a fractional part
12INTEGERa count, used in arithmetic
12/12/2024 · 13:00DATE · TIMEa date; a time of day
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00
PLAYER
PlayerIDFirstNameInstrumentIDSchoolYear
P1AnaI110
P2BenI311
P3CaraI112
P4DevI410
P5EliI312

1 Write the SQL to create PLAYER, with its primary key and its foreign key.

2 Write the SQL to add a field Maker, up to 20 characters, to INSTRUMENT.

3 Give the data type of SchoolYear, and say why.

  1. 1
    CREATE TABLE PLAYER( PlayerID VARCHAR(3) NOT NULL, FirstName VARCHAR(20), InstrumentID VARCHAR(3), SchoolYear INTEGER, PRIMARY KEY (PlayerID), FOREIGN KEY (InstrumentID) REFERENCES INSTRUMENT(InstrumentID) );
  2. 2
    ALTER TABLE INSTRUMENT ADD Maker VARCHAR(20);
  3. 3
    INTEGER: a whole number
Tick what you can do now
Exam focusFor a composite key, list both fields in one PRIMARY KEY (…). Each foreign key needs REFERENCES and the table it links to. ALTER TABLE … ADD gives the new field a name and a data type.
Practise with w24/11 Q2(b)(ii); s24/11 Q6(c)(i); s24/12 Q4(c); w25/12 Q4(b); s26/11 Q4(c)(i); w24/13 Q4(c)(i)
15 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

SQL queries: SELECT, WHERE and ORDER BY

§8.3 · DDL and DML · querying one table

Once the data is stored, you can ask it for exactly what you need, such as the beginner and intermediate courses, dearest first. SELECT picks the fields, FROM the table and WHERE the records. ORDER BY sorts the rows of the result. Test the WHERE condition on every record in turn.

Choose columns, choose rows, then sort

SQL
SELECT CourseName, Fee
FROM COURSE
WHERE Level = "B" OR Level = "I"
ORDER BY Fee DESC;
ClauseChooses
SELECTthe fields (columns) to show
FROMthe table
WHEREthe records (rows) to include
ORDER BYthe order: ASC (smallest first, the default) or DESC
CourseCodeCourseNameLevelFeeBRD1Bread basicsB45.00PAS2Fresh pastaI55.00CAK1Cake decoratingB40.00THA3Thai street foodA65.00KNF2Knife skillsI35.00COURSEWHERE keeps the ticked rows; SELECT keeps the shaded columns.ORDER BYFee DESCCourseNameFeeFresh pasta55.00Bread basics45.00Cake decorating40.00Knife skills35.00CourseNameFeeResulthighest fee first
COURSECourseCodeCourseNameLevelFeeBRD1Bread basicsB45.00PAS2Fresh pastaI55.00CAK1Cake decoratingB40.00THA3Thai street foodA65.00KNF2Knife skillsI35.00WHERE keeps levels B or I; SELECT keeps theshaded CourseName and Fee columns.ORDER BY Fee DESCResultCourseNameFeeFresh pasta55.00Bread basics45.00Cake decorating40.00Knife skills35.00
Each COURSE record tested; ORDER BY Fee DESC gives each kept record its place
CourseCodeCourseNameSELECTLevelWHEREFeeSELECT · ORDER BYIn result?
BRD1Bread basicsB45.002nd
PAS2Fresh pastaI55.001st
CAK1Cake decoratingB40.003rd
THA3Thai street foodA65.00no
KNF2Knife skillsI35.004th
Result
CourseNameFee
Fresh pasta55.00
Bread basics45.00
Cake decorating40.00
Knife skills35.00

Conditions, including dates

  • =, <>, <, >, <=, >=. AND: both true; OR: either.
  • Text in quotes: "B". Numbers and TRUE / FALSE without.
  • Dates as the question writes them, e.g. #14/03/2026#. BETWEEN … AND … also gives a range, ends included.
  • LIKE "P%": starts with P (% is any characters).
WORKSHOP
WorkshopIDCourseCodeWorkshopDateStartTime
W01BRD107/03/202610:00
W02PAS207/03/202614:00
W03BRD114/03/202610:00
W04THA321/03/202618:00
W05CAK128/03/202610:00
W06PAS204/04/202614:00
SQL · a date range
SELECT WorkshopID, CourseCode, StartTime
FROM WORKSHOP
WHERE WorkshopDate >= #14/03/2026#
AND WorkshopDate <= #31/03/2026#
ORDER BY WorkshopDate;
Result
WorkshopIDCourseCodeStartTime
W03BRD110:00
W04THA318:00
W05CAK110:00
  • =, <>, <, >, <=, >=. AND: both true; OR: either.
  • Text in quotes: "B". Numbers and TRUE / FALSE without.
  • Dates as the question writes them, e.g. #14/03/2026#. BETWEEN … AND … also gives a range, ends included.
  • LIKE "P%": starts with P (% is any characters).
SQL · a date range
SELECT WorkshopID, CourseCode, StartTime
FROM WORKSHOP
WHERE WorkshopDate >= #14/03/2026#
AND WorkshopDate <= #31/03/2026#
ORDER BY WorkshopDate;
Each WORKSHOP record tested against both dates; AND needs both to be true
WorkshopIDSELECTCourseCodeSELECTWorkshopDateWHERE · ORDER BYStartTimeSELECTIn result?
W01BRD107/03/202610:00no
W02PAS207/03/202614:00no
W03BRD114/03/202610:001st
W04THA321/03/202618:002nd
W05CAK128/03/202610:003rd
W06PAS204/04/202614:00no
Result
WorkshopIDCourseCodeStartTime
W03BRD110:00
W04THA318:00
W05CAK110:00
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00

1 Give the result of SELECT Name FROM INSTRUMENT WHERE Family = "Woodwind" ORDER BY HireFee DESC;

2 Write a query to show the Name and HireFee of every instrument whose fee is under 12.00.

3 Write a query to show the names of the String and Brass instruments in alphabetical order.

  1. 1
    Clarinet; Flute (11.00 before 10.00)
  2. 2
    SELECT Name, HireFee FROM INSTRUMENT WHERE HireFee < 12.00; gives Flute, 10.00; Clarinet, 11.00
  3. 3
    SELECT Name FROM INSTRUMENT WHERE Family = "String" OR Family = "Brass" ORDER BY Name; gives Cello; Trumpet; Violin
Tick what you can do now
Exam focusSELECT names the fields, FROM the table, WHERE the records. Put text values in quotes but not numbers or TRUE/FALSE, use AND when both conditions must hold, and write a date in the form the question uses.
Practise with w25/13 Q5(c); s23/12 Q2(c)(ii) (older paper: single-table date query)
16 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

SQL: COUNT, SUM and AVG

§8.3 · DDL and DML · aggregate functions

Sometimes the answer is one number: how many morning workshops are there? An aggregate function turns many records into one value: a count, a total or a mean. Every query below runs on these six WORKSHOP records.

FunctionReturns
COUNT(field)the number of non-NULL values; with a required field, this counts records
SUM(field)the total of the values
AVG(field)the mean of the values
… AS Namea heading for the result column
WORKSHOP
WorkshopIDCourseCodeStartTimePlaces
W01BRD110:008
W02PAS214:006
W03BRD110:008
W04THA318:0010
W05CAK110:006
W06PAS214:006

One value from the selected records

WHERE picks the records first; the function then gives one value from them.

SQL · COUNT
SELECT COUNT(WorkshopID) AS Mornings
FROM WORKSHOP
WHERE StartTime = "10:00";
Result
Mornings
3

counts the records that start at 10:00: W01, W03, W05

SQL · SUM
SELECT SUM(Places) AS PastaPlaces
FROM WORKSHOP
WHERE CourseCode = "PAS2";
Result
PastaPlaces
12

adds Places for the PAS2 workshops: 6 + 6

SQL · AVG
SELECT AVG(Places) AS MeanPlaces
FROM WORKSHOP;
Result
MeanPlaces
7.33

the mean of the 6 values: 44 ÷ 6

SQL · COUNT
SELECT COUNT(WorkshopID) AS Mornings
FROM WORKSHOP
WHERE StartTime = "10:00";
Each WORKSHOP record tested; COUNT counts the kept records
WorkshopIDCOUNTCourseCodeStartTimeWHERECounted?
W01BRD110:00yes
W02PAS214:00no
W03BRD110:00yes
W04THA318:00no
W05CAK110:00yes
W06PAS214:00no
Result
Mornings
3

SUM keeps records in the same way, then adds up one field of the kept records instead of counting them.

SQL · SUM
SELECT SUM(Places) AS PastaPlaces
FROM WORKSHOP
WHERE CourseCode = "PAS2";
Each WORKSHOP record tested; SUM adds the Places of the kept records
WorkshopIDCourseCodeWHEREPlacesSUMAdded?
W01BRD18no
W02PAS26yes
W03BRD18no
W04THA310no
W05CAK16no
W06PAS26yes
Result
PastaPlaces
12

This AVG has no WHERE, so all six records are used: add up Places, then divide by the number of records.

SQL · AVG
SELECT AVG(Places) AS MeanPlaces
FROM WORKSHOP;
No WHERE: every record is used; 44 ÷ 6
WorkshopIDPlacesAVGUsed?
W018yes
W026yes
W038yes
W0410yes
W056yes
W066yes
Result
MeanPlaces
7.33

COUNT after both conditions

SQL
SELECT COUNT(WorkshopID) AS NumWorkshops
FROM WORKSHOP
WHERE StartTime = "10:00"
AND Places >= 8;
Result
NumWorkshops
2

W01 and W03 meet both conditions. W04 has 10 places but starts at 18:00; W05 starts at 10:00 but has only 6 places.

COUNT after both conditions

SQL
SELECT COUNT(WorkshopID) AS NumWorkshops
FROM WORKSHOP
WHERE StartTime = "10:00"
AND Places >= 8;
Both tests must be true (AND); COUNT counts the kept records
WorkshopIDCOUNTStartTimeWHEREPlacesWHERECounted?
W0110:008yes
W0214:006no
W0310:008yes
W0418:0010no
W0510:006no
W0614:006no
Result
NumWorkshops
2

W01 and W03 meet both conditions. W04 has 10 places but starts at 18:00; W05 starts at 10:00 but has only 6 places.

Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00

1 Give the result of SELECT COUNT(InstrumentID) FROM INSTRUMENT WHERE Family = "String";

2 Write a query to find the total HireFee of the Woodwind instruments, with the heading WindFees.

3 Give the result of SELECT AVG(HireFee) FROM INSTRUMENT;

  1. 1
    2 (I1 and I2)
  2. 2
    SELECT SUM(HireFee) AS WindFees FROM INSTRUMENT WHERE Family = "Woodwind"; gives 21.00 (10.00 + 11.00)
  3. 3
    13.00: 65.00 ÷ 5
Tick what you can do now
Exam focusCOUNT counts records; SUM adds up the values in a field: “how many…” is COUNT, never SUM. Give the result a name with AS when a suitable name is asked for, and join two conditions with AND.
Practise with w24/11 Q2(b)(iii); w25/11 Q2(c)(ii); w24/12 Q6(b)(ii); w24/13 Q4(b); s22/11 Q4(c)(ii) (older paper: AVG); w22/13 Q2(c) (older paper: COUNT with LIKE)
17 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

SQL: GROUP BY

§8.3 · DDL and DML · grouping

One count for the whole table is rarely what the school wants; it wants the bookings for each workshop. GROUP BY puts records that share a value into one group. An aggregate then gives one result for each group, not one for the whole table.

Count the bookings for each workshop

SQL
SELECT WorkshopID, COUNT(MemberID) AS Booked
FROM BOOKING
GROUP BY WorkshopID;

Follow each bracket: the BOOKING rows that share a WorkshopID become one group, and COUNT turns each group into one row of the result.

BOOKINGWorkshopIDMemberIDPaidW01M01TRUEW01M02TRUEW01M03FALSEW02M01TRUEW02M04FALSEW03M05TRUEW04M02FALSEW04M03TRUEW04M04TRUEW04M05FALSEW05M01FALSEW06M03TRUEResult: one row per groupWorkshopIDBookedW013W022W031W044W051W061GROUP BY WorkshopID putsrows with the same WorkshopIDinto one group.COUNT(MemberID) then countsthe rows in each group.
BOOKINGWorkshopIDMemberIDPaidW01M01TRUEW01M02TRUEW01M03FALSEW02M01TRUEW02M04FALSEW03M05TRUEW04M02FALSEW04M03TRUEW04M04TRUEW04M05FALSEW05M01FALSEW06M03TRUEBooked321411One bracket = one WorkshopID group.COUNT(MemberID) counts the bookings in that group.

AVG and SUM for each group

Sort the records into groups by hand, then work out the aggregate for each group.

WORKSHOP CourseCode/Places: BRD1/8, PAS2/6, BRD1/8, THA3/10, CAK1/6, PAS2/6.

COURSE
CourseCodeCourseNameLevelFee
BRD1Bread basicsB45.00
PAS2Fresh pastaI55.00
CAK1Cake decoratingB40.00
THA3Thai street foodA65.00
KNF2Knife skillsI35.00
SQL
SELECT Level, AVG(Fee) AS MeanFee
FROM COURSE
GROUP BY Level;
Result
LevelMeanFee
A65.00
B42.50
I45.00
SQL
SELECT CourseCode, SUM(Places) AS TotalPlaces
FROM WORKSHOP
GROUP BY CourseCode;
Result
CourseCodeTotalPlaces
BRD116
CAK16
PAS212
THA310
SQL
SELECT Level, AVG(Fee) AS MeanFee
FROM COURSE
GROUP BY Level;
COURSE records in their Level groups; AVG(Fee) for each group
LevelGROUP BYCourseCodeCourseNameFeeAVGMeanFee
ATHA3Thai street food65.0065.00
BBRD1Bread basics45.0042.50
BCAK1Cake decorating40.00
IPAS2Fresh pasta55.0045.00
IKNF2Knife skills35.00
Result
LevelMeanFee
A65.00
B42.50
I45.00

Total places for each course

The same two moves with SUM: group the WORKSHOP records by CourseCode, then add up the Places in each group.

SQL
SELECT CourseCode, SUM(Places) AS TotalPlaces
FROM WORKSHOP
GROUP BY CourseCode;
WORKSHOP records in their CourseCode groups; SUM(Places) for each group
CourseCodeGROUP BYWorkshopIDPlacesSUMTotalPlaces
BRD1W01816
BRD1W038
CAK1W0566
PAS2W02612
PAS2W066
THA3W041010
Result
CourseCodeTotalPlaces
BRD116
CAK16
PAS212
THA310
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00

1 Give the result of SELECT Family, COUNT(InstrumentID) FROM INSTRUMENT GROUP BY Family;

2 Write a query to show each Family with the total HireFee of its instruments, headed FamilyFees.

3 Why must Family be in the SELECT list as well as in GROUP BY?

  1. 1
    Brass, 1; String, 2; Woodwind, 2
  2. 2
    SELECT Family, SUM(HireFee) AS FamilyFees FROM INSTRUMENT GROUP BY Family; gives Brass, 14.00; String, 30.00; Woodwind, 21.00
  3. 3
    so that each total is labelled with the group it belongs to
Tick what you can do now
Exam focusWithout GROUP BY an aggregate gives one value for the whole table. A total or count “for each” customer, show or player needs GROUP BY that field, with the field also in the SELECT list so each value is labelled. GROUP BY does not guarantee row order; add ORDER BY when order matters.
Practise with s24/11 Q6(c)(ii); w21/11 Q5(c)(i) (older paper: GROUP BY cloze)
18 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

SQL: joining two tables

§8.3 · DDL and DML · INNER JOIN

The names are in MEMBER and the payments are in BOOKING, so asking who has not paid needs both tables. A join pairs each record in one table with the records in another table whose key values match. WHERE then tests each joined row, as if it were one record.

A join pairs records whose keys match

Each line links a MemberID in MEMBER to the same MemberID in BOOKING. The two blue lines are the joined rows for W04 that are still unpaid.

MEMBERBOOKINGMemberIDFirstNameLastNameM01AishaKhanM02TomReyesM03MeiLinM04SamOkaforM05PriyaShahM06LeoGrantMemberIDWorkshopIDPaidM01W01TRUEM01W02TRUEM01W05FALSEM02W01TRUEM02W04FALSEM03W01FALSEM03W04TRUEM03W06TRUEM04W02FALSEM04W04TRUEM05W03TRUEM05W04FALSELeo (M06) has no booking, so the join leaves him out.ResultFirstNameLastNameTomReyesPriyaShahFirstNameLastNamejoined rows for W04with Paid = FALSE
MEMBERFirstNameLastNameMemberIDAishaKhanM01TomReyesM02MeiLinM03SamOkaforM04PriyaShahM05LeoGrantM06Join on MemberID; then keep WorkshopID W04and Paid = FALSE. Blue lines show the kept matches.BOOKINGWorkshopIDPaidMemberIDW01TRUEM01W02TRUEM01W05FALSEM01W01TRUEM02W04FALSEM02W01FALSEM03W04TRUEM03W06TRUEM03W02FALSEM04W04TRUEM04W03TRUEM05W04FALSEM05Result: LastName orderFirstNameLastNameTomReyesPriyaShahLeo (M06) has no matching booking: INNER JOINleaves him out; other matches fail the WHERE here.

Either query gives that result: one joins with INNER JOIN … ON, the other puts the join condition in WHERE.

SQL · INNER JOIN … ON
SELECT FirstName, LastName
FROM MEMBER INNER JOIN BOOKING
ON MEMBER.MemberID = BOOKING.MemberID
WHERE BOOKING.WorkshopID = "W04"
AND BOOKING.Paid = FALSE
ORDER BY LastName;
SQL · the same join in WHERE
SELECT FirstName, LastName
FROM MEMBER, BOOKING
WHERE MEMBER.MemberID = BOOKING.MemberID
AND BOOKING.WorkshopID = "W04"
AND BOOKING.Paid = FALSE
ORDER BY LastName;

Run it: join first, then test each joined row

The join gives 12 rows, one for each booking. Leo (M06) has no booking, so he is in none of them.

Each joined row (a member paired with one of their bookings) tested; ORDER BY LastName places the kept rows
MemberIDJOINFirstNameSELECTLastNameSELECT · ORDER BYWorkshopIDWHEREPaidWHEREIn result?
M01AishaKhanW01TRUEno
M01AishaKhanW02TRUEno
M01AishaKhanW05FALSEno
M02TomReyesW01TRUEno
M02TomReyesW04FALSE1st
M03MeiLinW01FALSEno
M03MeiLinW04TRUEno
M03MeiLinW06TRUEno
M04SamOkaforW02FALSEno
M04SamOkaforW04TRUEno
M05PriyaShahW03TRUEno
M05PriyaShahW04FALSE2nd
Result
FirstNameLastName
TomReyes
PriyaShah

Joining two tables

  • Match the primary key in one table to the foreign key in the other.
  • Use one method: INNER JOIN … ON, or both tables after FROM with the join condition in WHERE. Do not mix the two.
  • Only a field that is in both tables needs its table name: MEMBER.MemberID. Records with no match are left out: Leo has no booking.
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00
PLAYER
PlayerIDFirstNameInstrumentIDSchoolYear
P1AnaI110
P2BenI311
P3CaraI112
P4DevI410
P5EliI312

1 Give the result of SELECT FirstName, Name FROM PLAYER INNER JOIN INSTRUMENT ON PLAYER.InstrumentID = INSTRUMENT.InstrumentID WHERE Family = "String";

2 Write a query to show the first name of every player whose instrument’s HireFee is over 11.00.

3 Which instruments are in no joined row, and why?

  1. 1
    Ana, Violin; Cara, Violin
  2. 2
    SELECT FirstName FROM PLAYER INNER JOIN INSTRUMENT ON PLAYER.InstrumentID = INSTRUMENT.InstrumentID WHERE HireFee > 11.00; gives Ana; Cara; Dev
  3. 3
    Cello and Clarinet: no PLAYER record has their InstrumentID
Tick what you can do now
Exam focusThe join earns its own mark: the correct two tables and the condition that links them, MEMBER.MemberID = BOOKING.MemberID. Any correct join method gains the marks, but not a mixture of methods.
Practise with w25/12 Q4(c); s25/11 Q5(e); s24/13 Q4(c); s25/13 Q6(c)
19 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

SQL: join, group and sort

§8.3 · DDL and DML · combined query

The school wants one short report: for each course, how many workshops it runs and how many places they offer. That takes COURSE and WORKSHOP joined, grouped by course and sorted, in one query. Keep each aggregate labelled with its course.

Join first: each workshop finds its course through CourseCode. Follow BRD1, the course with two workshops.

COURSE · selected fieldsCourseNameCourseCodeBread basicsBRD1Fresh pastaPAS2Cake decoratingCAK1Thai street foodTHA3Knife skillsKNF2WORKSHOP · selected fieldsCourseCodeWorkshopIDPlacesBRD1W018PAS2W026BRD1W038THA3W0410CAK1W056PAS2W066Matching CourseCode BRD1 gives two joined rows; COUNT = 2, SUM(Places) = 16.
COURSE · selected fieldsCourseNameCourseCodeBread basicsBRD1Fresh pastaPAS2Cake decoratingCAK1Thai street foodTHA3Knife skillsKNF2WORKSHOP · selected fieldsWorkshopIDPlacesCourseCodeW018BRD1W026PAS2W038BRD1W0410THA3W056CAK1W066PAS2BRD1: two workshops, 8 + 8 = 16 places
SQL · join, group, then sort
SELECT COURSE.CourseCode, CourseName,
COUNT(WorkshopID) AS NumWorkshops,
SUM(Places) AS TotalPlaces
FROM COURSE INNER JOIN WORKSHOP
ON COURSE.CourseCode = WORKSHOP.CourseCode
GROUP BY COURSE.CourseCode, CourseName
ORDER BY COURSE.CourseCode DESC;
Result
CourseCodeCourseNameNumWorkshopsTotalPlaces
THA3Thai street food110
PAS2Fresh pasta212
CAK1Cake decorating16
BRD1Bread basics216
Result
CourseCodeCourseNameNumWorkshopsTotalPlaces
THA3Thai street food110
PAS2Fresh pasta212
CAK1Cake decorating16
BRD1Bread basics216

Join, then group: where each count and total comes from

The joined rows in their course groups, in ORDER BY CourseCode DESC order
CourseCodeGROUP BYCourseNameWorkshopIDCOUNTPlacesSUMNumWorkshopsTotalPlaces
THA3Thai street foodW0410110
PAS2Fresh pastaW026212
PAS2Fresh pastaW066
CAK1Cake decoratingW05616
BRD1Bread basicsW018216
BRD1Bread basicsW038

Knife skills (KNF2) has no workshop, so it is in no joined row and no group.

What each stage contributes

1
Join matching CourseCode values. BRD1 appears in two joined workshop rows; Knife skills has no workshop, so the inner join leaves it out.
2
Group by CourseCode and CourseName. COUNT counts the workshop records in each group; SUM adds their Places.
3
Order by CourseCode DESC: THA3, PAS2, CAK1, BRD1. This is the code's descending order, not an order by count or places.
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00
PLAYER
PlayerIDFirstNameInstrumentIDSchoolYear
P1AnaI110
P2BenI311
P3CaraI112
P4DevI410
P5EliI312
SQL
SELECT Name, COUNT(PlayerID) AS Players
FROM INSTRUMENT INNER JOIN PLAYER
ON INSTRUMENT.InstrumentID = PLAYER.InstrumentID
GROUP BY Name
ORDER BY Name;

1 Give the result of the query above.

2 Why are Cello and Clarinet not in the result?

3 Which line would you change to list the instruments with the most players first?

  1. 1
    Flute, 2; Trumpet, 1; Violin, 2
  2. 2
    no player has I2 or I5, so the inner join gives them no rows
  3. 3
    the last line: ORDER BY Players DESC (or ORDER BY COUNT(PlayerID) DESC)
Tick what you can do now
Exam focusUse the join condition before grouping. Include the course fields in GROUP BY so each count and total belongs to its course; use ORDER BY to request the result order.
Practise with s26/12 Q3(b)(ii); s26/13 Q4(c)(ii); s26/11 Q4(b)
20 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

SQL: INSERT, UPDATE and DELETE

§8.3 · DDL and DML · data maintenance

A database changes every day, as members join and fees go up. INSERT INTO adds records, UPDATE changes values in records that exist and DELETE FROM removes records. A WHERE clause picks which records UPDATE and DELETE act on.

Run the two INSERTs in order. The UPDATE and DELETE examples each restart from the original database.

INSERT INTO: add a record

SQL · values in table order
INSERT INTO MEMBER
VALUES ("M07", "Ravi", "Patel");
New MEMBER record
MemberIDFirstNameLastName
M07RaviPatel

One INSERT for each record; text in quotes.

SQL · fields named
INSERT INTO BOOKING (WorkshopID, MemberID, Paid)
VALUES ("W06", "M07", FALSE);
W06 bookings now
WorkshopIDMemberIDPaid
W06M03TRUE
W06M07FALSE

Naming the fields is safer: the values follow the list.

UPDATE: change existing records

SQL · two fields at once
UPDATE COURSE
SET Fee = 48.00, Level = "I"
WHERE CourseCode = "BRD1";
BRD1 now
CourseCodeCourseNameLevelFee
BRD1Bread basicsI48.00

SET lists each change, separated by commas.

SQL · one booking
UPDATE BOOKING
SET Paid = TRUE
WHERE WorkshopID = "W04" AND MemberID = "M02";
That booking now
WorkshopIDMemberIDPaid
W04M02TRUE

A booking is identified by both key fields.

The WHERE of the second UPDATE, run against all 12 bookings:

Each BOOKING record tested: only a record that passes both tests is changed
WorkshopIDWHEREMemberIDWHEREPaidChanged?
W01M01TRUEno
W01M02TRUEno
W01M03FALSEno
W02M01TRUEno
W02M04FALSEno
W03M05TRUEno
W04M02FALSEyes
W04M03TRUEno
W04M04TRUEno
W04M05FALSEno
W05M01FALSEno
W06M03TRUEno

DELETE FROM: remove records

SQL · every matching record
DELETE FROM BOOKING
WHERE WorkshopID = "W05";
BOOKING now
Records leftW05 records
110

All the records that meet the condition are deleted.

The same check on all 12 bookings: one is for W05, so one record goes.

Each BOOKING record tested: every record that passes is deleted
WorkshopIDWHEREMemberIDPaidDeleted?
W01M01TRUEno
W01M02TRUEno
W01M03FALSEno
W02M01TRUEno
W02M04FALSEno
W03M05TRUEno
W04M02FALSEno
W04M03TRUEno
W04M04TRUEno
W04M05FALSEno
W05M01FALSEyes
W06M03TRUEno
Without WHERE, UPDATE changes every record and DELETE FROM removes every record. ALTER TABLE changes structure; UPDATE changes data in existing fields.
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00
PLAYER
PlayerIDFirstNameInstrumentIDSchoolYear
P1AnaI110
P2BenI311
P3CaraI112
P4DevI410
P5EliI312

1 Write the SQL to add player P6, Fay, who plays I2 and is in school year 11.

2 Write the SQL to change the HireFee of the trumpet (I4) to 15.00.

3 DELETE FROM PLAYER WHERE SchoolYear = 12; runs on the original PLAYER table. How many records are left, and whose are deleted?

  1. 1
    INSERT INTO PLAYER VALUES ("P6", "Fay", "I2", 11);
  2. 2
    UPDATE INSTRUMENT SET HireFee = 15.00 WHERE InstrumentID = "I4";
  3. 3
    3 records are left; Cara and Eli (year 12) are deleted
Tick what you can do now
Exam focusUPDATE needs the table, SET with the new values and a WHERE that picks only the right record. The value must match the field's data type: a BOOLEAN field is set to TRUE or FALSE, with no quotes.
Practise with s25/13 Q6(b); s25/12 Q5(d)(ii); w25/11 Q2(c)(i); s26/11 Q4(c)(ii)
21 / 22
9618 · Unit 8 · Databases
Revisionbyexamplicity

Exam task: find and correct SQL errors

§8.3 · DDL and DML · correcting scripts

One missing comma or quote is enough to stop a script running. To correct a script, check each line in turn: keywords, commas and brackets, field and table names against the design, quotes on text, and the right function and operator.

A DDL script for the design below

WORKSHOP(WorkshopID, CourseCode, WorkshopDate, StartTime, Places)
Find four errors
 1CREATE DATA BASE COOKERY;
 2CREATE TABLE WORKSHOP(
 3WorkshopID VARCHAR(3) NOT NULL,
 4CourseCode VARCHAR(4) NOT NULL
 5TheDate DATE,
 6StartTime TIME,
 7Places INTEGER,
 8PRIMARY KEY (WorkshopID),
 9FOREIGN KEY (CourseCode)
10REFERENCES (CourseCode)
11);
Corrected
 1CREATE DATABASE COOKERY;
 2CREATE TABLE WORKSHOP(
 3WorkshopID VARCHAR(3) NOT NULL,
 4CourseCode VARCHAR(4) NOT NULL,
 5WorkshopDate DATE,
 6StartTime TIME,
 7Places INTEGER,
 8PRIMARY KEY (WorkshopID),
 9FOREIGN KEY (CourseCode)
10REFERENCES COURSE(CourseCode)
11);

Cover the corrected script and find the four errors yourself, then check each one in the table.

LineErrorCorrection
1DATABASE is one wordCREATE DATABASE COOKERY;
4no comma before the next fieldCourseCode VARCHAR(4) NOT NULL,
5the field name must match the designWorkshopDate DATE,
10REFERENCES needs the table nameREFERENCES COURSE(CourseCode)

A DML script: count the unpaid bookings of members called Lin

Find four errors
1SELECT SUM(WorkshopID) AS Unpaid
2FROM MEMBER, BOOKING
3WHERE MemberID = MemberID
4OR LastName = Lin AND Paid = FALSE;
Corrected
1SELECT COUNT(WorkshopID) AS Unpaid
2FROM MEMBER, BOOKING
3WHERE MEMBER.MemberID = BOOKING.MemberID
4AND LastName = "Lin" AND Paid = FALSE;

Compare the two scripts line by line: each difference is one error, given with its reason below.

LineErrorCorrection
1SUM adds values; this needs a countSELECT COUNT(WorkshopID) AS Unpaid
3MemberID is in both tablesWHERE MEMBER.MemberID = BOOKING.MemberID
4two errors: OR should be AND, and the text Lin needs quotesAND LastName = "Lin" AND Paid = FALSE;
Your turn
INSTRUMENT
InstrumentIDNameFamilyHireFee
I1ViolinString12.00
I2CelloString18.00
I3FluteWoodwind10.00
I4TrumpetBrass14.00
I5ClarinetWoodwind11.00

This query should list the Brass instruments that cost more than 12.00, in name order. It has three errors.

SQL
1SELECT Name, HireFee
2FROM INSTRUMENT
3WHERE Family = Brass OR HireFee > 12.00
4ORDER Name;

1 Give the line number and the correction for each error.

2 Give the result of the corrected query.

  1. 1
    line 3: Brass is text, so it needs quotes, "Brass"; line 3: both conditions must hold, so OR becomes AND; line 4: ORDER BY Name;
  2. 2
    Trumpet, 14.00
Tick what you can do now
Exam focusGive the line number and the corrected line. Check commas, brackets and keywords; field names against the design; REFERENCES with its table; COUNT, not SUM; AND, not OR; quotes on text.
Practise with s26/12 Q3(b)(i); s26/13 Q4(c)(i)
22 / 22