18 Databases – Sorting Data
Learning Objective
Be able to use a single criterion, or multiple criteria, to sort data into ascending or descending order and to evaluate the most appropriate way to sort data in a given situation.
1 Creating a Database Structure (Syllabus 18.1)
1.1 Why a good structure matters
- Ensures data integrity (no duplicate records, correct relationships).
- Facilitates efficient searching, sorting and reporting.
- Provides a clear basis for forms, queries and calculations.
1.2 Flat‑file vs Relational tables
| Aspect | Flat‑file (single table) | Relational (multiple linked tables) |
|---|
| Data redundancy | High – same information repeated in many rows | Low – data stored once and referenced |
| Maintenance | Hard – changes must be made in many places | Easy – change in one table updates all related records |
| Scalability | Limited – becomes unwieldy as records grow | Good – tables can be added without redesign |
| Typical use | Simple lists, one‑off reports | Complex applications (school, business, inventory) |
1.3 Field types and sub‑types
| Data Type | Sub‑type (if any) | Typical display format |
|---|
| Short Text | None (or “Email”, “Phone” for validation) | Plain text |
| Long Text | None | Paragraphs, notes |
| Number | Integer, Long Integer, Single, Double | 1, 2, 3 … (no decimal unless Single/Double) |
| Currency | Currency | £ 1,234.56 (symbol & two decimals) |
| Number | Percentage | 45 % (displayed with % sign) |
| Yes/No | Boolean | True/False or Tick/Blank |
| Date/Time | Short Date, Long Date, Time | dd/mm/yyyy, “12‑Jan‑2024” etc. |
| AutoNumber | Long Integer | System‑generated unique number |
1.4 Primary & foreign keys – relationships
- Primary key: a unique, non‑null identifier for each record (e.g.,
StudentID). - Foreign key: a field that stores the primary key value from another table, creating a link.
- One‑to‑many example:
Students.ClassID → Classes.ClassID. Each student belongs to one class; each class can have many students. - Enforce referential integrity (Access: Table Design ► Relationships ► Enforce Referential Integrity) to prevent orphaned records.
1.5 Example: “Students” Table
| Field Name | Data Type (Sub‑type) | Key | Purpose |
|---|
| StudentID | AutoNumber (Long Integer) | Primary | Unique identifier. |
| FirstName | Short Text (30) | | Given name. |
| LastName | Short Text (30) | | Family name. |
| DateOfBirth | Date/Time (Short Date) | | Used for age calculations. |
| ClassID | Number (Long Integer) | Foreign | Links to Classes table. |
1.6 Importing external data
- File ► Import ► External Data ► CSV File (or Text).
- Browse to the file, choose Delimited (comma) or Fixed Width.
- Map each column to an existing field or let the wizard create new fields.
- Set the correct data type/sub‑type for each imported column.
- Check “First Row Contains Field Names” if applicable.
- Finish – the data appear in a new table ready for relationships.
1.7 Form design (Syllabus 18.1)
A well‑designed form hides the table structure, guides the user and prevents invalid data.
Steps to create a basic data‑entry form
- Choose Form Wizard ► select the Students table.
- Drag the required fields onto the layout (typically in logical order).
- Set
StudentID as Locked (auto‑generated). - Adjust Tab Order (Design ► Tab Order) so navigation feels natural.
- Save the form as
frmStudents.
Validation checklist (AO2 – Apply)
| Rule | Example |
|---|
| Required field | FirstName, LastName must not be blank. |
| Range check | Age (derived from DateOfBirth) must be 5 – 120. |
| Format check | Email must contain “@”. |
| Lookup list | ClassID displayed as a drop‑down of existing Class names. |
| Unique constraint | StudentID is unique (primary key). |
2 Sorting Fundamentals (AO1 – Recall)
| Term | Definition |
|---|
| Criterion (field) | Column used to determine the order of records. |
| Record | A single row of related data in a table. |
| Ascending order | Smallest → largest; A → Z; earliest → latest. |
| Descending order | Largest → smallest; Z → A; latest → earliest. |
| Primary key | Unique identifier; cannot be null. |
| Foreign key | Links to the primary key of another table. |
| Stable sort | Preserves the relative order of records that compare equal on earlier criteria. |
3 Sorting by a Single Criterion
3.1 Procedure (Access, LibreOffice Base, MySQL Workbench, etc.)
- Select the table or query you wish to sort.
- Open the Sort dialog (toolbar ► Sort or right‑click ► Sort…).
- Choose the field (criterion) from the drop‑down list.
- Select Ascending or Descending.
- Click OK – the view updates immediately.
- To keep the order permanently, save the result as a new table or as a saved query.
3.2 Example – Single‑field Sort
Original Students table (unsorted):
| StudentID | Name | Score |
|---|
| 102 | Alice | 78 |
| 215 | Bob | 85 |
| 317 | Charlie | 62 |
| 428 | Diana | 91 |
Sorted by Score (Descending):
| StudentID | Name | Score |
|---|
| 428 | Diana | 91 |
| 215 | Bob | 85 |
| 102 | Alice | 78 |
| 317 | Charlie | 62 |
4 Sorting by Multiple Criteria (AO2 – Apply)
4.1 How it works
- The database first sorts on the primary criterion.
- Within each group that shares the same primary value, it sorts on the secondary criterion, and so on.
- This is a stable sort; later criteria do not disturb the order established by earlier ones.
4.2 Procedure
- Open the Sort dialog (or design a query and use the Sort By row).
- Enter the first field in the first row and choose its direction.
- Add a second field in the next row, choose its direction, and continue for any further fields.
- Run the query or view – the records appear ordered by the hierarchy of criteria.
- Save the query (e.g.,
qrySortedProducts) or export the result for later use.
4.3 Example – Two‑field Sort
Original Products table:
| Category | Product Name | Price ($) | Stock |
|---|
| Electronics | Headphones | 45 | 120 |
| Electronics | Smartphone | 299 | 45 |
| Furniture | Desk | 150 | 30 |
| Furniture | Chair | 85 | 80 |
| Electronics | Tablet | 199 | 60 |
| Furniture | Bookshelf | 120 | 25 |
Sort by Category (Ascending) then by Price (Descending):
| Category | Product Name | Price ($) | Stock |
|---|
| Electronics | Smartphone | 299 | 45 |
| Electronics | Tablet | 199 | 60 |
| Electronics | Headphones | 45 | 120 |
| Furniture | Desk | 150 | 30 |
| Furniture | Bookshelf | 120 | 25 |
| Furniture | Chair | 85 | 80 |
5 Calculations & Queries (Syllabus 18.2)
5.1 Calculated fields
Example: Adding a TotalPrice field to an OrderDetails query.
SELECT ProductName,
Quantity,
UnitPrice,
Quantity * UnitPrice AS TotalPrice
FROM OrderDetails;
The query now shows the line‑item total, which can also be sorted.
5.2 SELECT‑WHERE query with sorting
Show all orders placed in 2024, sorted by OrderDate (Descending) then by CustomerID (Ascending):
SELECT OrderID, CustomerID, OrderDate, TotalAmount
FROM Orders
WHERE OrderDate BETWEEN #01/01/2024# AND #31/12/2024#
ORDER BY OrderDate DESC, CustomerID ASC;
6 Presenting Sorted Data (Syllabus 18.3)
6.1 Creating a simple report
- Open the sorted query (e.g.,
qrySortedProducts). - Choose Report Wizard ► select the query as the data source.
- Pick the fields to display.
- In the wizard’s “Sorting” step, confirm the same order as the query.
- Choose a layout, add a title, page header/footer and page numbers.
- Finish and preview the report.
Figure 2 – Report Wizard screenshot (placeholder)
6.2 Exporting sorted results
- In query view, click Export ► CSV (or PDF for a printable report).
- Open the CSV in a text editor to verify that the order matches the query.
7 Key Points & Common Pitfalls (Depth & Accuracy)
7.1 Data‑type considerations
- Numeric vs Text: Text fields sort alphabetically (“10” precedes “2”). Use a numeric field or a calculated numeric expression for true numeric ordering.
- Date/Time fields: Must be stored as Date/Time. Text dates sort lexicographically and give incorrect results.
- Leading zeros: In text fields “001”, “010”, “100” sort as written; in numeric fields they are treated as 1, 10, 100.
7.2 Null / blank handling
Records with Null values are usually placed at the top when sorting Ascending and at the bottom when sorting Descending, but behaviour can vary between DBMSs. Always check the result when blanks are present.
7.3 Sorting stability
A stable sort guarantees that records equal on the first criterion retain the order established by the second (and subsequent) criteria. This matters when you later add another sort level.
7.4 Indexing and performance (AO3 – Evaluate)
- Indexed fields sort faster because the DBMS can read the index in order.
- Creating an index on a large text field increases storage size; weigh benefit against cost.
- For very large tables (e.g., >10 000 records), sorting inside the database is usually quicker than exporting to a spreadsheet, unless the DBMS lacks appropriate indexes.
7.5 Saving a sorted view
- Sorts applied in the table view are temporary – they disappear when the table is reopened.
- To keep the order, save the result as a new table (e.g.,
tblSortedStudents) or create a saved query that includes an ORDER BY clause.
8 Evaluation Activity (AO3)
Task: Compare sorting a 12 000‑record Orders table directly in Access with sorting the same data after exporting it to Excel.
- Record the time taken for each method (use a stopwatch).
- Note any differences in ease of selecting multiple criteria.
- Discuss the impact of indexing on the Access sort.
- Write a short paragraph recommending which method to use in a real‑world scenario and justify your choice.
9 Practice Activities (AO2)
- Open the sample Employees table. Sort by Last Name (Ascending). Record the first and last employee displayed.
- Using the same table, sort by Department (Ascending) then by Salary (Descending). List the three highest salaries in each department.
- Create a query that shows all records from the Orders table, sorted by Order Date (Descending) and then by Customer ID (Ascending). Export the result to a CSV file.
- The field ProductCode is stored as text. After sorting you obtain the order: 1, 10, 2, 20, 3 … Explain why this happens and describe two ways to correct it.
- Design a simple report based on the sorted query from activity 3. Include a title, page header, and page number.
10 Quick Revision – Match the Term
| Term | Definition |
|---|
| Criterion | Field used to determine order. |
| Primary key | Unique identifier for each record. |
| Foreign key | Field that links to another table’s primary key. |
| Ascending | Smallest → largest (A → Z). |
| Descending | Largest → smallest (Z → A). |
| Stable sort | Preserves the relative order of records that compare equal on earlier criteria. |
11 Suggested Flowchart (Figure 3)
A visual flowchart helps learners remember the steps for single‑criterion and multiple‑criterion sorting.
- Open table/query → Choose Sort dialog.
- Single criterion: select field → choose direction → OK.
- Multiple criteria: add first field → set direction → add second field → set direction → OK.
- Save as query or export if a permanent view is required.
Figure 3 – Flowchart placeholder