Databases
1. Data Storage — Two Approaches
≈ Excel / flat files. Can still hold data, but it is not a relational database.
Tables are linked (related) and managed by a DBMS (e.g. MS Access).
Key idea: a relational DB keeps the same row/column idea as a file, but adds tools (query processor etc.) and lets you form relationships between tables — impossible in the file-based approach, where data just repeats.
2. Limitations of the File-Based Approach
Q: What are the limitations of using a file-based approach?
| Limitation | Meaning (board) | Example (sir) |
|---|---|---|
| Data redundancy | data is repeated in more than one file | student registers twice (no feedback after 1st form) → same data stored 2× |
| Data dependency | changes to data mean changes to the program accessing the data | family name changes → must edit every single value in every file |
| Lack of data integrity | entries that should be the same can differ in different places | ID 1145 = “Taha” in one table but “Ali” in another |
| Lack of data privacy | all users have access to all data if a single flat file | can't set a username/password or hide part of the file |
3. Benefits of a Relational Database
Q: Benefits of a relational database instead of a flat file?
Just flip each limitation — they are the opposite (“vice versa”):
| File-based problem | Relational database gives… |
|---|---|
| data redundancy | reduced data redundancy |
| data dependency | reduced data dependency |
| lack of integrity | improved data integrity |
| lack of privacy | improved data privacy |
| — | program–data independence |
| — | ability to create ad hoc queries |
Ad hoc query = a query designed for a particular purpose, written on the spot, e.g. “all licences whose expiry date is after 30 Oct 2022”.
Program–data independence means:
- structure of data can change and does not affect the program
- structure of programs can change and does not affect the data
Q: Describe the features of a relational database that address the limitations of a file-based approach
- Multiple tables are linked together (using primary & foreign keys) → reduces data redundancy, increases data integrity, referential integrity can be enforced
- Program–data independence → data structure can change without affecting the program, and vice versa
- Complex queries can be more easily written (SQL) → to find specific data
- Different users can be given different access rights → improves security
- Different users can be given different views of the data → they don't see confidential information, so data privacy is maintained
4. Database Terms
DBMS = Database Management System — software that manages databases (e.g. Microsoft Access; AWS/IBM are the databases/platforms). Studied in detail at university; here only features.
The Student table — spot every term
| Roll No. | Name | Course |
|---|---|---|
| CS08 | Steive | Comp. Sci. |
| EE54 | Jhoson | Electronics |
| B12 | Eva | Biology |
| F32 | Jhoson | Finance |
| M26 | Erica | Maths |
● Entity = the whole Student table | ● Attributes = Roll No., Name, Course (headings) | ● Field = a column (e.g. Course) | ● Record / Tuple = one row (e.g. M26 Erica Maths)
| Term | Definition | Here |
|---|---|---|
| Entity | The concept or object in the system that we want to model and store information about | Student (also: employee, course) |
| Attribute | A data item, represented as a field within a table | Roll No, Name, Course |
| Field | a column value / column of the table | Course column |
| Record = Tuple | all the data about one entity instance = one row (like filling one form) | M26 · Erica · Maths |
| Table | all the data about one entity | the Student table |
| Primary key | A unique identifier for each tuple | Roll No |
| Foreign key | A field in one table that links to a primary key in another table | Roll No in Scores |
5. Keys — Primary, Foreign, Candidate
① Primary key (PK)
A unique identifier for each tuple (every record has one). Test an attribute: can it repeat?
- Name → no (“Jhoson” appears twice)
- Course → no (many students take Maths)
- Roll No → yes — different for every student (like CNIC, passport no.)
So to tell the two “Jhoson”s apart we use Roll No as the primary key. In exam tables the PK is underlined.
② Foreign key (FK)
Take the PK of the base table and use the same field in another table (e.g. a Scores table) → there it is a foreign key. Its job: create a relationship between the tables.
③ Candidate key & secondary key
Student table: Roll No, CNIC, Passport Number, Candidate number can each uniquely identify a student ⇒ all are candidate keys. Choose Roll No → it is the primary key; the rest are secondary keys.
6. Past-Paper Practice — Terms & Keys
Database tables (PKs underlined): CUSTOMER_DETAILS(CustomerID, CompanyName, Address1, Address2, City) and SOFTWARE_PURCHASED(SoftwareName, SoftwareDescription, CustomerID, LicenceType, LicenceCost, RenewalDate). Give an example of: entity, foreign key, attribute.
An entity is an object we store info about → a table; “CustomerID” alone is not an object. An attribute is a feature (column) of it. The FK is the field also used in the other table (the PK of CUSTOMER_DETAILS).
| Term | Example |
|---|---|
| Entity | CUSTOMER_DETAILS or SOFTWARE_PURCHASED |
| Foreign key | CustomerID |
| Attribute | SoftwareDescription |
Tip: when it asks for “examples” give what's asked — any one valid answer per row = free marks (“muft ke 3 marks”).
A bank stores customers' first name, last name, DOB; each account type has a unique ID, a name (regular/saving) and a bonus ($5/$10/$15); a customer can have more than one account; each customer account has its own ID number and the amount of money. Normalised design = 3 tables: CUSTOMER, ACCOUNT_TYPE, CUSTOMER_ACCOUNT.
Method: pull each attribute out of the wording, underline the PK. No ID given for customer? first/last name and DOB can all repeat → invent a new attribute CustomerID (common sense). CUSTOMER_ACCOUNT needs the two FKs to link the other tables.
Why a 3rd table? CUSTOMER and ACCOUNT_TYPE had no common key → no relationship. CUSTOMER_ACCOUNT uses CustomerID (PK of CUSTOMER) and AccountID (PK of ACCOUNT_TYPE) as foreign keys — that is how normalisation links tables.
| Definition | Term |
|---|---|
| All the data about one entity | Table |
| The data in one row of a table | Record / Tuple |
| A column or field in a table | Attribute |
Describe the role of a primary and a foreign key in a database relationship
- Primary key uniquely identifies each tuple
- Primary key can be used as a foreign key in another table
- to form a relationship between the tables
7. Structured Query Language (SQL) — DDL
SQL = Structured Query Language. It has two parts:
defines the structure: create database / table, add a field (ALTER)
works on the data: INSERT, UPDATE, SELECT, DELETE
① DDL — create a database
e.g. CREATE DATABASE Student;
Write a DDL statement to create the EMPLOYEES database.
② DDL — create a table
Data types (know examples):
| Type | Example | Meaning |
|---|---|---|
| Integer | 54 | whole number |
| Date | 04/04/2020 | a date |
| Time | 18:00 | a time |
| Varchar | — | (string) |
| Varchar(n) | — | string which can contain a maximum of n characters |
<attribute name> <datatype>,
<attribute name> <datatype>,
<attribute name> <datatype>,
PRIMARY KEY (name) NOT NULL
);
Define the table EMPLOYEE_DATA and declare EmployeeID as the primary key. Data: EmployeeID varchar(7) (156FJEK), FirstName varchar, LastName varchar, DateOfBirth Date (12/05/1984), Gender varchar(6) (Male/Female), DepartmentNumber varchar(2) (S1, F2).
Read the example data to pick each type: ID has letters → varchar(7); “Female” = 6 letters → varchar(6); “S1” = 2 chars → varchar(2).
EmployeeID VARCHAR(7) NOT NULL) and the last line is just PRIMARY KEY (EmployeeID) — stick to the board's form in the exam.③ DDL — add a new field
ADD <field name> <datatype>;
STUDENT needs an extra field for the telephone number, e.g. 012-3456. Write a DDL statement to add it.
Why only ½? The ✓ was circled on ADD and the field/datatype underlined — the marks are for ALTER TABLE, ADD, a sensible field name, and a data type that fits the data. “012-3456” contains a hyphen, so it must be VARCHAR (text), not INTEGER. Check you write every part, including the final ;
8. DML — Manipulating the Data
① INSERT — add data into a table
VALUES (<data in column 1>, <data in column 2>, …);
ROOM(RoomNumber, RoomType) holds 1 Standard, 2 Double, 3 Executive, 4 Standard. Room 5 is a Double room — complete the DML to add it.
Text values go in quotes; numbers don't. Values follow the column order.
SHOP_SUPPLIER(ShopID, SupplierID). Existing shop 8765 has used existing supplier SUP89 for the first time — add this data.
Correction: the board wrote VALUE — the keyword is VALUES.
1. Specify column names and values:
INSERT INTO table_name (column1, column2, column3, …) VALUES (value1, value2, value3, …);2. Adding values for all the columns? You can skip the column names — but the order of the values must match the table's column order:
INSERT INTO table_name VALUES (value1, value2, value3, …);② UPDATE — change data / a record
SET <column 1> = <value 1>, <column 2> = <value 2>, …
WHERE <condition>;
Fatima Woo is an Area B nurse, NurseID 076. She married and her new family name is Chi. Write an SQL command to update her record.
Table = B_Nurse; column to change = FamilyName (old value Woo → new Chi); find the record by the unique ID (not the name).
③ SELECT — display / return values
FROM <table name>
WHERE <conditions>;
Display the Nurse ID and family name for all Area B nurses with specialism ‘THEATRE’.
LESSON(LessonID, StudentID, InstructorID, LessonDate, LessonTime). Return the date and time of all future lessons booked with instructor Ins01.
Underline the clues: date and time → SELECT list; future → LessonDate > today's date; Ins01 → InstructorID = “Ins01”. Two conditions ⇒ join with AND.
GAME_DEVELOPMENT(GameName, Genre, TeamNumber, DevelopmentStage, ManagerID) e.g. Bunny Hop · Platform · 4 · Analysis · 23KP; Fried Eggs · Retro · 2 · Programming stage 1 · 9RTU; Create-a-game · Action · 1 · Acceptance testing · 11TF. Another table: PRODUCT_MANAGER(ManagerID, FirstName, LastName). Return the game name, genre and team number of all games managed by the product manager James Fitz.
Why two tables? The name James Fitz lives in PRODUCT_MANAGER but the games live in GAME_DEVELOPMENT. They are connected by ManagerID (PK in PRODUCT_MANAGER, FK in GAME_DEVELOPMENT) — so add a join condition in the WHERE.
Board slip: the last line was written GameDevelopment.ManagerID (no underscore) — use the exact table name Game_Development. Ticks were given for the first two conditions; the third (the join condition) is the one students forget. A neater way = INNER JOIN (section 9).
CUSTOMER(CustomerID, CompanyName) · SOFTWARE(SoftwareID, SoftwareName, OperatingSystem, Description) · LICENCE(LicenceID, CustomerID, SoftwareID, DateOfPurchase, LicenceType, Cost, ExpiryDate). Return CustomerID, SoftwareID, LicenceType, Cost and ExpiryDate for all licences that expire on or before 31/12/2019. Group the output by CustomerID, in ascending order of cost.
Watch: “on or before” → <= (not <). ASC = ascending (smallest first) · DESC = descending. The board wrote the table as “LICENSE” — the question's spelling is LICENCE.
④ DELETE — remove records
WHERE <condition>;
Table Customers: (1) Alfreds Futterkiste · Maria Anders · Berlin · Germany; (2) Ana Trujillo Emparedados y helados · México D.F.; (3) Antonio Moreno Taquería · México D.F.; (4) Around the Horn · Thomas Hardy · London · UK; (5) Berglunds snabbköp · Christina Berglund · Luleå · Sweden.
⑤ Aggregate functions — COUNT( ) · AVG( ) · SUM( )
FROM table_name
WHERE condition;
FROM table_name
WHERE condition;
FROM table_name
WHERE condition;
COUNT = how many · AVG = average · SUM = total. WHERE is optional (omit it to use all records).
Products table: (ProductID, ProductName, SupplierID, CategoryID, Unit, Price) → 1 Chais 18 · 2 Chang 19 · 3 Aniseed Syrup 10 · 4 Chef Anton's Cajun Seasoning 22 · 5 Chef Anton's Gumbo Mix 21.35
Number of products
→ 5
Average price
→ (18+19+10+22+21.35)/5 = 18.07
Sum of all the prices
→ 18 + 19 + 10 + 22 + 21.35 = 90.35
9. INNER JOIN
The INNER JOIN keyword selects records that have matching values in both tables.
FROM <table 1>
INNER JOIN <table 2>
ON table1.column_name = table2.column_name
WHERE <condition>;
ACTOR(ActorID, FirstName, LastName, DateOfBirth) · FILM_FACT(FilmID, FilmTitle, ReleaseDate, Category) · FILM_ACTOR(ActorID, FilmID). Return the IDs of all the actors in the film titled Cinderella.
The title is in FILM_FACT, the actor IDs are in FILM_ACTOR → link them on FilmID.
STAFF(StaffID, FirstName, LastName, DateOfBirth, JobTitle) · DEVICE(DeviceID, Type, DatePurchased, StaffID) (StaffID circled in both = the link). Return the number of devices for staff member Ali Khan.
The four blanks to fill were: COUNT · STAFF · ON · AND.
10. Referential Integrity
Q: What is meant by referential integrity? (≈ 3–4 marks)
- Referential integrity is making sure tables do not try to reference data which does not exist ✓
- A primary key cannot be deleted unless all dependent records are already deleted → cascading delete
- A primary key cannot be updated unless all dependent records are already updated → cascading update / edit
- Every foreign key value has a matching value in the corresponding primary key
- The foreign key must be the same data type as the corresponding primary key
Customer 1028 (Bano, 03/01/04, Islamabad) has order no. 75 (Shoes, 13/02/22) ✓. A second order (no. 76) with an ID that is not in Customer “cannot be referenced” — this is enforced by referential integrity.
Related theory questions
→ repeated data.
- Because each record of data is stored once and is referenced by a primary key
- Because data is stored in individual tables
- … and the tables are linked by relationships
- By the proper use of primary and foreign keys
- By enforcing referential integrity
- By going through the normalisation process
- Name is the primary key in table 1
- … links to Name, which is the foreign key in table 2
(fill the blank with the real field, e.g. “CustomerID is the PK in CUSTOMER and links to CustomerID, the FK in CUSTOMER_ACCOUNT”)
- Ensure data is consistent
- by enforcing referential integrity, validation rules
11. Entity–Relationship (ER) Diagrams
An ER diagram shows the relationships between tables. Four degrees of relationship:
| Relationship | Example | Meaning |
|---|---|---|
| One to One | Employee — Office | 1 employee ↔ 1 office |
| One to Many | Teacher —< Students | 1 teacher → many students |
| Many to One | Students >— Teacher | many students → 1 teacher |
| Many to Many | Customers >—< Products | needs a link table |
(a) A-NURSE >— A-WARD: Many to One (crow's foot on the NURSE side).
(i) B-NURSE >—< B-WARD: degree of relationship = Many to Many.
CUSTOMER(CustomerID, CompanyName); LICENCE(LicenceID, CustomerID, SoftwareID, …). One customer can hold many licences, each licence belongs to one customer → One to Many.
INSTRUCTOR(InstructorID, FirstName, LastName, DateOfBirth, Level) · CAR(Registration, Make, Model, EngineSize) · INSTRUCTOR_CAR(InstructorID, Registration) · STUDENT(StudentID, FirstName, LastName, DateOfBirth, Address1) · LESSON(LessonID, StudentID, InstructorID, LessonDate, LessonTime)
Find each FK, then put the foot at the table holding it: INSTRUCTOR_CAR holds InstructorID & Registration; LESSON holds StudentID & InstructorID.
MEMBER(MemberID, FirstName, LastName, MembershipType) · SESSION(SessionID, Description, SessionDate, SessionTime, NumberMembers) · TRAINER(TrainerID, TrainerFirstName, TrainerLastName) · MEMBER_SESSION(MemberID, SessionID) · SESSION_TRAINER(SessionID, TrainerID)
USER(UserName, FirstName, SecondName, DateOfBirth) · PHOTO(PhotoID, UserName, Comment, UploadDate) · TEXTPOST(PostID, UserName, DateOfPost, TheText)
An employee can be a manager · a department can have several managers and several employees · an employee belongs to only one department. EMPLOYEE_DATA(EmployeeID, FirstName, LastName, DateOfBirth, Gender, DepartmentNumber) · DEPARTMENT(DepartmentNumber, DepartmentName) · DEPARTMENT_MANAGER(DepartmentNumber, EmployeeID, role)
Note: on the board EMPLOYEE_DATA >— DEPARTMENT and DEPARTMENT —< DEPARTMENT_MANAGER were drawn with feet; the third line (EMPLOYEE_DATA — DEPARTMENT_MANAGER) was left as a plain line. Since DEPARTMENT_MANAGER holds EmployeeID as a FK, its foot goes on the DEPARTMENT_MANAGER end.
12. Database Management System (DBMS)
Screenshot on board: MS Access with tables (tblDepartment, tblHumanResourcesData, tblParkingInfo, tblPersonalData) and queries listed on the left, and the table data (Id, First Name, Last Name, Address, City, State, Zip, Phone) on the right.
Q: Describe the DBMS tools
Developer interface
- to create user-friendly features, e.g. forms to enter a new booking
- to create outputs, e.g. report of bookings on a given date
- to create interactive features, e.g. buttons or menus
Query processor
- to create SQL queries
- to search for data that meets set criteria, e.g. all bookings for next week
- to perform calculations on extracted data, e.g. number of empty rooms
- organises the results to be displayed
Q: The DBMS has a data dictionary — describe what it stores
- Stores all the information about the database
- e.g. fields, data types, keys
Tasks performed by the DBMS developer interface
- Create a table
- Set up relationships between tables
- Create a form
- Create a report
- Create a query
Q: How is DBMS software used to ensure the security of the data?
| Method | Why / how |
|---|---|
| Issue usernames and passwords | stops unauthorised access to the data · a strong password should be used |
| Access rights | only certain usernames can read certain parts of the data · read-only or full access · e.g. only the Finance department can edit/read finance data |
| Create regular backups | if live data is lost/damaged a copy is available · e.g. backup at the end of each day |
| Encryption of data | if there is unauthorised access, the data cannot be understood (e.g. … — left blank on the board) |
13. Normalisation
Normalisation “is a method to remove or reduce the repetition of the data (redundancy)”.
① 1NF — First Normal Form
- No repeated group of attributes
- All attributes should be atomic — an attribute that cannot be decomposed into meaningful components
- No duplicate rows
FirstName | Courses
Taha | Math
Taha | English
(Taha repeats; courses are a repeating group → split into separate tables)
② 2NF — Second Normal Form
- Must already be in 1NF ✓
- No partial dependency ✓ — every non-key attribute must depend on the whole key, not on part of it
Subject table(subject_id, subject_name) ✓
Score table(score_id, student_id, subject_id, marks, teacher) — compound key = student_id + subject_id, but teacher is only dependent on subject_id ✗ → partial dependency.
③ 3NF — Third Normal Form
- Should be in 1NF and 2NF
- No non-key dependency (a non-key attribute depending on another non-key attribute)
- No transitive dependency
CUSTOMER_DETAILS(CustomerID, CompanyName, Address1, Address2, City) · SOFTWARE_PURCHASED(SoftwareName, SoftwareDescription, CustomerID, LicenceType, LicenceCost, RenewalDate) — compound key = SoftwareName + CustomerID.
Explain why this database is NOT in 3NF:
- There are partial dependencies in the SOFTWARE_PURCHASED table: SoftwareDescription depends only on SoftwareName and does not depend on both parts of the key.
- There is a non-key dependency in SOFTWARE_PURCHASED: LicenceCost depends on LicenceType and does not depend on the primary key.
14. Levels of Schema of a Database
| Schema level | Description (board) |
|---|---|
| External schema | The individual's view of the database |
| Conceptual schema | Describes the views which users of the database might have |
| Logical schema | Describes how the relationships will be implemented in the logic structure of the database |
| Physical / Internal schema | Describes how the data will be stored on the physical media |
15. Quick Recap — Full Chapter Cheat-Sheet
- File-based limits: redundancy · dependency · lack of integrity · lack of privacy
- Relational benefits: reduced redundancy/dependency · better integrity/privacy · program–data independence · ad hoc & complex queries · access rights/views
- Terms: entity = table/object · attribute = field/column · record = tuple = row · PK unique ID · FK = PK of another table (makes the relationship) · candidate keys → 1 primary + rest secondary
- Ref. integrity: no reference to non-existent data · cascade delete/update · FK has matching PK, same data type
- Security: usernames/passwords · access rights · backups · encryption
- DBMS tools: developer interface · query processor · data dictionary
- Normalisation: 1NF atomic/no repeats · 2NF no partial dependency · 3NF no non-key/transitive dependency
- Schema: external · conceptual · logical · physical/internal
CREATE TABLE name ( attr type, …, PRIMARY KEY (attr) NOT NULL );
ALTER TABLE name ADD field type;
INSERT INTO name VALUES (v1, v2, …);
UPDATE name SET col = val WHERE cond;
SELECT cols FROM name [INNER JOIN t2 ON t1.col = t2.col] WHERE cond [GROUP BY col] [ORDER BY col ASC|DESC];
DELETE FROM name WHERE cond;
SELECT COUNT(col) | AVG(col) | SUM(col) FROM name;