Databases
Why a relational database beats separate files, the words and keys of the relational model, E-R diagrams, normalisation to 3NF, what a DBMS does, and SQL for building, querying and changing tables.
What goes wrong with separate files
Separate files store the same data many times and go wrong; a relational database stores each fact once.
In a file-based approach, each department keeps its own file. Think of a school office and a library, each with its own list of students.
| Problem | What goes wrong |
|---|---|
| Data redundancy | data that several departments need is stored many times |
| Data inconsistency | one copy is changed and another is not, so the copies disagree |
| Data dependency | every program must know its file's layout, so changing the layout means rewriting programs |
| Access and questions | users cannot easily be shown only part of a file, and each new question needs a new program |
A relational database stores each fact once, in linked tables. So one update is enough.
The DBMS (database management system, the software that runs the database) also:
- keeps the structure apart from the programs (program-data independence)
- enforces integrity rules
- controls access for each user
- answers new questions with a query.
The words for the parts of a table
A table stores one kind of thing. Its rows are records (tuples) and its columns are fields (attributes).
An entity is a thing we store data about, such as a student. A table holds the data about one entity, in rows and columns. The STUDENT table holds every student.
| Everyday word | Relational word | What it is |
|---|---|---|
| record | tuple | one row: all the data about one student |
| field | attribute | one column: one item of data stored for every record |
Example:In STUDENT, one row is Nomin's record. The column StudentName is a field.
Remember:Exam answers may use either pair of words. The relational model uses tuple and attribute.
Keys: primary, candidate, secondary, composite
A key is a field that finds records. The primary key picks out each record uniquely.
| Key | What it is | Example |
|---|---|---|
| Primary key | the field, or fields, chosen to identify each record uniquely | StudentID |
| Candidate key | any field, or smallest set of fields, that could be the primary key | StudentID |
| Secondary key | a candidate key not chosen as the primary key, but still used to find records | |
| Composite key | a key with two or more fields | (StudentID, CourseCode) |
A candidate key's value is unique for every record that could ever exist, not just the rows shown.
Watch out:A person's name is never a candidate key. Two people can share a name.
An index on a field lets the DBMS find records by that field quickly, without reading every row. It works like the index at the back of a book.
Relationships and E-R diagrams
A foreign key links two tables. An E-R diagram draws the tables as boxes and the links as lines.
A foreign key is a field in one table that holds the primary key of another table. It links the two tables.
A relationship is one-to-one, one-to-many or many-to-many.
In an E-R diagram (entity-relationship diagram):
- each entity is a box
- a line joins two related entities
- a crow's foot marks the many end.
Remember:In a one-to-many relationship, the foreign key goes in the table on the many side. One tutor has many students, so TutorID goes in STUDENT.
A many-to-many relationship cannot be stored with a foreign key in either table. It is resolved with a link entity. Its composite primary key is the two foreign keys:
STUDENT M:N COURSEbecomesSTUDENT 1:M ENROLMENT M:1 COURSE.
TUTOR(TutorID, TutorName)
STUDENT(StudentID, StudentName, TutorID)
COURSE(CourseCode, CourseTitle)
ENROLMENT(StudentID, CourseCode, Mark)
Primary keys: TutorID, StudentID,
CourseCode, and (StudentID, CourseCode)
in ENROLMENT
Foreign keys: STUDENT.TutorID,
ENROLMENT.StudentID,
ENROLMENT.CourseCodeReferential integrity
Referential integrity means every foreign key points at a record that really exists.
Referential integrity means that every foreign-key value matches a primary-key value that exists in the linked table.
The DBMS enforces this rule:
- It refuses to add an enrolment for a student who does not exist.
- It refuses to delete a student who still has enrolments.
- The exception: it is told to delete those enrolments too. That is a cascading delete.
Example:You try to enrol student S99 on a course. There is no S99 in STUDENT, so the DBMS says no.
Remember:Without referential integrity, records could point at nothing.
Normalisation, step 1: first normal form
Normalisation splits data into tables so each fact is stored once. 1NF is the first step.
Normalisation is the process of organising data into tables so that each fact is stored once. That removes the update, delete and insert problems of a badly designed table.
A table is in first normal form (1NF) when:
- it has no repeating groups of attributes
- every field holds one atomic value (one value that cannot be split)
- it has a primary key.
To reach 1NF:
- Give each repeated item its own row.
- Copy the student's details into that row.
- Choose a key. Here the key becomes
(StudentID, CourseCode).
Watch out:The table still repeats facts. In 1NF, renaming CS101 means changing 3 rows.
0NF STUDENT_COURSES(StudentID,
StudentName, TutorID, TutorName,
{CourseCode, CourseTitle, Mark})
1NF ENROLMENT_1NF(StudentID, CourseCode,
StudentName, TutorID, TutorName,
CourseTitle, Mark)
key: (StudentID, CourseCode)Step 2: second normal form
In 2NF, every non-key field depends on the whole key, not on part of it.
A table is in second normal form (2NF) when:
- it is in 1NF, and
- every non-key attribute (a field that is not part of the key) depends on the whole primary key.
A non-key attribute that depends on only part of a composite key is a partial dependency. Move it into a table of its own, with that part of the key as its key.
Remember:So 2NF can only fail when the key is composite.
Example:The key is (StudentID, CourseCode). StudentName, TutorID and TutorName depend on StudentID alone. CourseTitle depends on CourseCode alone. Only Mark needs both parts of the key.
So the 1NF table splits into STUDENT, COURSE and ENROLMENT, shown below.
STUDENT(StudentID, StudentName,
TutorID, TutorName)
COURSE(CourseCode, CourseTitle)
ENROLMENT(StudentID, CourseCode, Mark)Step 3: third normal form, and how to explain it
In 3NF, no non-key field depends on another non-key field: the key, the whole key, and nothing but the key.
A table is in third normal form (3NF) when:
- it is in 2NF, and
- no non-key attribute depends on another non-key attribute.
That is a non-key dependency, also called a transitive dependency.
Example:In STUDENT, TutorName depends on TutorID, which is not the key. So TUTOR(TutorID, TutorName) is split off. TutorID stays in STUDENT as a foreign key.
To explain whether tables are in 3NF, check each table and name the attributes:
| If an attribute... | it breaks |
|---|---|
| is in a repeating group | 1NF |
| depends on part of the key | 2NF |
| depends on a non-key attribute | 3NF |
Remember:In short: the key, the whole key, and nothing but the key.
TUTOR(TutorID, TutorName)
STUDENT(StudentID, StudentName, TutorID)
COURSE(CourseCode, CourseTitle)
ENROLMENT(StudentID, CourseCode, Mark)What the DBMS does for you
The DBMS is the software that runs the database: it describes, designs, protects and answers questions about the data.
A database management system (DBMS) is the software that manages the database.
| Feature | What it does |
|---|---|
| Data dictionary | keeps data about the data: table and field names, data types, keys, validation rules and relationships |
| Data modelling and the logical schema | holds the design of the tables and relationships, not tied to one DBMS, often drawn as an E-R diagram |
| Data integrity | protects it with validation and referential integrity |
| Data security | access rights for each user or group, and regular backups |
| Developer interface | lets developers build items such as tables, forms and reports |
| Query processor | checks and runs each query, and returns the results |
Example:A teacher can see marks but not change fees. That is an access right.
SQL DDL: building the structure
SQL's DDL builds the structure of a database: the database, its tables, their fields and keys.
The DBMS uses two kinds of statement. SQL is the industry standard for both.
| DDL (Data Definition Language) | DML (Data Manipulation Language) | |
|---|---|---|
| What it does | creates and changes the structure of a database | runs queries and changes the data |
The DDL you need:
| Statement | What it does |
|---|---|
CREATE DATABASE | makes a new database |
CREATE TABLE | makes a table, with fields of type CHARACTER, VARCHAR(n), BOOLEAN, INTEGER, REAL, DATE or TIME |
ALTER TABLE | changes a table, for example to add a field or a foreign key |
PRIMARY KEY (field) | sets the primary key |
FOREIGN KEY (field) REFERENCES Table(Field) | sets a foreign key |
Remember:Choose each type by meaning. An ID like S01 is a VARCHAR, and a single letter is a CHARACTER.
CREATE DATABASE School;
CREATE TABLE TUTOR (
TutorID VARCHAR(2),
TutorName VARCHAR(30),
PRIMARY KEY (TutorID)
);
CREATE TABLE STUDENT (
StudentID VARCHAR(3),
StudentName VARCHAR(40),
DateOfBirth DATE,
FormGroup CHARACTER,
TutorID VARCHAR(2),
PRIMARY KEY (StudentID),
FOREIGN KEY (TutorID)
REFERENCES TUTOR(TutorID)
);
ALTER TABLE STUDENT
ADD Email VARCHAR(50);SQL DML: asking questions with SELECT
A SELECT query asks the database a question: which fields, from which table, which rows, in what order.
| Clause | What it does |
|---|---|
SELECT | lists the fields to show |
FROM | names the table |
WHERE | keeps only the rows that match |
ORDER BY | sorts the result: ASC is the default, and DESC reverses it |
GROUP BY | makes one result row for each value; used with COUNT, SUM or AVG |
AS | gives a result column a name, as in AVG(Mark) AS AverageMark |
INNER JOIN ... ON | joins two tables where their key values match |
Example:The first query below lists each student's name and mark for CS101, highest mark first.
Exam:Exam questions use at most two tables. With two tables, write every field as TABLE.Field.
SELECT STUDENT.StudentName,
ENROLMENT.Mark
FROM STUDENT
INNER JOIN ENROLMENT
ON STUDENT.StudentID =
ENROLMENT.StudentID
WHERE ENROLMENT.CourseCode = 'CS101'
ORDER BY ENROLMENT.Mark DESC;
SELECT CourseCode,
COUNT(StudentID) AS Entries,
AVG(Mark) AS AverageMark
FROM ENROLMENT
GROUP BY CourseCode;SQL DML: changing data
INSERT adds records, UPDATE changes them and DELETE removes them. WHERE says which records.
| Statement | What it does |
|---|---|
INSERT INTO | adds a record; list the fields when you do not give a value for every one |
UPDATE ... SET ... WHERE | changes fields in the records that match |
DELETE FROM ... WHERE | removes the records that match |
Watch out:Forget the WHERE, and UPDATE or DELETE acts on every record. On the starting data, UPDATE without its WHERE sets all 6 marks to 60.
The DBMS still enforces referential integrity. It refuses to delete S02 from STUDENT while ENROLMENT still refers to S02.
The SELECT at the end shows ENROLMENT after the three changes.
INSERT INTO STUDENT
(StudentID, StudentName, TutorID)
VALUES ('S04', 'Nomin Ganbat', 'T2');
UPDATE ENROLMENT
SET Mark = 60
WHERE StudentID = 'S02'
AND CourseCode = 'CS101';
DELETE FROM ENROLMENT
WHERE StudentID = 'S01'
AND CourseCode = 'MA201';
SELECT StudentID, CourseCode, Mark
FROM ENROLMENT;- ProductID
- ProductName
- Category
- Price
- Stock
- CustomerID
- FirstName
- LastName
- Town
- JoinDate
- SaleID
- CustomerID
- ProductID
- Quantity
- SaleDate
TASKList the ProductName and Price of every product in the Input category.
KEY TERMS
CHECK YOURSELF
1.In a table, a non-key field depends on another non-key field. Which normal form does that dependency break?
2.CREATE TABLE is an example of:
3.What does referential integrity prevent?
4.A table in 1NF has the single-field primary key StudentID. What can you say about 2NF?
5.TUTOR to STUDENT is one-to-many. Where does the foreign key go?
6.In the key tester, FirstName and LastName together are unique in the four rows shown. Are they a candidate key?
7.What does UPDATE ENROLMENT SET Mark = 60; do (with no WHERE clause)?