KS48525 3.7 28 min read 10 question quiz 13 exam marks

Relational Databases and SQL

Tables, records, fields, primary and foreign keys, why splitting data across related tables removes whole categories of error, and every SQL statement the specification requires.

Relational database structure

A database is an organised, persistent store of data. A relational database stores data in linked tables.

TermMeaning
TableA set of data about one type of thing, such as Students or Books
RecordOne row of a table, describing one instance of that thing
FieldOne column of a table, holding one attribute
Primary keyA field whose value is unique for every record, identifying that record
Foreign keyA field in one table that holds the primary key of a record in another table, creating the link

Why data is split across tables

Suppose a library keeps everything in one table, with the borrower's name and address repeated on every loan.

Three problems follow immediately, and each has a name worth using:

  • Redundancy. The same address is stored dozens of times, wasting space.
  • Update anomalies. When a borrower moves, every one of those copies must be changed. Miss one and the database now holds two contradictory addresses with no way to tell which is right.
  • Insertion problems. A new borrower who has not yet taken a book out cannot be recorded at all, because there is no loan row to put them in.

Splitting the data into a Borrowers table and a Loans table solves all three. The address is stored exactly once, changing it is one edit, and a borrower can exist without any loans.

The Loans table then holds a foreign key, the borrower's ID, which links each loan back to exactly one borrower.

The one sentence justification

Storing each fact once and linking tables by key removes redundancy and makes inconsistent data impossible, because there is only one copy to change.

Tables, keys and the link between themA relational database drawn as separate tables. One table holds students, with a row for each student and a column for each field: StudentID, Name and Year. One field is chosen as the primary key, here StudentID, and its value must be different in every row and must never be reused, which is why a name makes a poor key and an ID number makes a good one. A second table holds courses, with CourseID as its own primary key. The two are joined by a third table of enrolments holding pairs of StudentID and CourseID, and in that table each of those fields is a foreign key, meaning a field that holds the primary key of another table. In the picture the enrolment row S01 and C01 points back at student S01 and course C01. Splitting the data this way is normalisation, and the reason for it is that every fact is then stored exactly once: when a course changes teacher you change one row in the courses table rather than three hundred rows in one enormous table, and there is no way for two of those rows to end up disagreeing.StudentsStudentIDNameYearS01Aisha KhanY10S02Tom ReillyY11S03Mia OkaforY10primary key: different in every rowCoursesCourseIDSubjectTeacherC01ComputingMr AliC02PhysicsMs DaleC03ArtMr Boydits own primary keyEnrolmentsStudentIDCourseIDS01C01S01C03S02C02foreign keyforeign keyAisha is stored once,even though shetakes two courses.Change a teacheronce, not on300 rows.12345
  1. One table for students. Each row is a student, each column a field.
  2. A primary key: one field whose value is different in every row.
  3. A second table for courses, with its own primary key.
  4. A foreign key in one table holds the primary key of the other.
  5. That link is why the data is stored once and not repeated.
Store every fact once. Almost every database exam answer comes back to that sentence.

SQL: retrieving data

SQL, Structured Query Language, is the language used to work with a relational database.

SELECT

SELECT firstName, surname
FROM Students
WHERE yearGroup = 11
ORDER BY surname ASC
  • SELECT lists the fields you want. SELECT * means every field.
  • FROM names the table.
  • WHERE filters which records are returned.
  • ORDER BY sorts the results, ASC for ascending and DESC for descending.

Conditions in WHERE

WHERE mark >= 70 AND yearGroup = 11
WHERE surname = 'Patel' OR surname = 'Khan'
WHERE title LIKE '%computing%'

LIKE with % as a wildcard matches part of a value, which is how you search for text containing something rather than exactly equal to it.

Joining two tables

SELECT Borrowers.surname, Loans.dueDate
FROM Borrowers, Loans
WHERE Borrowers.borrowerID = Loans.borrowerID

