Flat Files, Relational Databases and Keys

UNIT 2 • MODULE 3 • LESSON 11

A mas band in Port of Spain starts taking costume orders in a spreadsheet: one row per order, with the masquerader’s name, phone, section and price typed in every time. By January there are 3,000 rows, the same person’s phone number appears in three different forms, and nobody is sure what the Sailor section costs because its only order was deleted. This lesson explains why systems like this outgrow a single flat file, and how a relational database and its keys fix the problem.

What you will learn

  • What a flat file is and the problems it causes as data grows.
  • The update, insertion and deletion anomalies.
  • What a relational database is: tables, records, fields and relationships.
  • The examples of database platforms named in the syllabus: MySQL and SQL Server.
  • Primary, candidate, foreign and secondary keys, marked on a real schema.

Part 1: Flat files

A flat file stores all the data in one table or one text file, one record per line, with no links to other files. In Text Files in C: Saving, Loading and Appending Data you wrote exactly this kind of file in C. Here is the mas band’s order file written and read back the same way:

#include <stdio.h>
#include <string.h>

int main(void)
{
    const char *rows[] = {
    "1001,Kerry-Ann,868-555-0142,Jewel,M",
    "1002,Marcus,868-555-0199,Sailor,L",
    "1003,Kerry-Ann,868-555-0142,Wings,M",
    "1004,Kerry-Ann,868-555-0142,Jewel,S"
    };
    char line[80];
    int i, hits = 0;
    FILE *f = tmpfile();
    if (f == NULL)
        return 1;
    for (i = 0; i < 4; i++)
        fprintf(f, "%s\n", rows[i]);
    rewind(f);
    while (fgets(line, sizeof line, f)) {
        printf("%s", line);
        if (strstr(line, "Kerry-Ann"))
            hits++;
    }
    fclose(f);
    printf("Rows to change for a new");
    printf(" phone: %d\n", hits);
    return 0;
}

Output:

1001,Kerry-Ann,868-555-0142,Jewel,M
1002,Marcus,868-555-0199,Sailor,L
1003,Kerry-Ann,868-555-0142,Wings,M
1004,Kerry-Ann,868-555-0142,Jewel,S
Rows to change for a new phone: 3

Flat files are simple and fine for small, single-purpose data, such as a high-score list. As a system grows, they cause problems:

  • Redundancy: the same facts (Kerry-Ann’s phone, the Jewel price) are stored many times, wasting space.
  • Inconsistency: copies get out of step when only some are changed.
  • Poor sharing and security: every program that uses the file must know its exact layout, and you cannot easily let one user see only some fields.
  • Hard to query: answering a new question means writing a new program to read the whole file.

The three anomalies

AnomalyWhat goes wrong
UpdateA fact stored in many rows must be changed in all of them; miss one and the data contradicts itself.
InsertionYou cannot record one fact without another: a new section cannot be added until somebody orders it.
DeletionDeleting one fact removes another: cancelling the only Sailor order loses the Sailor price.

Try it 1Flat file or relational?

Do the same three jobs in each layout: give Kerry-Ann a new phone (868-555-0300), cancel order 1002, and add a new section. Watch what goes wrong.

Part 2: Relational databases

A relational database stores data in several tables (relations). Each table holds one kind of thing: masqueraders, sections, orders. Each row (record or tuple) is one item, and each column (field or attribute) is one property. Tables are linked through shared key values, so each fact is stored once.

Masquerader(MasID, FirstName,
  LastName, Phone, Email)
Section(SectionCode, SectionName,
  Price)
CostumeOrder(OrderNo, MasID*,
  SectionCode*, Size, OrderDate)

Primary keys come first in each.
* = foreign key
Masquerader 1 ----< CostumeOrder
                       >---- 1 Section
(one masquerader, many orders;
 one section, many orders)

If you have met entity-relationship diagrams, this schema is exactly what an ER diagram with three entities and two one-to-many relationships turns into. For a recap, see Unit 2 • Module 2 • Lesson 06 – Entity-Relationship Diagrams and User-Interface Design.

Database management systems

A database management system (DBMS) is the software that stores the tables, enforces the keys and rules, controls who can see what, handles many users at once, makes backups and runs queries. The syllabus names two widely used relational DBMSs as examples:

  • MySQL: free and open source, very common behind websites and web applications.
  • Microsoft SQL Server: a commercial DBMS widely used by businesses and governments, especially with other Microsoft software.

Both use SQL, the language you will write in the next lesson. Microsoft Access is a smaller desktop database that also understands SQL.

Flat fileRelational database
StructureOne table or fileMany linked tables
RedundancyHigh: facts repeatedLow: each fact stored once
ConsistencyEasily brokenKept by keys and rules
QueriesNew program for each questionSQL queries on demand
Multi-user and securityWeakBuilt into the DBMS
Set-upVery simpleNeeds design and a DBMS

Part 3: Keys

