AS & A Level Computer Science · Area 1 · AS Level content

Database concepts, DBMS and SQL

A file-based system duplicates data and ties every program to one file layout, so the examinable core of this topic is the pair: the limitation, and the relational feature that removes it. You then have to use the terminology precisely, read and draw an E-R diagram, and take a table that is not normalised through 1NF, 2NF and 3NF while naming the dependency that fails at each stage. Marks are lost by saying a table is 'not normalised' without naming the attribute and what it depends on, by writing SQL that mixes up DDL and DML, and by leaving WHERE off an UPDATE or DELETE.

Not started

Syllabus coverage

  • Limitations of using a file-based approach for the storage and retrieval of data
  • Features of a relational database that address the limitations of a file-based approach
  • Terminology: entity, table, record, field, tuple, attribute, primary key, candidate key, secondary key, foreign key, relationship, referential integrity, indexing
  • Relationships: one-to-many, one-to-one and many-to-many
  • Use of an entity-relationship (E-R) diagram to document a database design
  • The normalisation process: First Normal Form (1NF), Second Normal Form (2NF) and Third Normal Form (3NF)
  • Explaining why a given set of database tables is, or is not, in 3NF
  • Producing a normalised database design from a description, a given set of data or a given set of tables
  • DBMS features that address the issues of a file-based approach: data management including maintaining a data dictionary, data modelling, logical schema, data integrity
  • DBMS software tools used in practice: data security including backup procedures and access rights for individuals or groups of users, the developer interface, the query processor
  • The DBMS carries out all creation and modification of the database structure using its DDL, and all queries and maintenance of the data using its DML
  • SQL (Structured Query Language) is the industry standard for both DDL and DML
  • DDL: CREATE DATABASE, CREATE TABLE with data types CHARACTER, VARCHAR(n), BOOLEAN, INTEGER, REAL, DATE and TIME, ALTER TABLE, PRIMARY KEY (field), FOREIGN KEY (field) REFERENCES Table (Field)
  • DML: SELECT ... FROM, WHERE, ORDER BY, GROUP BY, INNER JOIN, SUM, COUNT, AVG, and INSERT INTO, DELETE FROM, UPDATE on at most two tables

Part of the AS & A Level Computer Science syllabus 9618.

Primary key and foreign keyStudent.StudentID uniquely names each row.Student.CourseID repeats a CourseID from Course.StudentIDS001S002S003NameAdaBoCyCourseIDC12C31C12CourseIDC12C31TitleBiologyPhysicsforeign keyprimary keyprimary keyforeign key
A primary key identifies each record in its own table; a foreign key holds the primary key of another table, and that link is the relationship.

Why storing data in separate files stops working

A file-based approach means each application keeps its own file or files of records, in whatever format that application was written to expect. The exams office has a pupil file, the library has a borrower file, the catering system has an account file, and each was set up on its own. It works while the systems are small and separate, and then it stops working for reasons you should be able to list and explain.

The first is data redundancy: the same facts are stored many times over. A pupil's name, tutor group and address appear in the exams file, the library file and the catering file. Redundancy on its own wastes space, but the real damage is what follows from it. When the pupil moves house, somebody updates the address in the exams file and forgets the other two, and now the same pupil has two different addresses. That is data inconsistency, and it is the limitation that examiners most often ask you to explain. Redundancy is the cause, inconsistency is the consequence.

The second is program-data dependence. Each program contains code that knows the exact layout of its file: the length of each record, the offset at which each field starts, the order of the fields. Change the file - widen a surname field, add a field, reorder them - and every program that reads that file has to be rewritten and retested. There is also no way to ask a new question of the data without writing another program, so a report that the head of year wants today takes a programming request and a week. There is no ad hoc querying.

The third group covers security, sharing and control. Access is granted to a whole file, so any program that can open the pupil file can read and change every field in it - there is no way to let the catering staff see names but not medical notes. Two users can open and update the same file at the same time, and the last one to save overwrites the other's change, so updates are lost. There is no transaction control: if a program fails halfway through writing, the file is left half-updated with no way to roll back. Validation rules have to be repeated in every program, and nothing stops a new program bypassing them. Finally there is no shared data dictionary, so one file calls the field Surname, another Last_Name and a third FamName, in different formats and lengths.

LimitationWhat it means in practice
Data redundancyThe same facts are stored in several files, so space is wasted and updates have to be repeated.
Data inconsistencyDifferent files hold different versions of the same fact because only one copy was updated.
Program-data dependenceEvery program is written round one file layout, so changing the layout means rewriting the programs.
No ad hoc queriesA new report needs a new program, so answering a new question is slow and expensive.
Weak securityAccess is granted to the whole file, so a user who may see one field can see them all.
No concurrent update controlTwo users editing at once overwrite each other, and a half-finished update cannot be rolled back.
No central integrity or validationRules are duplicated in each program and can be bypassed by a new one.
No data dictionary or standardsDifferent files use different names, formats and lengths for the same field.
Never leave a limitation as a single word. Write the cause and the effect together: redundancy leads to inconsistency when an update is made to one copy and not the others.

What a relational database does differently

A relational database stores all of an organisation's data in one place as a set of tables (also called relations), and a database management system (DBMS) controls every read and write. Data is held once, in one table, and everything else refers to it. That single change removes the cause of most file-based problems: if a pupil's address exists in exactly one record, then updating that record cannot leave the address inconsistent anywhere else.

