9.1 Databases

Question Bank · 20 Questions

Objectives: Students should be able to —

  • 1 Design and use single-table databases — fields, records and validation.
  • 2 Use the basic data types: text/alphanumeric, character, boolean, integer, real, date/time.
  • 3 Identify primary keys, give the reason for their choice and state their purpose.
  • 4 Write SQL scripts to query data stored in a single-table database.
  • 5 Distinguish between flat-file (single-table) and relational databases.
  • 6 Describe the role of a Database Management System (DBMS) and its components.
  • 7 Explain the purpose of field attributes — name, data type, size, format, validation rule.
  • 8 Describe different validation checks — presence, length, range, format, type, lookup, check digit.
  • 9 Construct SQL queries using SELECT, FROM, WHERE and ORDER BY.
  • 10 Use SQL aggregate functions SUM and COUNT.
  • 11 Understand the use of foreign keys to link tables in relational databases.
  • 12 Write SQL data manipulation statements: INSERT INTO, UPDATE, DELETE FROM.

Database Fundamentals: Definition, Types & DBMS

A database is a computerized record-keeping system.

It is an organized collection of data, that allows people to quickly search and extract information in a way that meets their need; edit and delete records using computer software.

The data can include text, numbers, pictures or anything that can be stored in a computer.

1) Single-table database (Flat database):

A simple database that stores all data in a single table in rows and columns.

It contains unrelated tables like a spreadsheet. It can be converted into a text file separating each field using delimiters like comma, hyphen, etc.

2) Relational database:

A computerized record-keeping system that contains two or more tables of data, interrelated through key fields called relationships.

Relational databases are very flexible for accessing, managing, and updating data.

3) Distributed database:

A relational database distributed over a computer network, allowing multiple users to access data simultaneously.

★ Advantages

  • Avoids data redundancy (duplication of data).
  • Increased data consistency (correctness) — allows only valid data defined by some rules.
  • Improved data access through use of host and query languages.
  • Improved data security through user credentials.
  • A database can be shared with many users over the network.

★ Disadvantages

  • Database systems are complex, difficult and time-consuming to design.
  • Extensive conversion costs in moving from a file-based system to a database system.
  • Initial training required for all programmers and users.
  1. To store information about people — like pupils at school, patients in a hospital, etc.
  2. To store information about things — like cars to be sold, books in a library, etc.
  3. To store information about events — like hotel bookings, results of races, etc.

(a) Database Management System (DBMS):

A DBMS is a set of programs that allows the creation of data files called tables and permits the ways to process, alter and extract records.

It provides the following features:

  • Allows the data to be stored by creating different tables which could be linked together.
  • Allows to search records which meet certain criteria (conditions) using a Query.
  • Allows editing and deletion of records.
  • Allows the alteration of structure of the table.
  • Allows import and export of data.
  • Allows to set security to access the data.

(b) Four main components of a DBMS:

★ Table: A data structure and the basic unit of storing data in a database. It stores related data in rows (records) with different pieces of information in columns (fields) of a record.

★ Form: A database object created for the user to enter, edit or display data from the data source table. It provides a user-friendly interface for a database application.

★ Query: A request used to extract data from a database according to the user's request. It uses Structured Query Language (SQL) that can be written or designed through query design grids.

★ Report: A database object used to display and print formatted data in an organized manner from the database table.

Tables, Records, Fields & Primary Key

(a) Record and Field:

Record: A basic data structure composed of different fields in a row. Each record is a single row in the table that contains different information about an item. A set of records makes a database table.

Field: The columns, or data categories of the same data type, used by each record. It represents an attribute (a characteristic or quality) of some entity (object, person, place, or event).

StudentID ↙ Key Field Forename Surname Date of Birth
6473PhilipBarker07/11/1995
6783SandipDosanjh12/07/1995
6777CynthiaFerguson03/01/1996
6788PhilipBarker07/11/1995
6789AnneRuth01/09/1995

Each row is a record; each column is a field. The whole grid is a table.

(b) Primary Key-field:

A primary key is a field in a table which uniquely identifies each record in a database table.

  • Primary keys must contain unique values.
  • A primary key column cannot have NULL values or be left empty.

