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.
- To store information about people — like pupils at school, patients in a hospital, etc.
- To store information about things — like cars to be sold, books in a library, etc.
- 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 |
|---|---|---|---|
| 6473 | Philip | Barker | 07/11/1995 |
| 6783 | Sandip | Dosanjh | 12/07/1995 |
| 6777 | Cynthia | Ferguson | 03/01/1996 |
| 6788 | Philip | Barker | 07/11/1995 |
| 6789 | Anne | Ruth | 01/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.
- Organize data of each individual or thing in rows, with each column containing data of the same data type.
- In table design view, name each field with its appropriate data type.
- Add validation check by specifying proper attributes like size (length of field), format, validation rule, etc.
- Identify the field which uniquely identifies each record and specify it as the primary key field.
- 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 |
|---|---|---|
| Text | Allows alphanumeric data — text, numbers and symbols. | Name: James Address: 73, High Street Postcode: CV34 5TR |
| Character | Allows only a single character of any alphanumeric data. | Code: N / C / P House: R / B / G / Y |
| Integer | Allows positive or negative whole numbers only. | Age: 16 Quantity: 36 Temperature: -10 |
| Real | Allows positive or negative decimal numbers. | Length (cm): 12.5 Weight (kg): 52.36 Temperature: -2.5 |
| Currency | Allows price with currency symbols and ensures two decimal places. | Cost: $5.75 Amount: £468.25 Price: €18.75 |
| Date/Time | Checks and allows only date and time in an appropriate format. | Long: 20 Feb 2006 18:21:35 Short: 20/02/06 18:21 |
| Boolean | Allows 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:
- To do a validation check over data while entering, to prevent invalid characters being stored.
- 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:
- File size can be kept as small as possible.
- 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:
- Code should always be of same length.
- Codes should contain enough detail and should not be too short.
- 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 check | Checks that data has been entered into a field. | Field which cannot be left blank like the primary key field. |
| Data-type check | Ensures that the correct type of data (text, number, date) is entered. | Name (Text), Date of birth (Date), Age (Number), Price (Currency). |
| Length check | Checks that the data isn't too short or too long. | A password which needs to be six letters long. |
| Format check | Checks that the data is in the right format. | Passport number M5228907 — a letter followed by 7 digits. |
| Date format check | Checks that the date is in the right format. | Date of birth in form 20 Jan 1998 or 20/01/1998. |
| Check digit | The 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 / Lookup | Looks up acceptable values in a list or table. | There are only seven possible days of the week. |
| Range check | Checks that a value falls within a specified range. | Number of hours worked must be > 0 and < 50. |
| Consistency / Cross-field | Checks that different fields in the same record correspond correctly. | If 'Mr' is in Title, 'Male' must be in Gender. |
| Spell check | Looks 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:
- View data only from the fields you are interested in viewing.
- Combine data from several data sources.
- Use expressions as fields.
- 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:
- An SQL query always begins with SELECT followed by FROM commands — both are mandatory in an SQL script.
- All other commands are optional.
- Start the SQL script with the SELECT command line, identify and write the names of fields to display separated by a comma (,).
- Next specify the table name in the FROM command line.
- Write the criteria or condition in the WHERE command line.
- Specify the names of fields to sort in the ORDER BY command line.
- 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. |
| = 100 | Records where field equals 100. |
| <> 100 / Not 100 | Records where field is not equal to 100. |
| > 50 | Records where field is greater than 50. |
| >= 50 | Greater than or equal to 50. |
| < 75 | Less than 75. |
| <= 75 | Less than or equal to 75. |
| 20 OR 25 | Either 20 or 25. |
| >0 AND <50 / Between 0 and 50 | Within a range (exclusive of boundaries for AND, inclusive for Between). |
| < 50 OR > 100 | Outside the range 50 to 100. |
| Is Null | No value in the field. |
| Is Not Null | Value 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 | ✓ | |
- 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 |
|---|---|---|---|---|---|---|---|---|
| 2030 | ATHOOF | M | 07-May-04 | 10(B) | Red | 70 | 82 | 94 |
| 2031 | FAINAAN | M | 12-Apr-04 | 10(A) | Yellow | 68 | 77 | 86 |
| 2033 | IYALA | F | 10-Oct-04 | 10(A) | Green | 89 | 92 | 95 |
| 2036 | MAIHA | F | 13-Sep-04 | 10(A) | Red | 76 | 82 | 90 |
| 2038 | SHAAIL | M | 08-Oct-04 | 10(B) | Orange | 54 | 79 | 58 |
| 2039 | HASEEN | M | 14-Dec-04 | 10(B) | Blue | 46 | 65 | 49 |
| 2043 | EENAASH | F | 10-Oct-04 | 10(A) | Green | 57 | 67 | 62 |
| 2238 | MAZEENA | F | 16-May-04 | 10(A) | Orange | 49 | 62 | 70 |
| 2053 | MAISHA | F | 24-Jun-04 | 10(B) | Yellow | 62 | 74 | 75 |
| 2072 | DHAAEE | M | 31-Dec-04 | 10(B) | Blue | 50 | 59 | 88 |
(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:
| Field | Data type |
|---|---|
| StdID | Integer |
| StdName | Text |
| Sex | Boolean (M/F) |
| DOB | Date/Time |
| Grade | Text |
| Eng | Integer |
(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:
| StdID | Sex | StdName |
|---|---|---|
| 2030 | M | ATHOOF |
| 2031 | M | FAINAAN |
| 2033 | F | IYALA |
| 2036 | F | MAIHA |
| 2053 | F | MAISHA |
(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 |
|---|---|---|---|---|---|
| CH001 | 1921 | Smith – six dining chairs | 6 | 4500 | Delivered |
| TB003 | 1921 | Smith – large table | 2 | 3200 | In progress |
| CH001 | 1924 | Hue – extra chairs | 4 | 3800 | Not started |
| CH003 | 1925 | Easy chairs | 2 | 3600 | Cancelled |
| BN001 | 1927 | Patel – replacement bench | 1 | 1350 | Not started |
| ST002 | 1931 | Sola – small table | 1 | 2400 | Delivered |
| CH003 | 1927 | Patel – eight dining chairs w/ arms | 8 | 9600 | In progress |
| TB003 | 1927 | Pagel – large table | 1 | 3450 | Not 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 |
| 6473 | Philip | H01 | H01 | Red |
| 6783 | Sandip | H02 | H02 | Yellow |
| 6777 | Cynthia | H01 | H03 | Green |
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) ;
- 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)" ;
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 ;
Summary — Data Manipulation vs Query:
| SQL Statement | Action | Type |
|---|---|---|
| SELECT | Read / fetch data | Query (DQL) |
| INSERT INTO | Add new records | Manipulation (DML) |
| UPDATE | Modify existing records | Manipulation (DML) |
| DELETE FROM | Remove records | Manipulation (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 |