Duplication is designed out using keys instead of copied text. An order does not store the customer's name, address and town; it stores the CustomerID, and the customer's details live once in the Customer table. When the customer moves, one field changes and every order still points at the right customer. Where a copy of a value is unavoidable - a foreign key repeats values by definition - the DBMS enforces referential integrity so the copies can never point at something that does not exist.

Control moves from the program to the DBMS. Integrity rules are declared once, in the database, so every application is subject to them. Access rights are granted per user or group and can be limited to individual tables or even columns, so catering staff can be given read access to names and nothing else. The DBMS handles concurrent access with locking and transactions, so an update either completes fully or is rolled back. It also takes the backups and provides recovery from them.

Two further features matter for the exam. A data dictionary holds the description of the data - field names, types, sizes, validation rules, keys, relationships - so all programs share one definition. And indexing keeps the data quick to search as it grows: an index is a separate structure that lets the DBMS jump to the records it needs instead of reading the table from the start. Finally, users can ask new questions directly in SQL, without any new program being written, which is what makes ad hoc reporting possible.

  • Redundancy is removed by storing each fact once and referring to it with a key.
  • Inconsistency is prevented because there is only one copy to update.
  • Program-data dependence goes because programs address tables and fields by name, not by byte offsets, and the DBMS maps names to storage.
  • No ad hoc queries is solved by SQL: a new question is a new query, not a new program.
  • Weak security is solved by access rights per user or group, down to column level.
  • Concurrent update problems are solved by transaction control and locking, with rollback if an update fails.
  • No central integrity is solved because validation and key rules are declared once in the database.
  • No data dictionary is solved because the DBMS maintains one, and it is the single definition all programs use.
A strong answer pairs each relational feature with the exact file-based limitation it removes; a list of features with no limitation attached gains little credit.

The terminology you must use precisely

An entity is a thing in the real world that the database needs to hold data about - a student, a book, an order. A table is the implementation of one entity: a set of rows, all with the same structure. The distinction is worth stating clearly, because an E-R diagram is drawn in entities and a physical design is written in tables. The same word 'entity' is also used for the type, while one occurrence of it - one student - is an instance.

Within a table, one row is a record, also called a tuple. One column is a field, also called an attribute. So a record is one complete set of values about one instance, and a field is one property of the entity, with a name and a data type that apply to every record. The words are interchangeable pairs: record and tuple, field and attribute, table and relation. Use whichever the question uses, and do not mix them within one answer.

A primary key is a field, or the smallest set of fields, that uniquely identifies each record in a table. It must be unique and it must never be null, and each table has exactly one. A candidate key is any field or set of fields that could serve as the primary key because it is unique and not null - StudentID, an email address, a national insurance number. One candidate key is chosen as the primary key and the rest remain candidate keys. A composite key is a primary key made of two or more fields together, which is needed in a table that resolves a many-to-many relationship.

A secondary key is a field used to search or sort the table that is not unique - Surname, Town, DateOfBirth. It cannot identify a record on its own, so it is not a candidate key, but it is the field queries will filter on, and the DBMS may build an index on it to make those searches fast. A foreign key is a field in one table that holds the value of the primary key of another table, and it is how a relationship is implemented. Unlike a primary key, a foreign key may repeat and may be null.

TermMeaningExample in a school database
EntityA real-world thing the database holds data aboutStudent, Course
Table (relation)The implementation of one entity: rows with the same fieldsStudent
Record (tuple)One row: all the values about one instance(S1042, Okafor, 2009-04-11, 11B)
Field (attribute)One column: one property, with a name and a data typeSurname
Primary keyField or minimal set of fields that uniquely identifies a record; unique and not nullStudentID
Candidate keyAny field or set of fields that could be the primary keyStudentID, SchoolEmail
Secondary keyA non-unique field used for searching or sortingSurname
Foreign keyA field holding the primary key value of another tableCourseCode in Student
Composite keyA primary key made of two or more fields together(StudentID, CourseCode) in Enrolment
The candidate/secondary distinction is a favourite one-mark question: a candidate key is unique and could be the primary key, whereas a secondary key is not unique and exists to be searched on.

Foreign keys, relationships and referential integrity

Every relationship between two entities is one of three types, and the type decides where the foreign key goes. In a one-to-many relationship, one record in the first table is linked to many in the second, but each record in the second is linked to only one in the first: one customer places many orders, one tutor supervises many students, one course contains many enrolments. The foreign key always goes into the table on the many side, so CustomerID sits in Orders and repeats once per order. Putting it the other way round would need a list of orders inside a single customer record, which a relational table cannot hold.

In a one-to-one relationship, one record in each table is linked to exactly one in the other: an employee and the company car allocated to them, a student and their locker. The foreign key can go in either table, but it is usually placed in the table that is optional or less important, and it must be declared unique so that no two records can point at the same record. In an many-to-many relationship, many records in each table link to many in the other: students take many courses, and each course is taken by many students. This cannot be implemented directly, because either table would need to hold a list of values. It is resolved with a third table, sometimes called a junction or linking table, which has a foreign key to each of the two tables and a composite primary key made of both, plus any attributes that belong to the pairing itself, such as the enrolment date or the grade.