KeyMeaningIn the mas band schema
Candidate keyAny field (or set of fields) whose value is unique for every row and could identify itIn Masquerader: MasID, Email, and Phone (if no two people share a phone)
Primary keyThe candidate key chosen as the main identifier: unique, never empty, rarely changesMasID, SectionCode, OrderNo
Foreign keyA field in one table that holds the primary key of another, creating the linkMasID and SectionCode in CostumeOrder
Secondary keyA field that is not unique but is indexed so records can be searched or sorted by it quicklyLastName in Masquerader; OrderDate in CostumeOrder

Why choose MasID rather than Email as the primary key? Email addresses change and some people do not have one; a made-up ID never needs to change. The other candidate keys are sometimes called alternate keys.

A foreign key must match a primary key value that exists (referential integrity): the DBMS refuses an order for MasID M09 if there is no masquerader M09.

Try it 2Mark the keys

Using the mas band schema, choose the best description of each field. Ten items.

Part 4: Common mistakes

  • Foreign key "is unique". It is unique in its home table, but in the linking table the same MasID appears on many orders.
  • Secondary key = second primary key. A secondary key is for searching and need not be unique.
  • Candidate and primary are different fields. The primary key is one of the candidate keys.
  • Listing problems without anomalies. Name the anomaly and give an example from the data.

Try it 3Keys and anomalies drill

Pick a mode. "Key" names the key type. "Anomaly" names the anomaly.

Summary

IdeaRemember
Flat fileOne table; simple; redundancy and anomalies as it grows.
AnomaliesUpdate, insertion, deletion.
Relational databaseLinked tables; each fact once; managed by a DBMS such as MySQL or SQL Server.
Primary keyChosen unique identifier.
Candidate keyAny field that could be the primary key.
Foreign keyCopy of another table’s primary key; makes the link.
Secondary keyNon-unique field indexed for searching.

Review questions

1. What is a flat file?

Show answer

A file that stores all the data in a single table or list of records, with no links to other tables.

2. Give three disadvantages of a flat file for a large system.

Show answer

Data redundancy; inconsistency from update anomalies; insertion and deletion anomalies; hard to query and share; weak security.

3. Using an example, explain a deletion anomaly.

Show answer

In the flat order file, deleting the only Sailor order also deletes the only record of the Sailor price.

4. Define primary key and foreign key.

Show answer

Primary key: the field chosen to uniquely identify each record in a table. Foreign key: a field in one table that refers to the primary key of another table.

5. Distinguish between a candidate key and a secondary key.

Show answer

A candidate key is unique and could identify each record. A secondary key is not necessarily unique and is used to search or sort records.

6. Name two relational DBMSs and say what a DBMS does.

Show answer

MySQL and Microsoft SQL Server. A DBMS stores and manages the tables, enforces keys and rules, controls access, supports many users and runs queries.

7. Why is a made-up ID often better than a phone number as a primary key?

Show answer

Phone numbers change, can be shared or missing; an ID is guaranteed unique and never needs to change.

8. In Try it 1, how many changes did a new phone number need in each layout?

Show answer

Three rows in the flat file; one row in the relational Masquerader table.

Homework

  1. Design a relational schema for a school library: books, members and loans. Mark every primary and foreign key.
  2. For your library, write one example of each anomaly that would happen if loans were kept in a flat file.
  3. Extend flat.c so the user types a name and the program counts that person’s rows.
  4. Find out which DBMS a website or app you use runs on (many say so on their careers or about page).

Mastery quiz: Flat Files, Relational Databases and Keys

This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

Mastery quiz: Flat Files, Relational Databases and Keys

Your course badges: loading saved progress…

View badges

    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

    Saved in this browser on this device. Clearing browser data may remove your badges.

    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

    1. Storing the same fact in many rows is called...
    2. Changing a phone number in only some rows causes...
    3. Being unable to add a section until it has an order is...
    4. A field that links to another table’s primary key is a...
    5. Which could be a candidate key for a student table?
    6. A non-unique field indexed for fast searching is a...
    7. Which is a relational DBMS named in the syllabus?
    8. In a relational database, data is stored in...
    9. Referential integrity means a foreign key value must...
    10. The primary key is chosen from the...

    Exam tips

    Key questions. When asked to identify keys in a schema, name the table as well as the field: "MasID is the primary key of Masquerader and a foreign key in CostumeOrder." A field name on its own is ambiguous, because the same field can be a different kind of key in each table.

    Flat file versus relational. Answers score best when they name a problem and illustrate it with data. Make up a two-row example if the question does not give one.

    The SQL part of Specimen Unit 2 Paper 02 (2021), Question 6, uses a schema with keys; Lesson 12 covers how to answer it. More worked answers are on the CS Solutions page.

    Previous: Unit 2 • Module 3 • Lesson 10 – Designing a Simple Network. Next: Unit 2 • Module 3 • Lesson 12 – Writing SQL and Connecting an Application to a Database.

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Operating Systems and Computer Networks (Unit 2, Module 3). Specific Objective 6: explain how data storage and retrieval have changed over time (flat files and their limitations; relational databases; platforms such as MySQL and SQL Server; primary, candidate, foreign and secondary keys).

    Video search terms

    Search YouTube for: "flat file vs relational database", "update insertion deletion anomaly", "primary foreign candidate key explained".

    Try it 4Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Updates

    2026/12/01

    - First version of the lesson.

    © 2026 islandclass.org

    Leave a Reply