The condition matching the primary key to the foreign key is what performs the join. Leave it out and every borrower is paired with every loan, which is almost never what you want.

Text values need quotation marks, numbers do not

WHERE surname = 'Khan' but WHERE yearGroup = 11. Getting this wrong is a guaranteed lost mark.

An SQL query labelled clause by clause, and what each clause does to the tableAn SQL query is read clause by clause. SELECT name, mark chooses which columns. FROM results says which table. WHERE mark greater than 60 chooses which rows. ORDER BY mark DESC puts them in order, highest first. Applied to a table of five pupils, id, name and mark, WHERE drops Ben on 55 and Eli on 48 and keeps three rows. SELECT keeps only the name and mark columns. ORDER BY puts the result in order: Chloe 91, Aisha 72 and Dev 64.query.sqlSELECT name, markFROM resultsWHERE mark > 60ORDER BY mark DESC;which columnswhich tablewhich rowsin what order1The table: results2idnamemark1Aisha722Ben553Chloe914Dev645Eli48WHERE mark > 60 keeps 3 rows and drops 2The result3namemarkChloe91Aisha72Dev64only the two chosen columns,highest mark first
  1. Each clause has a job: SELECT picks columns, FROM names the table, WHERE picks rows, ORDER BY sorts.
  2. WHERE keeps the rows that meet the condition and drops the rest.
  3. The result has only the selected columns, in the order asked for.
Read a query in the order FROM, WHERE, SELECT, ORDER BY: pick the table, filter the rows, choose the columns, then sort.

SQL: changing data

INSERT

INSERT INTO Students(studentID, firstName, surname, yearGroup)
VALUES (4102, 'Amira', 'Hassan', 10)

The list of fields and the list of values must be in the same order and of matching types.

UPDATE

UPDATE Students
SET yearGroup = 11
WHERE yearGroup = 10

DELETE

DELETE FROM Students
WHERE studentID = 4102
Never write DELETE or UPDATE without WHERE

DELETE FROM Students deletes every record in the table. UPDATE Students SET yearGroup = 11 sets every student to year 11. Both statements are valid SQL and both run instantly, which is why the WHERE clause is the most important line in either.

Writing SQL in an exam

  1. Which table or tables hold the data. That is your FROM.
  2. Which records do you want. That is your WHERE.
  3. Which fields should appear. That is your SELECT.
  4. Does the order matter. That is your ORDER BY.

Answering in that order rather than left to right stops the most common error, which is selecting the right fields from the wrong table.

Key terms you must be able to define

Relational database
A database storing data in tables that are linked to one another by keys.
Table
A set of data about one type of thing, arranged in records and fields.
Record
One row of a table, describing a single instance.
Field
One column of a table, holding one attribute of every record.
Primary key
A field whose value uniquely identifies each record in a table.
Foreign key
A field holding the primary key of a record in another table, creating a link between them.
Redundancy
The same data being stored more than once, wasting space and risking inconsistency.
SQL
Structured Query Language, used to retrieve and modify data in a relational database.
Wildcard
A symbol such as % that stands for any sequence of characters in a LIKE comparison.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineRelational database
AnswerA database storing data in tables that are linked to one another by keys.
DefineTable
AnswerA set of data about one type of thing, arranged in records and fields.
DefineRecord
AnswerOne row of a table, describing a single instance.
DefineField
AnswerOne column of a table, holding one attribute of every record.
DefinePrimary key
AnswerA field whose value uniquely identifies each record in a table.
DefineForeign key
AnswerA field holding the primary key of a record in another table, creating a link between them.
DefineRedundancy
AnswerThe same data being stored more than once, wasting space and risking inconsistency.
DefineSQL
AnswerStructured Query Language, used to retrieve and modify data in a relational database.

Reach the top grade on this topic

Two things separate full marks here.

Justify table splitting with a named consequence. Not "it is tidier" but "the address is stored once, so it cannot become inconsistent when a borrower moves, and a borrower can exist before they have taken out any loans".