Referential integrity is the rule that every foreign key value must match an existing primary key value in the referenced table, or be null. It is enforced by the DBMS, not by the application, and it protects the links between tables from both directions. You cannot insert an order for a customer who does not exist, and you cannot change a foreign key to a value that is not in the parent table. You also cannot delete a customer who still has orders, because those orders would be left pointing at nothing - the DBMS refuses the delete unless the relationship has been set up to cascade the change or to set the foreign keys to null. If a customer's CustomerID changes, every referencing order must change with it.

RelationshipExampleWhere the foreign key goes
One-to-many (1:M)One customer places many orders; each order belongs to one customerIn the many side: CustomerID in Orders
One-to-one (1:1)One employee is allocated one company carIn either table, declared unique, usually the optional side
Many-to-many (M:N)Many students take many coursesNowhere directly: a junction table Enrolment(StudentID, CourseCode) holds both foreign keys, which together form the primary key
If a question gives you two tables and asks how the relationship is implemented, the marks are for naming the foreign key, the table it sits in and the primary key it references - state all three.

Documenting a design with an entity-relationship diagram

An entity-relationship (E-R) diagram is the design document you produce before any tables exist. It shows the entities the system must hold, the relationships between them and how many records at each end take part. The conventions are simple: an entity is a rectangle labelled with a singular noun (Customer, not Customers), a relationship is a line joining two entities labelled with a verb or verb phrase (places, is allocated, enrols on), and the cardinality is written at each end of the line - 1 or M - showing how many records at that end may be involved.

Attributes are usually shown as a list inside the entity box, with the primary key underlined. That underline is not decoration: it is how the diagram records which field identifies the entity, and it is what lets the diagram be turned into tables. If you draw attributes as separate ovals, underline the primary key oval and connect the rest to their entity.

The diagram earns its keep because it converts to a design by three rules. Each entity becomes a table, with its attributes as fields and its underlined attribute as the primary key. Each 1:M relationship becomes a foreign key in the table on the many side - the key of the one side. Each M:N relationship becomes a new table containing the primary keys of both entities as foreign keys, and those two fields together become its composite primary key. A 1:1 relationship becomes a foreign key in one of the tables, declared unique.

A library shows all of this at once. The entities are Member, Copy and Loan; the relationships are that a member takes many copies over time and a copy is taken many times, which is many-to-many, so Loan is the junction table holding MemberID, CopyNo, DateTaken and DateReturned. Book is a separate entity from Copy, because one title has many physical copies. Read the diagram one line at a time and say out loud what the cardinality means - 'one member, many loans' - and errors become obvious.

E-R elementHow it is drawnWhat it becomes in the design
EntityRectangle, singular nounA table
AttributeListed in the entity box or drawn as an oval; primary key underlinedA field; the underlined one is the primary key
RelationshipLabelled line or diamond between two entitiesA foreign key, or a junction table if M:N
Cardinality 1:M1 at the one end, M at the many endForeign key in the M-side table, referencing the 1-side primary key
Cardinality M:NM at both endsA new junction table with both primary keys as a composite key
Cardinality 1:11 at both endsForeign key in one table, declared unique
Examiners award E-R marks for entities, cardinality at both ends and the keys - not for neat drawing. A labelled box with 1 and M written in the right places scores more than a beautiful diagram with no cardinality.

Normalisation: 1NF, 2NF and 3NF

Normalisation is the step-by-step restructuring of tables so that each fact is stored once. Its purpose is to remove the update anomalies that redundancy causes: with a well-normalised design you cannot update one copy and leave another wrong, cannot insert a record without inventing unrelated data, and cannot lose data by deleting a record. There are three stages, and each one assumes the one before it: a table cannot be in 2NF unless it is already in 1NF.

First Normal Form (1NF) forbids repeating groups and multi-valued fields. Every field must hold a single atomic value, and there must be no repeating columns such as Course1, Course2 and Course3, and no field holding a list such as 'Smith, Jones'. The fix is to put one value in each field and add a row for each additional value, so a student taking three courses becomes three rows. A table in 1NF is also expected to have a primary key, which will often be composite.

Second Normal Form (2NF) requires 1NF plus no partial dependency: every non-key field must depend on the whole primary key, not on part of it. This can only go wrong when the key is composite. Take Enrolment(StudentID, CourseCode, StudentName, CourseTitle, Grade) keyed on (StudentID, CourseCode). Grade depends on both fields, which is correct. StudentName depends on StudentID alone, and CourseTitle on CourseCode alone, so both are partial dependencies and the table is only in 1NF. Splitting them out gives Student(StudentID, StudentName), Course(CourseCode, CourseTitle) and Enrolment(StudentID, CourseCode, Grade), which is 2NF.

Third Normal Form (3NF) requires 2NF plus no transitive dependency: no non-key field may depend on another non-key field. Suppose each course has one tutor, so Course becomes Course(CourseCode, CourseTitle, TutorID) and the tutor's name is added as TutorName. TutorName depends on TutorID, and TutorID is not the key, so TutorName is only indirectly dependent on the key - a transitive dependency - and the table is not in 3NF. Removing TutorName into Tutor(TutorID, TutorName) leaves Course(CourseCode, CourseTitle, TutorID), which is 3NF. The test in one sentence: every non-key field depends on the key, the whole key and nothing but the key.