(c) Purposes of primary key-field:

  • It serves as a unique identifier for a row of data in a database table.
  • It stops the possibility of duplicate data.
  • It helps to speed up queries, searches and sort requests.
  • It is used to establish relationships with other tables by linking the fields.
  1. Organize data of each individual or thing in rows, with each column containing data of the same data type.
  2. In table design view, name each field with its appropriate data type.
  3. Add validation check by specifying proper attributes like size (length of field), format, validation rule, etc.
  4. Identify the field which uniquely identifies each record and specify it as the primary key field.
  5. Save the table structure to store data later using datasheet view or form.

Field name: The names given to the columns in a table to identify the field. It is mandatory.

Field / Data type: Determines the type of data that a user can enter into the field. It validates and restricts invalid data types. Based on the data type, other properties of the fields are provided.

Field size: Specifies the required length or size of data. It helps to minimize the wastage of storage space.

Format: Specifies a unique format of data to be allowed and stored in a uniform way.

Input Mask: A string of characters that indicates the format of valid input values.

Validation Rule: Specifies the criteria or rule that should be met before storing data in the field.

Data Types & Coding Data

(a) Different data types used in a table:

Data type Description Example
TextAllows alphanumeric data — text, numbers and symbols.Name: James
Address: 73, High Street
Postcode: CV34 5TR
CharacterAllows only a single character of any alphanumeric data.Code: N / C / P
House: R / B / G / Y
IntegerAllows positive or negative whole numbers only.Age: 16
Quantity: 36
Temperature: -10
RealAllows positive or negative decimal numbers.Length (cm): 12.5
Weight (kg): 52.36
Temperature: -2.5
CurrencyAllows price with currency symbols and ensures two decimal places.Cost: $5.75
Amount: £468.25
Price: €18.75
Date/TimeChecks and allows only date and time in an appropriate format.Long: 20 Feb 2006 18:21:35
Short: 20/02/06 18:21
BooleanAllows only one of two choices.Paid: Yes / No
Option: True / False
Gender: Male / Female

(b) Two reasons why choosing the correct data type is important:

  1. To do a validation check over data while entering, to prevent invalid characters being stored.
  2. To check the correct format of data, like date and time, to be stored in a uniform way.

(c) Two reasons why setting the field size / max length is important:

  1. File size can be kept as small as possible.
  2. Time taken to process data can be kept minimum.

(a) Why coding data is useful:

  • Codes are quicker to type in.
  • Using codes reduces the size of the files.
  • Increases the speed of search and process performed on the data.
  • Codes are often unique and are easy to search.

(b) Three factors when designing codes:

  1. Code should always be of same length.
  2. Codes should contain enough detail and should not be too short.
  3. Codes should be easy to use.

Data Validation

(a) Data Validation:

Validation is an automatic computer check to ensure that the data entered is sensible, reasonable and consistent. Data is accepted only if it falls within the set rules.

Note: Validation does not check the accuracy of data — only that it is sensible.

(b) Validation checks:

Validation type How it works Example usage
Presence checkChecks that data has been entered into a field.Field which cannot be left blank like the primary key field.
Data-type checkEnsures that the correct type of data (text, number, date) is entered.Name (Text), Date of birth (Date), Age (Number), Price (Currency).
Length checkChecks that the data isn't too short or too long.A password which needs to be six letters long.
Format checkChecks that the data is in the right format.Passport number M5228907 — a letter followed by 7 digits.
Date format checkChecks that the date is in the right format.Date of birth in form 20 Jan 1998 or 20/01/1998.
Check digitThe last digit in a code (number) is used to check the other digits are correct.Bar codes use check digits at the right-most of the number.
List / LookupLooks up acceptable values in a list or table.There are only seven possible days of the week.
Range checkChecks that a value falls within a specified range.Number of hours worked must be > 0 and < 50.
Consistency / Cross-fieldChecks that different fields in the same record correspond correctly.If 'Mr' is in Title, 'Male' must be in Gender.
Spell checkLooks up words in a dictionary.When word processing.

Structured Query Language (SQL) — Querying Data

(a) SQL query:

SQL stands for Structured Query Language. It is a standard query language for writing scripts, to make requests to the database for the records which meet the criteria we specify.

An SQL script is a list of SQL commands that performs a given task, often stored in a file so the script can be reused.

(b) Benefits of using a query:

  1. View data only from the fields you are interested in viewing.
  2. Combine data from several data sources.
  3. Use expressions as fields.
  4. View records that meet criteria that you specify.

(c) Function of each SQL statement:

(i) SELECT — Fetches specified fields from the table; queries always begin with SELECT.

