Why use a relational database?
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.
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.
| Limitation | Why it happens with files | How a relational database addresses it |
|---|---|---|
| Data redundancy | the same data is stored many times, in different files | separate, 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 disagree | a member’s name is updated once in MEMBER; every linked booking uses that record |
| Program–data dependence | a change to a file's structure means every program that uses it must be rewritten | program–data independence: programs use the DBMS rather than fixed file layouts, so storage changes need not require program rewrites |
| Complex searches are difficult | a new program has to be written for each new search | complex queries are run by the query processor, for example in SQL |
| Lack of privacy | anyone who can open a file sees all of it | different views and access rights: each user sees only the parts of the database they need |
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?
- 1data redundancy: the same data is stored more than once
- 2data inconsistency: the two files now disagree about her year
- 3once, in one PLAYER record; the hire and concert tables refer to her by her PlayerID
Tables, records and fields
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.
Terms to use precisely
Define each term, then give an example from a named table.
| Term | Definition | Example |
|---|---|---|
| Entity | an object (a person, thing or event) about which data can be stored; it is represented as a table | a member; a workshop |
| Table (relation) | the data stored about one entity, in rows and columns | MEMBER |
| Record (tuple) | a row of data in a table about one instance of the entity | M03, Mei, Lin |
| Field (attribute) | a column in a table: one item of data about the entity | LastName in MEMBER |
| Relational database | a collection of tables, linked by primary and foreign keys | MEMBER 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.
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.
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.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.
- 15 records, 4 fields
- 2an instrument the orchestra lends
- 3for example I3, Flute, Woodwind, 10.00 is a tuple; Woodwind is one attribute value
- 4INSTRUMENT(InstrumentID, Name, Family, HireFee)
Keys and indexes
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.
| Key | Definition | Example |
|---|---|---|
| Primary key | the unique attribute, or combination of attributes, that identifies each record (tuple) | MemberID in MEMBER |
| Candidate key | an attribute, or smallest set of attributes, that could be the primary key: no two tuples have the same value | WorkshopDate + StartTime: one kitchen, one workshop at a time |
| Secondary key | an additional search key used alongside the primary key; an unchosen candidate key is one example | WorkshopDate + StartTime; LastName as a search key |
| Composite key | a primary key made of two or more attributes | WorkshopID + MemberID |
| Foreign key | a field in one table that is linked to a primary key in another table; its values can repeat | MemberID 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 field | Counterexample from BOOKING |
|---|---|
| WorkshopID W01 | both M01 and M02 book it |
| MemberID M01 | books 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.
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.
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.00 |
| Player | First | Instrument | School |
|---|---|---|---|
| P1 | Ana | I1 | 10 |
| P2 | Ben | I3 | 11 |
| P3 | Cara | I1 | 12 |
| P4 | Dev | I4 | 10 |
| P5 | Eli | I3 | 12 |
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.
- 1PlayerID
- 2InstrumentID, linked to the primary key of INSTRUMENT
- 3no: String appears 2 times, so Family is not unique
- 4a composite key: PlayerID + LessonDate
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.
| Degree | E-R diagram | Read it both ways | How it is implemented |
|---|---|---|---|
| One-to-one (1:1) | 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) | 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) | 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). |
One-to-one (1:1)
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)
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)
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 | Course |
|---|---|
| W01 | BRD1 |
| W03 | BRD1 |
Both foreign-key values reference the one BRD1 primary key in COURSE: many workshops, one course.
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.00 |
| Player | First | Instrument | School |
|---|---|---|---|
| P1 | Ana | I1 | 10 |
| P2 | Ben | I3 | 11 |
| P3 | Cara | I1 | 12 |
| P4 | Dev | I4 | 10 |
| P5 | Eli | I3 | 12 |
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?
- 1one instrument (I1) is played by many players (P1, P3); each player has one instrument
- 2one-to-many (1:M); PLAYER holds InstrumentID as a foreign key
- 3PLAYER, the many end
Linking tables and complete 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.
- 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
BIKE(BikeID, Model, StationID)
RIDER(RiderID, FirstName, Phone)
HIRE(HireID, BikeID, RiderID, HireDate, Hours)
HireID identifies one hire event: the same rider/bike pair can occur again.
- 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.
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?
- 1MEMBERSHIP: it holds both primary keys as foreign keys
- 2ENSEMBLE to MEMBERSHIP (1:M), through EnsembleID; PLAYER to MEMBERSHIP (1:M), through PlayerID; ROOM to ENSEMBLE (1:M), through RoomID
- 3at the table holding the foreign key: MEMBERSHIP, MEMBERSHIP and ENSEMBLE
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.
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.
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.00 |
| Player | First | Instrument | School |
|---|---|---|---|
| P1 | Ana | I1 | 10 |
| P2 | Ben | I3 | 11 |
| P3 | Cara | I1 | 12 |
| P4 | Dev | I4 | 10 |
| P5 | Eli | I3 | 12 |
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?
- 1rejects it: I9 has no matching primary key in INSTRUMENT
- 22: P1, P3 play I1
- 3no PLAYER record refers to I2, so no record is left orphaned
Normalisation: 1NF, 2NF and 3NF
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.
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.
| Form | A table is in this form when… | To reach it |
|---|---|---|
| 1NF | there are no repeating groups of attributes; every field is atomic (holds one value); the table has a primary key | move the repeating group to a new table; its primary key includes the original key |
| 2NF | it is in 1NF and every non-key attribute is fully dependent on the whole primary key: there are no partial (key) dependencies | move each attribute that depends on only part of a composite key to a table with that part as its key |
| 3NF | it is in 2NF and every non-key attribute depends on the primary key and no other attribute: there are no non-key (transitive) dependencies | move 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
| Check | Evidence in the final school design |
|---|---|
| 1NF | BOOKING has one workshop/member pair per row, with atomic fields |
| 2NF | Paid depends on the pair; names belong in MEMBER, not on part of the BOOKING key |
| 3NF | CourseName, Level and Fee belong in COURSE: they depend on CourseCode |
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?
- 11NF: it has a repeating group
- 22NF: FirstName depends on PlayerID only, part of the key (a partial dependency)
- 33NF: RoomName depends on RoomID, a non-key attribute (a non-key dependency)
Normalising the workshop registers: 1NF
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.
BRD1 Bread basics
level B · fee 45.00 · 8 places
| Member | Paid |
| M01 Aisha Khan | Yes |
| M02 Tom Reyes | Yes |
| M03 Mei Lin | No |
BRD1 Bread basics
level B · fee 45.00 · 8 places
| Member | Paid |
| M05 Priya Shah | Yes |
THA3 Thai street food
level A · fee 65.00 · 10 places
| Member | Paid |
| M02 Tom Reyes | No |
| M03 Mei Lin | Yes |
| M04 Sam Okafor | Yes |
| M05 Priya Shah | No |
Unnormalised: list every data item
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.
| Workshop | Workshop | Start | Places | Course | Course | Level | Fee |
|---|---|---|---|---|---|---|---|
| W01 | 07/03/2026 | 10:00 | 8 | BRD1 | Bread basics | B | 45.00 |
| W03 | 14/03/2026 | 10:00 | 8 | BRD1 | Bread basics | B | 45.00 |
| W04 | 21/03/2026 | 18:00 | 10 | THA3 | Thai street food | A | 65.00 |
| Workshop | Workshop | Start | Places |
|---|---|---|---|
| W01 | 07/03/2026 | 10:00 | 8 |
| W03 | 14/03/2026 | 10:00 | 8 |
| W04 | 21/03/2026 | 18:00 | 10 |
| Workshop | Course | Course | Level |
|---|---|---|---|
| W01 | BRD1 | Bread basics | B |
| W03 | BRD1 | Bread basics | B |
| W04 | THA3 | Thai street food | A |
| Workshop | Fee |
|---|---|
| W01 | 45.00 |
| W03 | 45.00 |
| W04 | 65.00 |
BOOKING takes the repeating group: one row for each attendee at each workshop, so its key is the pair.
| Workshop | Member | First | Last | Paid |
|---|---|---|---|---|
| W01 | M01 | Aisha | Khan | TRUE |
| W01 | M02 | Tom | Reyes | TRUE |
| W01 | M03 | Mei | Lin | FALSE |
| W03 | M05 | Priya | Shah | TRUE |
| W04 | M02 | Tom | Reyes | FALSE |
| W04 | M03 | Mei | Lin | TRUE |
| W04 | M04 | Sam | Okafor | TRUE |
| W04 | M05 | Priya | Shah | FALSE |
| Workshop | Member | First | Last |
|---|---|---|---|
| W01 | M01 | Aisha | Khan |
| W01 | M02 | Tom | Reyes |
| W01 | M03 | Mei | Lin |
| W03 | M05 | Priya | Shah |
| W04 | M02 | Tom | Reyes |
| W04 | M03 | Mei | Lin |
| W04 | M04 | Sam | Okafor |
| W04 | M05 | Priya | Shah |
| Workshop | Member | Paid |
|---|---|---|
| W01 | M01 | TRUE |
| W01 | M02 | TRUE |
| W01 | M03 | FALSE |
| W03 | M05 | TRUE |
| W04 | M02 | FALSE |
| W04 | M03 | TRUE |
| W04 | M04 | TRUE |
| W04 | M05 | FALSE |
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.
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?
- 1REHEARSAL(RehearsalID, RehearsalDate, Room, (PlayerID, FirstName, Instrument))
- 2PlayerID, FirstName, Instrument: one set for each player at the rehearsal
- 3REHEARSAL(RehearsalID, RehearsalDate, Room) and ATTENDANCE(RehearsalID, PlayerID, FirstName, Instrument); its key is RehearsalID + PlayerID
Normalising the workshop registers: 2NF and 3NF
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.
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.
| Workshop | Member | First | Last | Paid |
|---|---|---|---|---|
| W01 | M01 | Aisha | Khan | TRUE |
| W01 | M02 | Tom | Reyes | TRUE |
| W01 | M03 | Mei | Lin | FALSE |
| W03 | M05 | Priya | Shah | TRUE |
| W04 | M02 | Tom | Reyes | FALSE |
| W04 | M03 | Mei | Lin | TRUE |
| W04 | M04 | Sam | Okafor | TRUE |
| W04 | M05 | Priya | Shah | FALSE |
| Workshop | Member | First | Last |
|---|---|---|---|
| W01 | M01 | Aisha | Khan |
| W01 | M02 | Tom | Reyes |
| W01 | M03 | Mei | Lin |
| W03 | M05 | Priya | Shah |
| W04 | M02 | Tom | Reyes |
| W04 | M03 | Mei | Lin |
| W04 | M04 | Sam | Okafor |
| W04 | M05 | Priya | Shah |
| Workshop | Member | Paid |
|---|---|---|
| W01 | M01 | TRUE |
| W01 | M02 | TRUE |
| W01 | M03 | FALSE |
| W03 | M05 | TRUE |
| W04 | M02 | FALSE |
| W04 | M03 | TRUE |
| W04 | M04 | TRUE |
| W04 | M05 | FALSE |
| Member | First | Last |
|---|---|---|
| M01 | Aisha | Khan |
| M02 | Tom | Reyes |
| M03 | Mei | Lin |
| M04 | Sam | Okafor |
| M05 | Priya | Shah |
| Workshop | Member | Paid |
|---|---|---|
| W01 | M01 | TRUE |
| W01 | M02 | TRUE |
| W01 | M03 | FALSE |
| W03 | M05 | TRUE |
| W04 | M02 | FALSE |
| W04 | M03 | TRUE |
| W04 | M04 | TRUE |
| W04 | M05 | FALSE |
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.
| Workshop | Course | Course | Levelon CourseCode | Feeon CourseCode |
|---|---|---|---|---|
| W01 | BRD1 | Bread basics | B | 45.00 |
| W03 | BRD1 | Bread basics | B | 45.00 |
| W04 | THA3 | Thai street food | A | 65.00 |
| Workshop | Course | Course | Levelon CourseCode |
|---|---|---|---|
| W01 | BRD1 | Bread basics | B |
| W03 | BRD1 | Bread basics | B |
| W04 | THA3 | Thai street food | A |
| Workshop | Feeon CourseCode |
|---|---|
| W01 | 45.00 |
| W03 | 45.00 |
| W04 | 65.00 |
| Course | Course | Level | Fee |
|---|---|---|---|
| BRD1 | Bread basics | B | 45.00 |
| THA3 | Thai street food | A | 65.00 |
| Workshop | Course |
|---|---|
| W01 | BRD1 |
| W03 | BRD1 |
| W04 | THA3 |
Result of step 2
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
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
WORKSHOP(WorkshopID, CourseCode, WorkshopDate, StartTime, Places)
MEMBER(MemberID, FirstName, LastName)
BOOKING(WorkshopID, MemberID, Paid)
- 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.
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.
- 1FirstName: it depends on PlayerID only, part of the key
- 2PLAYER(PlayerID, FirstName) and PART(EnsembleID, PlayerID, Part)
- 3ROOM(RoomID, RoomName) and ENSEMBLE(EnsembleID, EnsembleName, RoomID), RoomID kept as a foreign key
Design a normalised database
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.
The dance school design in 3NF
DANCE_CLASS(ClassID, Style, ClassDay, StartTime, TeacherID)
PUPIL(PupilID, FirstName, LastName, DateOfBirth)
ENROLMENT(PupilID, ClassID, DateJoined)
- 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.
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.
- 1singer and concert
- 2singer to concert, many-to-many
- 3SINGER(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
The DBMS: 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.
Features and tools of a DBMS
Name each feature or tool, say what it does and give a specific example.
| Feature or tool | What it is or does | Example |
|---|---|---|
| Data management | storing, retrieving and updating the data; maintaining the data dictionary | |
| Data dictionary | data about the data in the database (metadata): data types, validation rules, primary and foreign keys, relationships, views | Places: INTEGER, 1 to 12 |
| Data modelling | designing the structure of the data: the entities, their attributes and the relationships between them | an E-R diagram |
| Logical schema | an overview of the database structure, independent of any particular DBMS; used to design the physical structure | E-R diagram, table designs |
| Developer interface | tools to create, modify and delete tables and relationships, and to create forms (drop-down boxes, buttons), reports and menus | a form for adding new members |
| Query processor | lets the user enter criteria (or SQL), searches for the data that meets them and organises the results | members who have not paid |
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.
- 1the data dictionary
- 2the developer interface
- 3the query processor
- 4for example: PlayerID is VARCHAR(3) and the primary key; InstrumentID is a foreign key to INSTRUMENT
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.
| Method | How it supports integrity |
|---|---|
| Validation rules | data must meet set criteria, so inappropriate data is rejected when it is entered |
| Verification | compares the data entered with the original (source) data, so copying errors are found |
| Referential integrity | every foreign key has a matching primary key; changes can cascade to related records |
| Normalisation | a 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.
Validation rules for the cookery school
Choose a check for a named field and write its rule.
| Check | What it tests | Example rule |
|---|---|---|
| Presence check | a value must be entered | WorkshopID cannot be left empty |
| Range check | a number lies between limits | Places from 1 to 12 |
| Type check | the value is of the right data type | Places is a whole number |
| Length check | the number of characters is allowed | MemberID has exactly 3 characters |
| Format check | the value follows a pattern | WorkshopID is W then two digits |
| Look-up / existence check | the value is in a list of allowed values | Level 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.
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.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?
- 1look-up check: String, Woodwind or Brass
- 2format check: I followed by a digit (or a length check: exactly 2 characters)
- 3I2 (18.00)
- 4verification (double entry or a visual check): 12.00 passes validation because it is reasonable
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.
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 group | COURSE | WORKSHOP | MEMBER | BOOKING |
|---|---|---|---|---|
| Manager | read and write | read and write | read and write | read and write |
| Reception staff | read only | read only | read and write | read and write |
| Instructors | read only | read only | read only | read only |
| Website visitors | read only | read only | no access | no access |
| User group | COURSE | WORKSHOP |
|---|---|---|
| Manager | R/W | R/W |
| Reception staff | R | R |
| Instructors | R | R |
| Website visitors | R | R |
Continued permissions for the same user groups:
| User group | MEMBER | BOOKING |
|---|---|---|
| Manager | R/W | R/W |
| Reception staff | R/W | R/W |
| Instructors | R | R |
| 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.
| Method | How it protects the data |
|---|---|
| Access rights | set 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 |
| Views | a user is given a view showing only the fields and records they need; the rest of the database is hidden |
| Passwords / authentication | users must log in, which stops people without a valid account reaching the data |
| Encryption | the stored data cannot be understood by anyone who gains unauthorised access, without the key |
| Backup procedures | regular copies of the database are kept, so the data can be restored if it is lost or damaged |
A backup procedure
| Player | First | Instrument | School |
|---|---|---|---|
| P1 | Ana | I1 | 10 |
| P2 | Ben | I3 | 11 |
| P3 | Cara | I1 | 12 |
| P4 | Dev | I4 | 10 |
| P5 | Eli | I3 | 12 |
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?
- 1read only on PLAYER
- 2a view showing only those two fields
- 3a backup, restored from the off-site copy; it does not stop unauthorised access
SQL: DDL, DML and CREATE TABLE
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.
| Language | Used to | Statements |
|---|---|---|
| DDL (Data Definition Language) | creates and modifies the structure: tables, fields, types, keys | CREATE DATABASE, CREATE TABLE, ALTER TABLE |
| DML (Data Manipulation Language) | queries the data and maintains it: adds, changes, deletes records | SELECT, 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.
Data types
Choose the SQL type that fits a field’s values.
| Type | Holds |
|---|---|
| CHARACTER | one character; CHARACTER(n): exactly n |
| VARCHAR(n) | text of up to n characters |
| BOOLEAN | TRUE or FALSE |
| INTEGER | a whole number |
| Type | Holds |
|---|---|
| REAL | a number with a fractional part |
| DATE | a date |
| TIME | a 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.
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.
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.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?
- 1UPDATE is DML (it changes data); ALTER TABLE is DDL (it changes structure)
- 2
CREATE TABLE INSTRUMENT( InstrumentID VARCHAR(3) NOT NULL, Name VARCHAR(20), Family VARCHAR(10), HireFee REAL, PRIMARY KEY (InstrumentID) ); - 3fees have a fractional part, such as 12.50
CREATE TABLE with 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.
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
ALTER TABLE MEMBER ADD Email VARCHAR(40);
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.
Choose each data type from the sample data
Choose the type from what the value looks like and how it is used.
| Sample value | Type | Because |
|---|---|---|
| 00123 | VARCHAR(5) | an ID: as INTEGER the leading zeros would be lost |
| W01 | VARCHAR(3) | letters and digits |
| Yes / No | BOOLEAN | only two possible values |
| B / I / A | CHARACTER | always exactly one character |
| 2.20 | REAL | money: it has a fractional part |
| 12 | INTEGER | a count, used in arithmetic |
| 12/12/2024 · 13:00 | DATE · TIME | a date; a time of day |
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.00 |
| Player | First | Instrument | School |
|---|---|---|---|
| P1 | Ana | I1 | 10 |
| P2 | Ben | I3 | 11 |
| P3 | Cara | I1 | 12 |
| P4 | Dev | I4 | 10 |
| P5 | Eli | I3 | 12 |
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
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
ALTER TABLE INSTRUMENT ADD Maker VARCHAR(20); - 3INTEGER: a whole number
SQL queries: SELECT, WHERE and ORDER BY
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
SELECT CourseName, Fee FROM COURSE WHERE Level = "B" OR Level = "I" ORDER BY Fee DESC;
| Clause | Chooses |
|---|---|
| SELECT | the fields (columns) to show |
| FROM | the table |
| WHERE | the records (rows) to include |
| ORDER BY | the order: ASC (smallest first, the default) or DESC |
CourseCode | CourseNameSELECT | LevelWHERE | FeeSELECT · ORDER BY | In result? |
|---|---|---|---|---|
| BRD1 | Bread basics | B | 45.00 | 2nd |
| PAS2 | Fresh pasta | I | 55.00 | 1st |
| CAK1 | Cake decorating | B | 40.00 | 3rd |
| THA3 | Thai street food | A | 65.00 | no |
| KNF2 | Knife skills | I | 35.00 | 4th |
CourseName | Fee |
|---|---|
| Fresh pasta | 55.00 |
| Bread basics | 45.00 |
| Cake decorating | 40.00 |
| Knife skills | 35.00 |
Conditions, including dates
=,<>,<,>,<=,>=. AND: both true; OR: either.- Text in quotes:
"B". Numbers andTRUE/FALSEwithout. - 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 | Course | Workshop | Start |
|---|---|---|---|
| W01 | BRD1 | 07/03/2026 | 10:00 |
| W02 | PAS2 | 07/03/2026 | 14:00 |
| W03 | BRD1 | 14/03/2026 | 10:00 |
| W04 | THA3 | 21/03/2026 | 18:00 |
| W05 | CAK1 | 28/03/2026 | 10:00 |
| W06 | PAS2 | 04/04/2026 | 14:00 |
SELECT WorkshopID, CourseCode, StartTime FROM WORKSHOP WHERE WorkshopDate >= #14/03/2026# AND WorkshopDate <= #31/03/2026# ORDER BY WorkshopDate;
| Workshop | Course | Start |
|---|---|---|
| W03 | BRD1 | 10:00 |
| W04 | THA3 | 18:00 |
| W05 | CAK1 | 10:00 |
=,<>,<,>,<=,>=. AND: both true; OR: either.- Text in quotes:
"B". Numbers andTRUE/FALSEwithout. - 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).
SELECT WorkshopID, CourseCode, StartTime FROM WORKSHOP WHERE WorkshopDate >= #14/03/2026# AND WorkshopDate <= #31/03/2026# ORDER BY WorkshopDate;
WorkshopIDSELECT | CourseCodeSELECT | WorkshopDateWHERE · ORDER BY | StartTimeSELECT | In result? |
|---|---|---|---|---|
| W01 | BRD1 | 07/03/2026 | 10:00 | no |
| W02 | PAS2 | 07/03/2026 | 14:00 | no |
| W03 | BRD1 | 14/03/2026 | 10:00 | 1st |
| W04 | THA3 | 21/03/2026 | 18:00 | 2nd |
| W05 | CAK1 | 28/03/2026 | 10:00 | 3rd |
| W06 | PAS2 | 04/04/2026 | 14:00 | no |
WorkshopID | CourseCode | StartTime |
|---|---|---|
| W03 | BRD1 | 10:00 |
| W04 | THA3 | 18:00 |
| W05 | CAK1 | 10:00 |
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.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.
- 1Clarinet; Flute (11.00 before 10.00)
- 2
SELECT Name, HireFee FROM INSTRUMENT WHERE HireFee < 12.00;gives Flute, 10.00; Clarinet, 11.00 - 3
SELECT Name FROM INSTRUMENT WHERE Family = "String" OR Family = "Brass" ORDER BY Name;gives Cello; Trumpet; Violin
SQL: COUNT, SUM and AVG
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.
| Function | Returns |
|---|---|
| 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 Name | a heading for the result column |
| Workshop | Course | Start | Places |
|---|---|---|---|
| W01 | BRD1 | 10:00 | 8 |
| W02 | PAS2 | 14:00 | 6 |
| W03 | BRD1 | 10:00 | 8 |
| W04 | THA3 | 18:00 | 10 |
| W05 | CAK1 | 10:00 | 6 |
| W06 | PAS2 | 14:00 | 6 |
One value from the selected records
WHERE picks the records first; the function then gives one value from them.
SELECT COUNT(WorkshopID) AS Mornings FROM WORKSHOP WHERE StartTime = "10:00";
| Mornings |
|---|
| 3 |
counts the records that start at 10:00: W01, W03, W05
SELECT SUM(Places) AS PastaPlaces FROM WORKSHOP WHERE CourseCode = "PAS2";
| Pasta |
|---|
| 12 |
adds Places for the PAS2 workshops: 6 + 6
SELECT AVG(Places) AS MeanPlaces FROM WORKSHOP;
| Mean |
|---|
| 7.33 |
the mean of the 6 values: 44 ÷ 6
SELECT COUNT(WorkshopID) AS Mornings FROM WORKSHOP WHERE StartTime = "10:00";
WorkshopIDCOUNT | CourseCode | StartTimeWHERE | Counted? |
|---|---|---|---|
| W01 | BRD1 | 10:00 | yes |
| W02 | PAS2 | 14:00 | no |
| W03 | BRD1 | 10:00 | yes |
| W04 | THA3 | 18:00 | no |
| W05 | CAK1 | 10:00 | yes |
| W06 | PAS2 | 14:00 | no |
| Mornings |
|---|
| 3 |
SUM keeps records in the same way, then adds up one field of the kept records instead of counting them.
SELECT SUM(Places) AS PastaPlaces FROM WORKSHOP WHERE CourseCode = "PAS2";
WorkshopID | CourseCodeWHERE | PlacesSUM | Added? |
|---|---|---|---|
| W01 | BRD1 | 8 | no |
| W02 | PAS2 | 6 | yes |
| W03 | BRD1 | 8 | no |
| W04 | THA3 | 10 | no |
| W05 | CAK1 | 6 | no |
| W06 | PAS2 | 6 | yes |
PastaPlaces |
|---|
| 12 |
This AVG has no WHERE, so all six records are used: add up Places, then divide by the number of records.
SELECT AVG(Places) AS MeanPlaces FROM WORKSHOP;
WorkshopID | PlacesAVG | Used? |
|---|---|---|
| W01 | 8 | yes |
| W02 | 6 | yes |
| W03 | 8 | yes |
| W04 | 10 | yes |
| W05 | 6 | yes |
| W06 | 6 | yes |
MeanPlaces |
|---|
| 7.33 |
COUNT after both conditions
SELECT COUNT(WorkshopID) AS NumWorkshops FROM WORKSHOP WHERE StartTime = "10:00" AND Places >= 8;
| Num |
|---|
| 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
SELECT COUNT(WorkshopID) AS NumWorkshops FROM WORKSHOP WHERE StartTime = "10:00" AND Places >= 8;
WorkshopIDCOUNT | StartTimeWHERE | PlacesWHERE | Counted? |
|---|---|---|---|
| W01 | 10:00 | 8 | yes |
| W02 | 14:00 | 6 | no |
| W03 | 10:00 | 8 | yes |
| W04 | 18:00 | 10 | no |
| W05 | 10:00 | 6 | no |
| W06 | 14:00 | 6 | no |
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.
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.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;
- 12 (I1 and I2)
- 2
SELECT SUM(HireFee) AS WindFees FROM INSTRUMENT WHERE Family = "Woodwind";gives 21.00 (10.00 + 11.00) - 313.00: 65.00 ÷ 5
SQL: GROUP BY
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
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.
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 | Course | Level | Fee |
|---|---|---|---|
| BRD1 | Bread basics | B | 45.00 |
| PAS2 | Fresh pasta | I | 55.00 |
| CAK1 | Cake decorating | B | 40.00 |
| THA3 | Thai street food | A | 65.00 |
| KNF2 | Knife skills | I | 35.00 |
SELECT Level, AVG(Fee) AS MeanFee FROM COURSE GROUP BY Level;
| Level | Mean |
|---|---|
| A | 65.00 |
| B | 42.50 |
| I | 45.00 |
SELECT CourseCode, SUM(Places) AS TotalPlaces FROM WORKSHOP GROUP BY CourseCode;
| Course | Total |
|---|---|
| BRD1 | 16 |
| CAK1 | 6 |
| PAS2 | 12 |
| THA3 | 10 |
SELECT Level, AVG(Fee) AS MeanFee FROM COURSE GROUP BY Level;
| LevelGROUP BY | CourseCode | CourseName | FeeAVG | MeanFee |
|---|---|---|---|---|
| A | THA3 | Thai street food | 65.00 | 65.00 |
| B | BRD1 | Bread basics | 45.00 | 42.50 |
| B | CAK1 | Cake decorating | 40.00 | |
| I | PAS2 | Fresh pasta | 55.00 | 45.00 |
| I | KNF2 | Knife skills | 35.00 |
| Level | MeanFee |
|---|---|
| A | 65.00 |
| B | 42.50 |
| I | 45.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.
SELECT CourseCode, SUM(Places) AS TotalPlaces FROM WORKSHOP GROUP BY CourseCode;
CourseCodeGROUP BY | WorkshopID | PlacesSUM | TotalPlaces |
|---|---|---|---|
| BRD1 | W01 | 8 | 16 |
| BRD1 | W03 | 8 | |
| CAK1 | W05 | 6 | 6 |
| PAS2 | W02 | 6 | 12 |
| PAS2 | W06 | 6 | |
| THA3 | W04 | 10 | 10 |
CourseCode | TotalPlaces |
|---|---|
| BRD1 | 16 |
| CAK1 | 6 |
| PAS2 | 12 |
| THA3 | 10 |
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.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?
- 1Brass, 1; String, 2; Woodwind, 2
- 2
SELECT Family, SUM(HireFee) AS FamilyFees FROM INSTRUMENT GROUP BY Family;gives Brass, 14.00; String, 30.00; Woodwind, 21.00 - 3so that each total is labelled with the group it belongs to
SQL: joining two tables
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.
Either query gives that result: one joins with INNER JOIN … ON, the other puts the join condition in WHERE.
SELECT FirstName, LastName FROM MEMBER INNER JOIN BOOKING ON MEMBER.MemberID = BOOKING.MemberID WHERE BOOKING.WorkshopID = "W04" AND BOOKING.Paid = FALSE ORDER BY LastName;
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.
MemberIDJOIN | FirstNameSELECT | LastNameSELECT · ORDER BY | WorkshopIDWHERE | PaidWHERE | In result? |
|---|---|---|---|---|---|
| M01 | Aisha | Khan | W01 | TRUE | no |
| M01 | Aisha | Khan | W02 | TRUE | no |
| M01 | Aisha | Khan | W05 | FALSE | no |
| M02 | Tom | Reyes | W01 | TRUE | no |
| M02 | Tom | Reyes | W04 | FALSE | 1st |
| M03 | Mei | Lin | W01 | FALSE | no |
| M03 | Mei | Lin | W04 | TRUE | no |
| M03 | Mei | Lin | W06 | TRUE | no |
| M04 | Sam | Okafor | W02 | FALSE | no |
| M04 | Sam | Okafor | W04 | TRUE | no |
| M05 | Priya | Shah | W03 | TRUE | no |
| M05 | Priya | Shah | W04 | FALSE | 2nd |
FirstName | LastName |
|---|---|
| Tom | Reyes |
| Priya | Shah |
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.
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.00 |
| Player | First | Instrument | School |
|---|---|---|---|
| P1 | Ana | I1 | 10 |
| P2 | Ben | I3 | 11 |
| P3 | Cara | I1 | 12 |
| P4 | Dev | I4 | 10 |
| P5 | Eli | I3 | 12 |
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?
- 1Ana, Violin; Cara, Violin
- 2
SELECT FirstName FROM PLAYER INNER JOIN INSTRUMENT ON PLAYER.InstrumentID = INSTRUMENT.InstrumentID WHERE HireFee > 11.00;gives Ana; Cara; Dev - 3Cello and Clarinet: no PLAYER record has their InstrumentID
SQL: join, group and sort
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.
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;
| Course | Course | Num | Total |
|---|---|---|---|
| THA3 | Thai street food | 1 | 10 |
| PAS2 | Fresh pasta | 2 | 12 |
| CAK1 | Cake decorating | 1 | 6 |
| BRD1 | Bread basics | 2 | 16 |
CourseCode | CourseName | NumWorkshops | TotalPlaces |
|---|---|---|---|
| THA3 | Thai street food | 1 | 10 |
| PAS2 | Fresh pasta | 2 | 12 |
| CAK1 | Cake decorating | 1 | 6 |
| BRD1 | Bread basics | 2 | 16 |
Join, then group: where each count and total comes from
CourseCodeGROUP BY | CourseName | WorkshopIDCOUNT | PlacesSUM | NumWorkshops | TotalPlaces |
|---|---|---|---|---|---|
| THA3 | Thai street food | W04 | 10 | 1 | 10 |
| PAS2 | Fresh pasta | W02 | 6 | 2 | 12 |
| PAS2 | Fresh pasta | W06 | 6 | ||
| CAK1 | Cake decorating | W05 | 6 | 1 | 6 |
| BRD1 | Bread basics | W01 | 8 | 2 | 16 |
| BRD1 | Bread basics | W03 | 8 |
Knife skills (KNF2) has no workshop, so it is in no joined row and no group.
What each stage contributes
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.00 |
| Player | First | Instrument | School |
|---|---|---|---|
| P1 | Ana | I1 | 10 |
| P2 | Ben | I3 | 11 |
| P3 | Cara | I1 | 12 |
| P4 | Dev | I4 | 10 |
| P5 | Eli | I3 | 12 |
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?
- 1Flute, 2; Trumpet, 1; Violin, 2
- 2no player has I2 or I5, so the inner join gives them no rows
- 3the last line: ORDER BY Players DESC (or ORDER BY COUNT(PlayerID) DESC)
SQL: INSERT, UPDATE and DELETE
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
INSERT INTO MEMBER VALUES ("M07", "Ravi", "Patel");
| Member | First | Last |
|---|---|---|
| M07 | Ravi | Patel |
One INSERT for each record; text in quotes.
INSERT INTO BOOKING (WorkshopID, MemberID, Paid) VALUES ("W06", "M07", FALSE);
| Workshop | Member | Paid |
|---|---|---|
| W06 | M03 | TRUE |
| W06 | M07 | FALSE |
Naming the fields is safer: the values follow the list.
UPDATE: change existing records
UPDATE COURSE SET Fee = 48.00, Level = "I" WHERE CourseCode = "BRD1";
| Course | Course | Level | Fee |
|---|---|---|---|
| BRD1 | Bread basics | I | 48.00 |
SET lists each change, separated by commas.
UPDATE BOOKING SET Paid = TRUE WHERE WorkshopID = "W04" AND MemberID = "M02";
| Workshop | Member | Paid |
|---|---|---|
| W04 | M02 | TRUE |
A booking is identified by both key fields.
The WHERE of the second UPDATE, run against all 12 bookings:
WorkshopIDWHERE | MemberIDWHERE | Paid | Changed? |
|---|---|---|---|
| W01 | M01 | TRUE | no |
| W01 | M02 | TRUE | no |
| W01 | M03 | FALSE | no |
| W02 | M01 | TRUE | no |
| W02 | M04 | FALSE | no |
| W03 | M05 | TRUE | no |
| W04 | M02 | FALSE | yes |
| W04 | M03 | TRUE | no |
| W04 | M04 | TRUE | no |
| W04 | M05 | FALSE | no |
| W05 | M01 | FALSE | no |
| W06 | M03 | TRUE | no |
DELETE FROM: remove records
DELETE FROM BOOKING WHERE WorkshopID = "W05";
| Records left | W05 records |
|---|---|
| 11 | 0 |
All the records that meet the condition are deleted.
The same check on all 12 bookings: one is for W05, so one record goes.
WorkshopIDWHERE | MemberID | Paid | Deleted? |
|---|---|---|---|
| W01 | M01 | TRUE | no |
| W01 | M02 | TRUE | no |
| W01 | M03 | FALSE | no |
| W02 | M01 | TRUE | no |
| W02 | M04 | FALSE | no |
| W03 | M05 | TRUE | no |
| W04 | M02 | FALSE | no |
| W04 | M03 | TRUE | no |
| W04 | M04 | TRUE | no |
| W04 | M05 | FALSE | no |
| W05 | M01 | FALSE | yes |
| W06 | M03 | TRUE | no |
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.00 |
| Player | First | Instrument | School |
|---|---|---|---|
| P1 | Ana | I1 | 10 |
| P2 | Ben | I3 | 11 |
| P3 | Cara | I1 | 12 |
| P4 | Dev | I4 | 10 |
| P5 | Eli | I3 | 12 |
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
INSERT INTO PLAYER VALUES ("P6", "Fay", "I2", 11); - 2
UPDATE INSTRUMENT SET HireFee = 15.00 WHERE InstrumentID = "I4"; - 33 records are left; Cara and Eli (year 12) are deleted
Exam task: find and correct SQL errors
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
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);
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.
| Line | Error | Correction |
|---|---|---|
| 1 | DATABASE is one word | CREATE DATABASE COOKERY; |
| 4 | no comma before the next field | CourseCode VARCHAR(4) NOT NULL, |
| 5 | the field name must match the design | WorkshopDate DATE, |
| 10 | REFERENCES needs the table name | REFERENCES COURSE(CourseCode) |
A DML script: count the unpaid bookings of members called Lin
1SELECT SUM(WorkshopID) AS Unpaid 2FROM MEMBER, BOOKING 3WHERE MemberID = MemberID 4OR LastName = Lin AND Paid = FALSE;
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.
| Line | Error | Correction |
|---|---|---|
| 1 | SUM adds values; this needs a count | SELECT COUNT(WorkshopID) AS Unpaid |
| 3 | MemberID is in both tables | WHERE MEMBER.MemberID = BOOKING.MemberID |
| 4 | two errors: OR should be AND, and the text Lin needs quotes | AND LastName = "Lin" AND Paid = FALSE; |
| Instrument | Name | Family | Hire |
|---|---|---|---|
| I1 | Violin | String | 12.00 |
| I2 | Cello | String | 18.00 |
| I3 | Flute | Woodwind | 10.00 |
| I4 | Trumpet | Brass | 14.00 |
| I5 | Clarinet | Woodwind | 11.00 |
This query should list the Brass instruments that cost more than 12.00, in name order. It has three errors.
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.
- 1line 3: Brass is text, so it needs quotes, "Brass"; line 3: both conditions must hold, so OR becomes AND; line 4: ORDER BY Name;
- 2Trumpet, 14.00