Normal formTest it must passTypical fault it removes
1NFEvery field holds one atomic value; no repeating groups or lists; a primary key existsCourse1, Course2, Course3 columns; 'Smith, Jones' in one field
2NF1NF, and every non-key field depends on the whole primary keyStudentName depending on StudentID alone in a table keyed on (StudentID, CourseCode)
3NF2NF, and no non-key field depends on another non-key fieldTutorName depending on TutorID, where TutorID is not the key
When asked why a table is not in 3NF, name three things: the field, the field it actually depends on, and the fact that this is not the primary key. 'It has repeated data' scores nothing.

The DBMS: what it does, and the tools inside it

A database management system (DBMS) is the software layer that sits between the users and applications on one side and the stored data on the other. Nothing touches the files directly: every request goes through the DBMS, which is what allows it to enforce rules and control access. The syllabus names four features it provides, and each one answers a file-based problem.

Data management, including maintaining a data dictionary. The data dictionary - sometimes called the system catalogue - is the DBMS's own store of metadata: the description of the data rather than the data. For every table it records the field names, data types, sizes, validation rules, which field is the primary key, which are foreign keys and what they reference, plus who owns the table and who may access it. Programs and users consult it rather than hard-coding a layout, which is what removes program-data dependence.

Data modelling is the DBMS's support for describing the data independently of how it will be stored: entities, attributes, relationships and constraints, expressed in the E-R diagram and then in the tables. The logical schema is the result - the DBMS's view of the structure: which tables exist, their fields and types, their keys, the relationships between them and the integrity constraints. It says nothing about where the records physically sit on disk, which files or cylinders they occupy or how they are indexed; that is the physical schema, and the DBMS is free to change it without altering the logical schema. That separation is what makes it possible to reorganise storage without rewriting programs.

Data integrity is enforced centrally, in three parts. Entity integrity means the primary key is unique and never null. Referential integrity means every foreign key matches an existing primary key or is null. Domain integrity means each value is of the right type, length and range for its field. Because the DBMS applies these rules to every user and every program, no application can bypass them.

The tools you are expected to know about are the practical face of these features. Data security is handled by access rights granted to individuals or groups - typically roles such as read, insert, update, delete and alter - so a clerk can add orders but not drop a table, and by backup procedures: regular full backups plus more frequent incremental ones, copies held off site, the transaction log kept so completed transactions can be replayed, and restores tested rather than assumed. The developer interface is the console or graphical tool in which the developer writes and tests SQL, creates tables, inspects the data dictionary and sets permissions. The query processor is the component that takes a submitted SQL statement, parses it, checks it against the data dictionary for valid table and field names, works out an efficient way to execute it - using an index where one exists - runs it and returns the result set.

DBMS feature or toolWhat it providesFile-based problem it removes
Data management and data dictionaryA single central store of metadata: names, types, sizes, validation, keys, relationships, access rightsDifferent files using different names and formats for the same field
Data modellingA description of entities, attributes and relationships before any storage decisionData structures buried inside individual programs
Logical schemaThe DBMS's view of tables, fields, types, keys and constraints, independent of physical storagePrograms breaking when the file layout changes
Data integrityEntity, referential and domain rules applied to every user and programValidation duplicated in each program and easily bypassed
Access rightsPermissions granted to individuals or groups, down to table or column levelWhole-file access with no way to hide fields
Backup proceduresScheduled full and incremental backups, off-site copies, transaction log, tested restoresNo recovery if a file is corrupted or a program fails mid-update
Developer interfaceConsole or GUI to create objects, write and test SQL, inspect the catalogue, set permissionsChanges made by writing and recompiling a program
Query processorParses, validates, optimises and executes SQL, returning the result setEvery new question needing a new program
Do not describe the logical schema as 'the design on paper': in an exam answer it is the DBMS's own description of tables, keys and constraints, held independently of physical storage.

DDL: creating the structure, choosing data types and declaring keys

The DBMS keeps two languages apart. Its Data Definition Language (DDL) is used for all creation and modification of the structure: making a database, making and altering tables, declaring fields and data types, and declaring keys and relationships. The DBMS records everything a DDL statement defines in its data dictionary, which is why the structure can be enforced afterwards. Its Data Manipulation Language (DML) is used for all queries and for the maintenance of the data inside those tables. The industry standard for both is SQL, Structured Query Language, which is why a query written for one relational DBMS will usually run, perhaps with small changes, on another.

The DDL statements in the syllabus are a small, fixed set, and you should be able to read any of them and write them from a description. CREATE DATABASE makes an empty database. CREATE TABLE defines a table by listing each field with its data type, and optionally declaring the primary key and any foreign keys. ALTER TABLE changes a definition that already exists: it can add a field, change a field's type, or add a primary key or foreign key to a table that was created without one.

Choosing a data type is a decision about which values are legal, so a mark is usually available for the type and for the reason. A price is REAL because it has a fractional part; a quantity in stock is INTEGER because it is a whole number; whether a book has been returned is BOOLEAN because there are only two possible values; a date of birth is DATE because it will be compared and sorted as a date, not as text. A surname is VARCHAR(30) because names vary in length and 30 characters is enough, whereas a single-character grade is CHARACTER(1) because every grade is exactly one character. Text that will be searched belongs in a text type even when it looks numeric: a phone number stored as INTEGER loses its leading zero and cannot hold spaces.