SELECT Field1, Field2, Field3   -- specifies individual fields
SELECT *                       -- specifies ALL fields

(ii) FROM — Identifies the table to use.

FROM TableName   -- specifies the table to use

(iii) WHERE — Includes only records in a query that match a given condition.

WHERE Condition   -- values must match the field's data type

(iv) ORDER BY — Sorts the results by a given column, alphabetically or numerically.

ORDER BY Field1, Field2                    -- ascending
ORDER BY Field1 DESC, Field2             -- first field descending, second ascending

Note: DESC specifies descending order only. To sort in ascending order, omit the keyword.

(v) SUM — Returns the sum of all values in a field. Used with SELECT.

SELECT SUM(Field)               -- sum of values in field (must be integer/real)
SELECT SUM(Field) AS ResultField  -- alias name is optional

(vi) COUNT — Counts the number of records where the field matches a condition. Used with SELECT.

SELECT COUNT(Field)               -- counts items matching criteria
SELECT COUNT(Field) AS ResultField -- alias name is optional

Method — How to create an SQL query:

  1. An SQL query always begins with SELECT followed by FROM commands — both are mandatory in an SQL script.
  2. All other commands are optional.
  3. Start the SQL script with the SELECT command line, identify and write the names of fields to display separated by a comma (,).
  4. Next specify the table name in the FROM command line.
  5. Write the criteria or condition in the WHERE command line.
  6. Specify the names of fields to sort in the ORDER BY command line.
  7. Put a semicolon (;) to mark the end of the SQL statement.

Examples of criteria / conditions for the WHERE clause:

Criteria Query result
= "Male" / Like "Male"Records where field exactly matches "Male".
Not "Apple" / Not Like "Apple"Records where field does NOT match "Apple".
Like "U*"Text begins with "U" (e.g. UK, USA). * is a wildcard.
"Apple" OR "Orange"Records matching either value.
= 100Records where field equals 100.
<> 100 / Not 100Records where field is not equal to 100.
> 50Records where field is greater than 50.
>= 50Greater than or equal to 50.
< 75Less than 75.
<= 75Less than or equal to 75.
20 OR 25Either 20 or 25.
>0 AND <50 / Between 0 and 50Within a range (exclusive of boundaries for AND, inclusive for Between).
< 50 OR > 100Outside the range 50 to 100.
Is NullNo value in the field.
Is Not NullValue is present (not missing).
"" (pair of quotes)Field set to blank (but not null).

Tick (✓) the appropriate column to show how to provide values in criteria for a field to filter records:

