Single-table databases and primary keys

Computer Science · Databases. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science topics

The idea

A database is an organised store of data. In a single-table database all the data is held in one table. Each column is a field: one item of data, such as a surname. Each row is a record: all the data about one person or thing.

When you define a table you give each field a name and a data type. You can also add validation, which checks that data being entered is sensible, for example a range check on an age.

Every table needs a primary key. This is a field whose value is different in every record, so it identifies exactly one record.

In simpler words

A database stores data in an organised way. A single-table database keeps everything in one table. Each column is a field, such as surname. Each row is a record, all the data about one thing. Each field has a data type. Validation checks the data makes sense. A primary key is a field that is different for every record.

An everyday comparison

A primary key is like a student's roll number. Many students can share a name, but every roll number is different, so it points to one student only. The comparison stops working because a primary key is a database field with a fixed data type, chosen when the table is designed.

Rules to remember

Common mistake

Students choose a name as the primary key. Two people can share a name, so it is not unique. Choose an ID or code field that is different for every record.

In the exam

Count fields as columns and records as rows, and give the numbers. For each field, state a suitable data type with a reason, such as text for phone numbers because they may start with 0. Name the primary key and explain that its values are unique in every record. Suggest a validation check by name, such as a range check, and say what it would check.

Worked example

A table PET stores, for each of 120 pets: PetID, Name, Species, Weight (for example 4.5) and Vaccinated (yes or no). Which field is the primary key, and which data types suit Weight and Vaccinated?

  1. Name and Species can repeat, so they cannot identify one pet. PetID is different for every pet.
  2. Weight has a decimal part, so it needs the real data type, not integer.
  3. Vaccinated has only two possible values, so Boolean fits.
  4. The table has 5 fields and 120 records.

Answer: Primary key: PetID. Weight: real. Vaccinated: Boolean.

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Arrays and file handlingStructured query language (SQL) →Take a Computer Science test