Keys are part of the definition. A primary key can be declared inline after the field, or on its own line as PRIMARY KEY (CustomerID), which is the only way to declare a composite key such as PRIMARY KEY (StudentID, CourseCode). A foreign key must be declared separately, because it has to name the table and field it references: FOREIGN KEY (CustomerID) REFERENCES Customer (CustomerID). The order matters - the referenced table and its primary key must already exist before another table can point at them - and the data types on both sides of a foreign key must match. Read any CREATE TABLE statement field by field and you can say exactly what it enforces: the data type of each field, which field identifies a record, and which field must match a record in another table.

  • CREATE DATABASE School; makes a new, empty database called School.
  • CREATE TABLE Customer (CustomerID INTEGER, Surname VARCHAR(30), PRIMARY KEY (CustomerID)); creates a table with two fields and declares the primary key.
  • ALTER TABLE Customer ADD COLUMN Email VARCHAR(60); adds a field to a table that already exists.
  • ALTER TABLE Orders ADD PRIMARY KEY (OrderID); adds a primary key to a table created without one.
  • ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customer (CustomerID); adds a foreign key linking Orders to Customer.
Data typeHoldsUse it for
CHARACTER(n)Exactly n characters, padded with spaces if shorterOne-character grade, two-letter country code, fixed-length code
VARCHAR(n)Up to n characters, storing only what is enteredSurname, town, email address, phone number
BOOLEANTRUE or FALSEHasPaid, IsReturned, IsActive
INTEGERWhole numbers, positive or negativeCustomerID, QuantityInStock, NumberOfDoors
REALNumbers with a fractional partPrice, Total, Mass, Temperature
DATEA calendar dateDateOfBirth, OrderDate
TIMEA time of dayStartTime, TimeOfArrival
DDL changes the shape of the database and DML changes what is inside it; if a statement mentions a data type, a key, or a table being created or altered, it is DDL.

DML: querying and maintaining the data

DML covers everything done to the data once the tables exist: retrieving it with SELECT, adding records with INSERT INTO, changing them with UPDATE and removing them with DELETE FROM. SQL is a declarative language: you state which records and fields you want, and the query processor works out how to fetch them. That is why the same statement can run against a table of ten records or ten million without being rewritten.

A SELECT statement is built from clauses, and it helps to know both the order you write them in and the order they take effect. You write SELECT, then FROM, then WHERE, then GROUP BY, then ORDER BY. Logically the DBMS first takes the tables in FROM and joins them, then filters rows with WHERE, then groups the surviving rows with GROUP BY, then works out the fields and aggregates in SELECT, and finally sorts the result with ORDER BY - which is why ORDER BY can sort on a value that WHERE could never filter on.

The three aggregates you need are SUM, COUNT and AVG. Used without GROUP BY they summarise the whole table: SELECT COUNT(*) FROM Orders returns one number. Used with GROUP BY they summarise each group: SELECT CustomerID, COUNT(OrderID) FROM Orders GROUP BY CustomerID returns one row per customer. The rule that catches students out is that every field in the SELECT list that is not inside an aggregate must appear in the GROUP BY clause, because otherwise the DBMS would not know which of the group's values to show.

INNER JOIN combines rows from two tables where a condition matches, and returns only the rows that match in both. The condition is almost always foreign key equals primary key: FROM Customer INNER JOIN Orders ON Customer.CustomerID = Orders.CustomerID. Because both tables may share a field name, qualify the field with the table name. A customer with no orders simply does not appear in the result, which is the difference between an inner join and an outer join - and outer joins are outside this syllabus.

The maintenance statements are short and easy to lose marks on. INSERT INTO names the table and the fields, then gives the values in the same order. UPDATE names the table, SET gives the new values, and WHERE chooses the records. DELETE FROM names the table and WHERE chooses the records. In UPDATE and DELETE the WHERE clause is not optional in practice: leave it out and every record in the table is changed or deleted. That single omission is the most expensive mistake in this topic.

Clause or statementWhat it does
SELECT ... FROMChooses which fields and which tables appear in the result
WHEREFilters individual records before any grouping; comparisons, AND, OR, NOT
GROUP BYCollects records with the same value into one row per group, for use with SUM, COUNT and AVG
ORDER BYSorts the result, ASC by default or DESC; applied last
INNER JOIN ... ONCombines two tables, keeping only rows where the join condition is true
SUM / COUNT / AVGTotals a numeric field, counts records, averages a numeric field
INSERT INTO ... VALUESAdds a new record
UPDATE ... SET ... WHEREChanges values in existing records
DELETE FROM ... WHERERemoves records
Write the WHERE clause before you write the SELECT list on any UPDATE or DELETE, and check it names the key of exactly the records you mean to touch.

Key terms you must be able to define

