Multiple choiceQuestion 1 · Recall
Loading…
By the end you can write CREATE DATABASE and CREATE TABLE statements that use the
syllabus data types sensibly, and explain why each field needs a type at all.
Before any data goes in, someone has to decide what each field will hold. FirstName holds
text. Average holds a number that can have a decimal part. Enrolled holds a date.
That decision is the field's data type, and it is the DBMS's main defence against rubbish
data. Put 'Amara' into an INTEGER field and the DBMS refuses the row. You cannot store
half a date.
So a table definition is really a set of promises, and the DBMS enforces every one of them on every row, for ever.
A database is a container. A table lives inside one, so create the database first:
CREATE DATABASE School;
Then define the table inside it:
CREATE TABLE Student (
StudentID INTEGER PRIMARY KEY,
FirstName VARCHAR(30),
FeePaid BOOLEAN,
Average REAL,
Enrolled DATE
);
Read it in this order:
CREATE TABLE Student — make a table called Student.field name, then data type, then any extra rule such as PRIMARY KEY.Spelling and punctuation matter: an extra comma before the last bracket is a syntax error, and a missing comma between two fields is too.
You need to recognise these and choose between them.
| Type | Holds | Example value |
|---|---|---|
CHARACTER |
a fixed number of characters | 'AB' |
VARCHAR(n) |
up to n characters, variable length |
'Amara' |
BOOLEAN |
true or false | TRUE |
INTEGER |
a whole number | 42 |
REAL |
a number with a fractional part | 72.5 |
DATE |
a calendar date | '2026-10-29' |
TIME |
a time of day | '14:30:00' |
How to choose, in one line each:
VARCHAR(n). Reserve enough
characters, but not 500 "just in case".AB-1234) →
CHARACTER. The syllabus lists it as CHARACTER; most DBMS let you write CHARACTER(2)
or CHAR(2) to fix the length.BOOLEAN.INTEGER.REAL.DATE or TIME. Never store a date in a text field: you
could not then compare dates or sort them properly.PRIMARY KEY marks the field that uniquely identifies each row. StudentID is a good
choice; FirstName is not, because two students can share a name.
The primary key comes with two guarantees, enforced by the DBMS:
A table can have only one primary key, though that key can be made of more than one field. You write it on its own line when it is the last rule:
CREATE TABLE Booking (
StudentID INTEGER,
ClassID INTEGER,
PRIMARY KEY (StudentID, ClassID)
);
That is a composite key: the pair must be unique, so one student cannot book the same class twice, but may book many classes.
Worked example: Worked example: defining a library table
Write the DDL to create a database called Library and a table called Book with these
fields: a whole-number BookID that uniquely identifies a book, a title of up to 120
characters, an author of up to 60 characters, a Fiction flag, and the date it was added.