Tables, records and fields

A database is an organised, permanent store of data that can be searched, sorted and updated. The data sits in tables.

Table: Film

FilmIDTitleGenreYear
1Silver RiverDrama2011
2Paper CometFamily2019
3Quiet EngineDrama2004
  • A record is one row: everything stored about one film. This table has 3 records.
  • A field is one column: one piece of data stored for every record. This table has 4 fields.
  • Every field has a data type: integer, real, Boolean, character, string or date. Year is an integer; Title is a string.

Keys and linked tables

  • A primary key is a field whose value is different for every record, so it identifies each one. FilmID is the primary key above; Genre is not, because two films share Drama.
  • A relational database keeps data in separate tables linked by keys. A foreign key is a field in one table that holds the primary key of another.

Table: Customer

CustomerIDNameTown
C12MayaLeeds

Table: Sale

SaleIDCustomerIDItem
301C12Folder
302C12Glue

CustomerID is the primary key of Customer and a foreign key in Sale. Maya's town is stored once. If it were typed on every sale instead, that would be data redundancy (the same data stored more than once), and when she moved, one copy could be changed and another missed: data inconsistency. Linked tables remove both.

Records in a program

In a program, a record groups related fields, which can have different data types. A table of records can be held in a 2D array: one row per record, one column per field.

pupils = [["Ava", "10A", 54], ["Ben", "10B", 71], ["Cal", "10A", 62]]
print(pupils[1, 0])
print(pupils[2, 2])
pupils ← [["Ava", "10A", 54], ["Ben", "10B", 71], ["Cal", "10A", 62]]
OUTPUT pupils[1][0]
OUTPUT pupils[2][2]
pupils = [["Ava", "10A", 54], ["Ben", "10B", 71], ["Cal", "10A", 62]]
print(pupils[1][0])
print(pupils[2][2])

This prints Ben, then 62. The first index picks the record, the second the field, both counting from 0. A loop from 0 to length - 1 visits every record, just as a database query checks every row.

Find the keys

The primary key never repeats. The foreign key is the field that also appears in the other table.