Entity
A real-world thing that the database holds data about, such as a student or an order. One occurrence of an entity is an instance, and one record in a table.
Table (relation)
The implementation of one entity: a set of records with the same fields. Each column is a field and each row is a record.
Record (tuple)
One complete row of a table, holding all the values about one instance of the entity.
Field (attribute)
One column of a table: a single property of the entity, with a name and one data type that applies to every record.
Primary key
The field, or smallest set of fields, that uniquely identifies each record in a table. It must be unique and never null, and each table has exactly one.
Candidate key
Any field or set of fields that is unique and not null, and so could have been chosen as the primary key, such as StudentID or an email address.
Secondary key
A field used for searching or sorting that is not unique, such as Surname. It cannot identify a record on its own, but an index may be built on it.
Foreign key
A field in one table that holds the value of the primary key of another table, which is how a relationship is implemented. It may repeat and it may be null.
Composite key
A primary key made up of two or more fields together, used where no single field is unique - for example (StudentID, CourseCode) in an enrolment table.
Referential integrity
The rule that every foreign key value must match an existing primary key value in the referenced table, or be null. The DBMS enforces it, so links between tables cannot point at records that do not exist.
Indexing
The use of a separate structure that lets the DBMS locate records without reading the whole table, so searches and joins on the indexed field are much faster.
Normalisation
The step-by-step restructuring of tables into 1NF, 2NF and 3NF so that each fact is stored once, removing redundancy and the update anomalies it causes.
Data dictionary
The DBMS's store of metadata: for every table it records field names, data types, sizes, validation rules, keys, relationships and access rights.
Logical schema
The DBMS's description of the database structure - tables, fields, data types, keys, relationships and constraints - independent of how the data is physically stored.

Applied to real systems

9618 sets its questions inside systems you already use - a phone, a school network, a supermarket till, a website, a bank. These show how to apply the theory to a context you have not seen before, then you write your own.

SQLite in a smartphone app

SQLite is a relational DBMS that is built into the app rather than run as a separate server, and it keeps a whole database in a single file on the device. A messaging app uses it for the message history: one table for contacts, one for conversations and one for messages, with the messages table holding a foreign key to the conversation. It shows that the relational model and SQL are not limited to large servers, and that a DBMS can be small enough to ship inside an application while still providing keys, indexes and queries.

Moodle with MySQL: a many-to-many relationship in a real system

Moodle is an open-source virtual learning environment, and it stores its data in a relational database such as MySQL. Users and courses have a many-to-many relationship, because a student takes many courses and a course has many students, so the design needs a linking table - the enrolment table - holding a foreign key to the user and a foreign key to the course. That table carries the attributes that belong to the pairing itself, such as the date of enrolment and the role taken. The same database enforces referential integrity, so an enrolment cannot refer to a course that has been deleted, and access rights distinguish a student, a teacher and an administrator.

A library lending system: 1:M and M:N together

A library database separates Book from Copy, because one title has many physical copies, and each copy has its own barcode and condition. Member to Copy is many-to-many over time, since a member borrows many copies and a copy is borrowed many times, so a Loan table holds MemberID, CopyNo, DateTaken and DateReturned with a composite primary key. Referential integrity is visible in everyday rules: a member record cannot be deleted while loans are outstanding, and a loan cannot name a copy that is not in stock. The design is in 3NF because the member's address is stored once in Member, not repeated in every loan.

Oracle Database in a bank: transactions, access rights and backups

A bank's account records are held in a commercial relational DBMS such as Oracle Database, which provides the transaction control, access rights and backup facilities described in this topic. A transfer between two accounts must either complete both updates or make neither, so the DBMS commits the whole transaction or rolls it back. Staff are given access rights by role: a cashier can insert transactions but cannot alter the table definitions, and no clerk can read every customer's record. Backups run on a schedule with the transaction log kept so that completed transactions can be reapplied after a failure.

Flashcards

Click a card to flip it. Mark honestly — the tracker uses this.

Q1What is referential integrity, and who enforces it?
The rule that every foreign key value must match an existing primary key value in the referenced table, or be null. The DBMS enforces it, so you cannot insert a record pointing at a parent that does not exist, and you cannot delete a parent that still has children pointing at it.
Q2Candidate key or secondary key?
A candidate key is unique and not null, so it could have been the primary key - StudentID, an email address. A secondary key is not unique and exists to be searched or sorted on - Surname, Town - and may have an index built on it.
Q3What must a table satisfy to be in 1NF?
Every field must hold a single atomic value: no repeating groups such as Course1, Course2, Course3, and no list inside one field. A student taking three courses becomes three rows, and the table needs a primary key, often composite.
Q4What must a table satisfy to be in 2NF?
It must be in 1NF, and every non-key field must depend on the whole primary key, not just part of it. This can only fail where the key is composite - for example StudentName depending on StudentID alone in a table keyed on (StudentID, CourseCode).
Q5What must a table satisfy to be in 3NF?
It must be in 2NF, and no non-key field may depend on another non-key field. A field that depends on a non-key field is only transitively dependent on the key, which 3NF forbids: TutorName depending on TutorID in a Course table.
Q6Where does the foreign key go in a one-to-many relationship?
In the table on the many side. One customer places many orders, so CustomerID is a foreign key in Orders, repeating once per order and referencing Customer(CustomerID). The one side cannot hold it, because a single record cannot hold a list of orders.
Q7How is a many-to-many relationship implemented?
With a third table - a junction or linking table - that has a foreign key to each of the two tables. Those two foreign keys together form its composite primary key, and any attributes of the pairing itself, such as a date or a grade, are fields in that table.
Q8What does DDL do, and which statements belong to it?
DDL creates and modifies the structure: CREATE DATABASE, CREATE TABLE with data types, ALTER TABLE, and the declaration of PRIMARY KEY and FOREIGN KEY. The DBMS records every DDL definition in its data dictionary.
Q9What does DML do, and which statements belong to it?
DML queries and maintains the data inside the tables: SELECT with FROM, WHERE, GROUP BY and ORDER BY, INNER JOIN and the aggregates SUM, COUNT and AVG, plus INSERT INTO, UPDATE and DELETE FROM.
Q10Which data type would you choose for a price, a yes/no flag and a date of birth?
A price is REAL, because it has a fractional part. A yes/no flag is BOOLEAN, because there are only two possible values. A date of birth is DATE, so it can be compared and sorted as a date rather than as text.
Q11What does an INNER JOIN return?
Only the rows where the join condition is true in both tables. The condition normally matches a foreign key to a primary key, as in ON Customer.CustomerID = Orders.CustomerID, so a customer with no orders does not appear at all.
Q12What does the data dictionary hold?
Metadata - the description of the data, not the data itself: for every table, the field names, data types, sizes, validation rules, primary and foreign keys, relationships, ownership and access rights. It is why programs can address fields by name instead of by file layout.
0 of 12 marked as known