Field data type How to provide value
In quotes ("..." or '...') NOT in quotes
Text
Integer
Real
Boolean
Character
Date/Time
⚠ Important notes:
  • Date/Time values should be enclosed in hash (#) symbols — e.g. #06/01/2004# — not single or double quotes.
  • Boolean values are stored using binary digits 0 and 1, so they should NOT be enclosed in quotes either.

SQL Exam Practice — MARKS Table

StdID StdName Sex DOB Grade House Eng Dhi Math
2030ATHOOFM07-May-0410(B)Red708294
2031FAINAANM12-Apr-0410(A)Yellow687786
2033IYALAF10-Oct-0410(A)Green899295
2036MAIHAF13-Sep-0410(A)Red768290
2038SHAAILM08-Oct-0410(B)Orange547958
2039HASEENM14-Dec-0410(B)Blue466549
2043EENAASHF10-Oct-0410(A)Green576762
2238MAZEENAF16-May-0410(A)Orange496270
2053MAISHAF24-Jun-0410(B)Yellow627475
2072DHAAEEM31-Dec-0410(B)Blue505988

(a)(i) Records and fields:

Records: 10  ·  Fields: 9 (StdID, StdName, Sex, DOB, Grade, House, Eng, Dhi, Math)

(a)(ii) Primary key field and reason:

StdID — because the field contains unique data elements which can be used to identify each record (all data elements are different).

(b) Data type for each field:

FieldData type
StdIDInteger
StdNameText
SexBoolean (M/F)
DOBDate/Time
GradeText
EngInteger

(c) Display StdID, StdName, Sex in ascending order of name, grouped by sex (M first, F next), where Eng > 60:

SELECT StdID, StdName, Sex
FROM MARKS
WHERE Eng > 60
ORDER BY Sex DESC, StdName ;

Note: The field that has to be grouped should be sorted first. M sorts after F alphabetically, so DESC puts M first.

Output:

StdIDSexStdName
2030MATHOOF
2031MFAINAAN
2033FIYALA
2036FMAIHA
2053FMAISHA

(d) Display name and Math marks of all girls of Grade 10(A) in descending order of Math marks:

SELECT StdName, Math
FROM MARKS
WHERE Sex Like "F" AND Grade Like "10(A)"
ORDER BY Math DESC ;

(e) Display StdID, StdName, Grade in descending order of Dhi marks grouped by Grade, where Dhi < 45 OR Dhi >= 60:

SELECT StdID, StdName, Grade
FROM MARKS
WHERE Dhi < 45 OR Dhi >= 60
ORDER BY Grade, Dhi DESC ;

(f) Display StdID, StdName, Sex in descending order of Eng marks grouped by gender (F first, M next), where Eng between 60 and 75 (inclusive):

SELECT StdID, StdName, Sex
FROM MARKS
WHERE Eng >= 60 AND Eng <= 75
ORDER BY Sex, Eng DESC ;

Equivalent: WHERE Eng Between 60 and 75

(g) Display StdName only in descending order of Eng marks grouped by Grade, where Eng >= 50 OR Dhi > 60:

SELECT StdName
FROM MARKS
WHERE Eng >= 50 OR Dhi > 60
ORDER BY Grade, Eng DESC ;

(h) Display StdName and Grade where student has passed all three subjects with marks >= 60:

SELECT StdName, Grade
FROM MARKS
WHERE Eng >= 60 AND Dhi >= 60 AND Math >= 60 ;

(i) Display StdName and Grade where Math >= 85 AND (Eng >= 60 OR Dhi >= 60):

SELECT StdName, Grade
FROM MARKS
WHERE Math >= 85 AND (Eng >= 60 OR Dhi >= 60) ;

(j) Display StdID, StdName, Grade for students belonging to a House other than Orange:

SELECT StdID, StdName, Grade
FROM MARKS
WHERE House Not Like "Orange" ;

(k) Display StdID, StdName, Grade for students belonging to Red OR Blue house:

SELECT StdID, StdName, Grade
FROM MARKS
WHERE House Like "Red" OR House Like "Blue" ;

(l) Display StdName, Grade, DOB for students born between 1st June 2004 and 30th October 2004:

SELECT StdName, Grade, DOB
FROM MARKS
WHERE DOB >= #6/1/2004# AND DOB <= #10/30/2004# ;

Equivalent: WHERE DOB Between #6/1/2004# AND #10/30/2004#

(m) Display StdName, Sex, total mark (Eng+Dhi+Math) for Grade 10(A) students in highest-to-lowest order of total:

SELECT StdName, Sex, (Eng + Dhi + Math) AS TotalMark
FROM MARKS
WHERE Grade Like "10(A)"
ORDER BY (Eng + Dhi + Math) DESC ;

SQL Exam Practice — SALES Table (SUM & COUNT)

ItemNo OrderNo Notes Qty Amount Status
CH0011921Smith – six dining chairs64500Delivered
TB0031921Smith – large table23200In progress
CH0011924Hue – extra chairs43800Not started
CH0031925Easy chairs23600Cancelled
BN0011927Patel – replacement bench11350Not started
ST0021931Sola – small table12400Delivered
CH0031927Patel – eight dining chairs w/ arms89600In progress
TB0031927Pagel – large table13450Not started

(a) Why ItemNo could not be a primary key:

All fields contain repeated data elements (e.g. CH001 appears in rows 1 and 3; TB003 in rows 2 and 8). So no single field can uniquely identify each record, and none can be set as the primary key field.

(b) Total amount collected from Delivered items:

SELECT SUM(Amount) AS TotalAmt
FROM SALES
WHERE Status Like "Delivered" ;

Output:

TotalAmt
6900

(c) Count items "In progress":

SELECT COUNT(Status) AS NoItems
FROM SALES
WHERE Status Like "In progress" ;

Output:

NoItems
2

(d) Count items with Amount > 3500:

SELECT COUNT(Amount) AS NoItems
FROM SALES
WHERE Amount > 3500 ;

Output:

NoItems
4

Relational Databases & SQL Data Manipulation (Syllabus Extension)

A foreign key is a field (or group of fields) in one table that refers to the primary key of another table. It is used to link two tables together and establish a relationship between them.

Purpose:

  • Links records in one table to records in another table.
  • Allows data to be looked up across tables (avoiding data redundancy).
  • Enforces referential integrity — a foreign key value must either match an existing primary key in the linked table or be NULL.

Example: A school has two tables — STUDENT and HOUSE.

STUDENT table HOUSE table
StdID (PK) Name HouseID (FK) HouseID (PK) HouseName
6473PhilipH01H01Red
6783SandipH02H02Yellow
6777CynthiaH01H03Green

The HouseID field in STUDENT is a foreign key that points to the primary key HouseID in HOUSE. Each student's house can be looked up without repeating the house name in every student record.

The INSERT INTO statement is used to add new records (rows) to a table.

Syntax (specifying fields):

INSERT INTO TableName (Field1, Field2, Field3)
VALUES (Value1, Value2, Value3) ;

Syntax (all fields, in defined order):

INSERT INTO TableName
VALUES (Value1, Value2, Value3) ;

Example — add a new student to the MARKS table:

INSERT INTO MARKS (StdID, StdName, Sex, DOB, Grade, House, Eng, Dhi, Math)
VALUES (2088, "RASHID", "M", #03/15/2004#, "10(A)", "Green", 72, 85, 90) ;
⚠ Notes:
  • Text and Character values must be in single/double quotes.
  • Integer, Real and Boolean values are NOT in quotes.
  • Date/Time values must be in hash # symbols.
  • The order of values must match the order of fields listed.

The UPDATE statement is used to modify existing records in a table.

Syntax:

UPDATE TableName
SET Field1 = Value1, Field2 = Value2
WHERE Condition ;

Example 1 — change the house of student 6473 to "Blue":

UPDATE MARKS
SET House = "Blue"
WHERE StdID = 6473 ;

Example 2 — increase Math marks by 5 for all Grade 10(A) students:

UPDATE MARKS
SET Math = Math + 5
WHERE Grade Like "10(A)" ;
⚠ Critical: If you omit the WHERE clause, ALL records in the table will be updated — usually a serious mistake. Always include a WHERE clause unless you genuinely want to update every row.

The DELETE FROM statement is used to remove one or more existing records from a table.

Syntax:

DELETE FROM TableName
WHERE Condition ;

Example 1 — delete student record with StdID = 2039:

DELETE FROM MARKS
WHERE StdID = 2039 ;

Example 2 — delete all students with Eng < 50:

DELETE FROM MARKS
WHERE Eng < 50 ;
⚠ Critical: If you omit the WHERE clause, ALL records will be deleted — the table will become empty (only the structure remains). Always double-check the WHERE clause before running DELETE.

Summary — Data Manipulation vs Query:

SQL Statement Action Type
SELECTRead / fetch dataQuery (DQL)
INSERT INTOAdd new recordsManipulation (DML)
UPDATEModify existing recordsManipulation (DML)
DELETE FROMRemove recordsManipulation (DML)

Revision: Statements and Key Computing Terms

Statement Key Term
A computerized record-keeping system; an organized collection of data.Database
A database that stores all data in a single table.Single-table (Flat-file) database
A database with two or more tables interrelated through key fields.Relational database
A relational database distributed over a computer network.Distributed database
A set of programs that allows creation, alteration and extraction of records.DBMS (Database Management System)
The basic unit of storing data in a database — rows are records, columns are fields.Table
A single row of related data in a table.Record
A column representing one attribute / data category in a table.Field
A field that uniquely identifies each record in a table.Primary key
A field in one table that refers to the primary key of another table.Foreign key
Determines the type of data a field can hold (text, integer, real, etc.).Data type
An automatic computer check that data is sensible, reasonable and consistent.Validation
A validation check that ensures data has been entered into a field.Presence check
A validation check that ensures a value falls within a specified range.Range check
A single character used at the end of a code to verify the other digits.Check digit
A standard query language used to write scripts that request data from a database.SQL (Structured Query Language)
SQL keyword that fetches specified fields from a table.SELECT
SQL keyword that identifies the table to use in a query.FROM
SQL keyword that includes only records matching a given condition.WHERE
SQL keyword that sorts query results by a given column.ORDER BY
SQL keyword used to sort results in descending order.DESC
SQL aggregate function returning the sum of all values in a field.SUM()
SQL aggregate function counting records matching a condition.COUNT()
SQL statement that adds new records to a table.INSERT INTO
SQL statement that modifies existing records in a table.UPDATE
SQL statement that removes records from a table.DELETE FROM