Write SQL that would actually run. Quotation marks round text, none round numbers, field names spelled exactly as the question gives them, and a WHERE clause on every UPDATE and DELETE. Examiners mark SQL strictly because a query that does not run does not retrieve anything.

Explain a foreign key as the mechanism, not the label. It holds the primary key of a record in another table, and matching the two in a WHERE clause is what joins them.

Mistakes that cost marks here

Avoid these
  • Putting quotation marks round numeric values, or leaving them off text values.
  • Forgetting the WHERE clause on an UPDATE or DELETE, which affects every record in the table.
  • Forgetting the join condition when selecting from two tables.
  • Saying a primary key is 'the first field'. It is the field whose value is unique for every record.
  • Confusing a record with a field. A record is a row, a field is a column.
Fun fact

SQL was designed at IBM in the 1970s to be readable by people who were not programmers, which is why it reads almost like English. That decision is the main reason it is still in daily use fifty years later.

Knowledge check

0 of 10 answered
1What is a primary key?
2What is a foreign key?
3Which SQL clause filters which records are returned?
4What does SELECT * mean?
5What is wrong with UPDATE Students SET yearGroup = 11?
6Which query returns all books with 'python' anywhere in the title?
7Why is customer data split into separate tables rather than stored in one?
8In SQL, which values need quotation marks?
9What happens if you select from two tables without a join condition?
10Which statement adds a new record to a table?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

13 marks
1State the difference between a primary key and a foreign key.2 marks
State

Mark scheme0 / 2
  • LA primary key uniquely identifies each record in its own table
  • LA foreign key holds the primary key of a record in another table, linking the two
Model answer

A primary key is a field whose value is unique for every record in its own table, so it identifies that record without ambiguity. A foreign key is a field in one table that holds the primary key value of a record in another table, which is what creates the link between the two tables.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2A Students table has the fields studentID, firstName, surname, yearGroup and tutorGroup. Write an SQL query to return the first name and surname of every student in year 11, sorted by surname.4 marks
Write

Mark scheme0 / 4
  • LSelects the correct two fields
  • LUses FROM Students
  • LFilters on yearGroup with no quotation marks round the number
  • LSorts by surname
Model answer

The query is: SELECT firstName, surname FROM Students WHERE yearGroup = 11 ORDER BY surname. The two field names appear after SELECT because only those columns are wanted, Students follows FROM because that is where the data is, the WHERE clause filters to year 11 with no quotation marks because the value is numeric, and ORDER BY surname sorts the results alphabetically, which is ascending by default.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain why a library database stores borrower details in a separate table from loans, rather than repeating them on every loan record.4 marks
Explain

Mark scheme0 / 4
  • LRepeating the details would store the same data many times, which is redundancy
  • LWasted storage is one cost
  • LIf a detail changes it would have to be corrected in every copy
  • LMissing one copy would leave the database inconsistent, with no way to tell which version is right
Model answer

Repeating the borrower's name and address on every loan record means storing the same facts dozens of times over, which wastes storage but, far more importantly, creates a maintenance problem. When a borrower moves house, every single copy of their address has to be found and changed. If one is missed the database then holds two different addresses for the same person with nothing to say which is correct, and any report using the data may be wrong. Storing the borrower once in its own table and linking each loan to it by a foreign key means each fact exists in exactly one place, so a change is a single edit and inconsistency is impossible. It also allows a borrower to be recorded before they have taken out any books, which a combined table could not do.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4Write an SQL statement to change the year group of the student whose studentID is 4102 to 11.3 marks
Write

Mark scheme0 / 3
  • LUses UPDATE on the correct table
  • LUses SET to change yearGroup to 11
  • LIncludes a WHERE clause identifying the single student
Model answer

The statement is: UPDATE Students SET yearGroup = 11 WHERE studentID = 4102. The WHERE clause is essential rather than optional here: without it the statement would set the year group of every student in the table to 11, and it would do so immediately with no confirmation.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 13