Exam-style questions

8 questions, 31 marks. Write your answer, then reveal the mark scheme and tick each point you actually made. Answering honestly here is what makes the rest of the site useful.

StateAO11 mark
State the name given to the field, or smallest set of fields, that uniquely identifies each record in a table.

Mark scheme — tick each point you actually made

Examiner tip: One mark, one term. Do not add a description or offer 'candidate key' as well - the candidate keys are the fields that could have been chosen, and only one of them is the primary key.
DefineAO12 marks
Define the terms primary key and foreign key as they are used in a relational database.

Mark scheme — tick each point you actually made

Examiner tip: Uniqueness earns the first mark and the reference to another table's primary key earns the second. Saying a foreign key is 'a key from another table' without saying it holds that table's primary key value is too loose for the mark.
ExplainAO23 marks
A school keeps pupil data in three separate files: one for the exams office, one for the library and one for the catering system. Explain one limitation of this file-based approach.

Mark scheme — tick each point you actually made

Examiner tip: Name the limitation, then follow it through to its effect. Redundancy on its own is a label; redundancy leading to inconsistency is the explanation the marks are for.
DescribeAO14 marks
Describe two features of a relational database that overcome limitations of a file-based approach.

Mark scheme — tick each point you actually made

Examiner tip: Each feature needs both halves: what the feature is and which limitation it removes. Two features with no limitation attached may score nothing, and three features described vaguely will not beat two described fully.
AnalyseAO24 marks
An orders table has the fields OrderID, OrderDate, CustomerID, CustomerName, CustomerTown and Total, with OrderID as the primary key. Analyse why this table is not in Third Normal Form, and write the tables that would put the design in 3NF.

Mark scheme — tick each point you actually made

Examiner tip: The diagnosis and the design are separately marked, so write both even if you are unsure. 'It has repeated data' scores nothing: the mark is for naming the field that is out of place and the field it actually depends on.
WriteAO25 marks
The Customer table has CustomerID (INTEGER) as its primary key. Write the SQL DDL to create an Orders table with the fields OrderID (INTEGER), OrderDate (DATE), CustomerID (INTEGER) and Total (REAL), including the primary key and a foreign key to Customer.

Mark scheme — tick each point you actually made

Examiner tip: Copy the pattern exactly as the syllabus writes it: FOREIGN KEY (field) REFERENCES Table (Field). Missing brackets, a missing referenced field, or a foreign key whose data type does not match the primary key it references all cost marks.
WriteAO26 marks
The Customer table has the fields CustomerID, Surname and Town, and the Orders table has the fields OrderID, CustomerID, OrderDate and Total. Write an SQL statement for each of the following. (a) List the surname and town of every customer who lives in Leeds, in alphabetical order of surname. (b) For each customer, show the customer ID, the number of orders placed and the total value of those orders.

Mark scheme — tick each point you actually made

Examiner tip: In (b) every field in the SELECT list outside an aggregate must appear in GROUP BY. Writing ORDER BY Surname in (a) earns the sort mark, but writing ORDER BY without naming the field does not.
DiscussAO26 marks
A hospital stores its patient records in a database managed by a DBMS. Discuss how the use of access rights and of backup procedures helps the hospital to protect its data.

Mark scheme — tick each point you actually made

Examiner tip: Six marks need six distinct points, and the strongest answers cover both tools evenly. A list of 'it is more secure' and 'backups are good' scores nothing; each point must say what the tool does and what it prevents.

Exam technique for this topic

  • Answer file-based questions as cause and effect pairs. 'Data redundancy' alone is a label; 'the same address is stored in three files, so updating one leaves the other two wrong and the data is inconsistent' is the mark. Learn four pairs cold: redundancy to inconsistency, program-data dependence to rewriting programs, no ad hoc querying to slow new reports, file-level access to poor security.
  • For normalisation, never write 'it is not normalised' or 'it has repeated data'. Write the dependency: name the field that is out of place, name the field it actually depends on, and state that this is not the primary key. Then write the new tables with their keys, because the second half of the marks is for the design, not the diagnosis.
  • Keep DDL and DML apart by asking what the statement changes. If it creates or alters a table, a field, a data type or a key, it is DDL and it is recorded in the data dictionary. If it selects, inserts, updates or deletes records, it is DML. A question that asks for a query wants DML only, even though the tables had to be built with DDL first.
  • In any SQL answer, check three things before you move on: every non-aggregate field in SELECT appears in GROUP BY; an INNER JOIN has an ON condition linking a foreign key to a primary key; and every UPDATE or DELETE has a WHERE clause naming the key. Those three checks cover most of the marks lost on this topic.
  • When a question says 'at most two tables', do not write a three-table join to be helpful - it cannot be marked against the scheme. If you need data from a third table, the question expects you to assume it is already in one of the two you were given.

Why students lose marks here

A student wroteA student wrote: 'A foreign key is a field that is unique to each record, and it goes in the table on the one side of a one-to-many relationship.'
Why it loses marksBoth halves are wrong. Uniqueness is the job of the primary key; a foreign key deliberately repeats, because the many side holds the same customer ID on every order that customer places. And the foreign key belongs on the many side, not the one side, because the one side would otherwise have to hold a list of orders in a single record.
The answer that scoresA foreign key is a field in one table that holds the value of the primary key of another table, so it is how the relationship is implemented. It may repeat and it may be null, so it is not unique. In a one-to-many relationship such as one customer placing many orders, the foreign key CustomerID sits in the Orders table, the many side, and repeats once for each order that customer places. In a many-to-many relationship there is no single place for it: a junction table is created holding both foreign keys, and those two fields together form its composite primary key.
A student wroteA student wrote: 'The table is not in 3NF because it contains repeated data and duplicate rows.'
Why it loses marksRepeated data is a description of redundancy, not of a dependency, and duplicate rows would breach the primary key rather than 3NF. The mark is for identifying which non-key field depends on which other non-key field. The words 'duplicate' and 'repeated' tell the examiner nothing about normal forms.
The answer that scoresThe table is in 2NF but not in 3NF because it contains a transitive dependency. CustomerName and CustomerTown both depend on CustomerID, and CustomerID is not the primary key, so they depend on the key only indirectly. To reach 3NF, the customer details move into their own table, Customer(CustomerID, CustomerName, CustomerTown) with CustomerID as the primary key, and Order becomes Order(OrderID, OrderDate, Total, CustomerID) with CustomerID as a foreign key referencing Customer. Each fact is then stored once, so changing a customer's town means changing one field.
A student wroteA student answered an UPDATE question with: 'UPDATE Customer SET Town = "Bradford";'
Why it loses marksThere is no WHERE clause, so the statement changes the town to Bradford for every customer in the table. The marks are for the WHERE clause that limits the change to the intended records, and the statement as written would destroy the data. Double quotes are also wrong for a text value in SQL.
The answer that scoresThe statement must name the records to be changed: UPDATE Customer SET Town = 'Bradford' WHERE CustomerID = 51; The WHERE clause identifies the single record by its primary key, so only that customer moves. Exactly the same rule applies to DELETE FROM Customer WHERE CustomerID = 51;, and to a query, where omitting WHERE returns every record instead of the ones asked for.
A student wroteA student wrote: 'DDL is used to insert and update the data, and DML is used to create the tables.'
Why it loses marksThe two are the wrong way round. DDL defines the structure and DML works on the data inside it, so swapping them loses the mark in every question that mentions either. A student who has this backwards cannot answer a question about which statements a DBMS records in its data dictionary.
The answer that scoresDDL, the Data Definition Language, is used for all creation and modification of the structure: CREATE DATABASE, CREATE TABLE, ALTER TABLE, and the declaration of data types, primary keys and foreign keys. The DBMS records these definitions in its data dictionary. DML, the Data Manipulation Language, is used for all queries and maintenance of the data: SELECT, INSERT INTO, UPDATE and DELETE FROM. Both are written in SQL, which is the industry standard for each.
A student wroteA student wrote: 'SELECT CustomerID, Surname, COUNT(OrderID) FROM Orders GROUP BY CustomerID;'
Why it loses marksSurname is in the SELECT list but not in the GROUP BY clause and is not inside an aggregate, so the DBMS has no single value it could show for a group of several orders. The statement is invalid, and even if it ran it would not answer the question, because Surname is not in the Orders table at all.
The answer that scoresEvery field in the SELECT list that is not inside an aggregate must appear in the GROUP BY clause: SELECT CustomerID, COUNT(OrderID) FROM Orders GROUP BY CustomerID; If the surname is genuinely needed, it has to be brought in from the Customer table with an INNER JOIN on CustomerID, and it still cannot be shown alongside a count of orders unless the grouping is by customer and the query returns one row per customer. The safe check is to compare the SELECT list with the GROUP BY list before writing anything else.
A student wroteA student wrote: 'A file-based approach is worse than a database because it is slower and takes up more space on the disk.'
Why it loses marksSpeed and disk space are not the examinable limitations, and neither is explained. The syllabus limitations are about redundancy and inconsistency, dependence of programs on file layout, the absence of ad hoc querying, weak security, uncontrolled concurrent access and the lack of central integrity rules. A vague comparison earns nothing.
The answer that scoresIn a file-based approach the same data is duplicated across separate files owned by separate applications, so an update made to one copy leaves the others holding a different version and the data becomes inconsistent. Each program is written round the exact layout of its file, so widening a field means rewriting every program that reads it. There is no way to ask a new question without writing a new program, access is granted to a whole file rather than to individual fields, and nothing centrally prevents two users overwriting each other's changes or a program bypassing the validation rules.