






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







How to use this guide. Read Sections 1 to 3 for the core vocabulary, work through the SQL examples in Section 4 by typing them into any SQL engine (SQLite, MySQL, PostgreSQL or SQL Server all accept the code shown), then study normalization in Sections 5 to 7. Section 8 is a one-page summary table for revision, and Section 9 contains 20 practice questions with full answers.
Contents
The relational model in plain terms Keys and integrity constraints The four families of SQL commands SQL worked examples on a sample database Functional dependencies Update anomalies: why we normalize Normalization step by step: UNF, 1NF, 2NF, 3NF, BCNF Summary table Practice questions and answers
A relational database stores data in relations , which most people call tables. Each table describes one kind of thing (an entity such as a student or a course) or one relationship between things (such as a student enrolling in a course).
Formal term Everyday term Meaning Relation Table A named set of rows that all have the same columns Tuple Row / record One instance, for example one particular student Attribute Column / field One property, for example last_name Domain Data type + allowed values The set of legal values for an attribute, for example integers 1 to 5 Degree Number of columns A table with 4 columns has degree 4 Cardinality Number of rows A table with 120 rows has cardinality 120 Schema Table definition The table name plus its attributes and constraints
Three properties make a table a true relation:
Every cell holds a single (atomic) value. No lists or repeating groups inside a cell. Rows are unique. No two rows are identical, which is guaranteed by a primary key. Order does not matter. Neither the order of rows nor the order of columns carries meaning.
Key type Definition Example Superkey Any set of attributes that uniquely identifies a row {student_id, last_name} Candidate key
A minimal superkey: remove any attribute and it stops being unique
{student_id} , or {national_id} if also stored Primary key The candidate key chosen as the main identifier; cannot be NULL
student_id
national_id
Key type Definition Example Alternate key
A candidate key that was not chosen as primary key Composite key
A key made of two or more attributes {student_id, course_code, semester} Foreign key An attribute that refers to the primary key of another (or the same) table
enrollment.student_id → student.student_id Surrogate key
An artificial key with no business meaning, often auto-generated
an auto-increment id
Integrity rules
Entity integrity: no part of a primary key may be NULL. Referential integrity: a foreign key value must either match an existing primary key value in the referenced table or be NULL (if the column allows NULL). Domain integrity: values must come from the column's domain, enforced with data types, NOT NULL , CHECK and UNIQUE.
Prime and non-prime attributes. An attribute that belongs to any candidate key is called prime. All others are non-prime. This distinction matters for 2NF and 3NF.
3. The four families of SQL commands
Family Purpose Main commands DDL (Data Definition Language) Create and change structure CREATE , ALTER , DROP , TRUNCATE DML (Data Manipulation Language) Read and change data SELECT , INSERT , UPDATE , DELETE DCL (Data Control Language) Permissions GRANT , REVOKE TCL (Transaction Control Language) Group changes into transactions (^) COMMIT , ROLLBACK , SAVEPOINT
Some textbooks place SELECT in its own group called DQL (Data Query Language). Both conventions are common; just be consistent in an exam answer.
Logical order of a SELECT statement. You write clauses in this order: SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY. The database evaluates them in a different logical order:
FROM (and JOIN ) builds the working set of rows WHERE filters individual rows GROUP BY forms groups HAVING filters groups SELECT computes the output columns ORDER BY sorts the result
This order explains two common errors: you cannot use an aggregate such as COUNT(*) inside WHERE (groups do not exist yet), and in standard SQL you cannot refer to a SELECT alias inside WHERE.
4. SQL worked examples on a sample database
All examples below were run against the following schema and data, and the results shown are the actual outputs.
4.1 Creating the tables (DDL)
CREATE TABLE department ( dept_id INTEGER PRIMARY KEY, dept_name VARCHAR(50) NOT NULL UNIQUE );
CREATE TABLE student (
SELECT first_name, last_name, year_of_study FROM student WHERE dept_id = 10 ORDER BY last_name;
first_name last_name year_of_study Amina Hassan 2 Brian Otieno 3
NULL trap: WHERE dept_id = NULL returns nothing, because any comparison with NULL is unknown , not true. Use WHERE dept_id IS NULL to find Esther.
4.4 INNER JOIN across three tables
Task: show each student's first name, the course title and the grade, only for grades of 65 or above, highest first.
SELECT s.first_name, c.title, e.grade FROM enrollment e JOIN student s ON s.student_id = e.student_id JOIN course c ON c.course_code = e.course_code WHERE e.grade >= 65 ORDER BY e.grade DESC;
first_name title grade Brian Discrete Mathematics 81 Amina Database Systems 78 Carol Principles of Management 70 David Database Systems 66
4.5 LEFT JOIN to find missing matches
Task: find students who have not enrolled in anything.
SELECT s.first_name FROM student s LEFT JOIN enrollment e ON e.student_id = s.student_id WHERE e.student_id IS NULL;
Result: Esther. A LEFT JOIN keeps every row from the left table; where there is no match, the right- hand columns are filled with NULL, and the WHERE … IS NULL keeps exactly those unmatched rows. The same result can be written with NOT EXISTS :
SELECT s.first_name FROM student s WHERE NOT EXISTS (SELECT 1 FROM enrollment e WHERE e.student_id = s.student_id);
4.6 Aggregates with GROUP BY and HAVING
Task: for every course with at least two students, show the number of students and the average grade.
SELECT course_code, COUNT() AS num_students, ROUND(AVG(grade), 1) AS avg_grade FROM enrollment GROUP BY course_code HAVING COUNT() >= 2;
course_code num_students avg_grade BUS1101 2 59. CSC2101 3 66.
Check: BUS1101 = (70 + 48) / 2 = 59.0; CSC2101 = (78 + 55 + 66) / 3 = 66.33. WHERE cannot replace HAVING here, because the count only exists after grouping.
Counting with an outer join. To count students per department including departments with nobody, count a column from the right-hand table, not * :
SELECT d.dept_name, COUNT(s.student_id) AS students FROM department d LEFT JOIN student s ON s.dept_id = d.dept_id GROUP BY d.dept_name ORDER BY students DESC, d.dept_name;
dept_name students Business 2 Computing 2 Mathematics 0
COUNT(*) would wrongly show 1 for Mathematics, because the LEFT JOIN produces one row (with NULLs) for it. COUNT(column) ignores NULLs.
4.7 Subqueries
Task: names of students who scored above the overall average grade in at least one course.
SELECT first_name FROM student WHERE student_id IN (SELECT student_id FROM enrollment WHERE grade > (SELECT AVG(grade) FROM enrollment));
The overall average is (78 + 64 + 55 + 81 + 70 + 48 + 66) / 7 = 462 / 7 = 66.0. Grades above 66 are 78 (Amina), 81 (Brian) and 70 (Carol), so the result is Amina, Brian, Carol.
Correlated subquery: the top scorer in each course. The inner query is re-evaluated for each outer row, using the outer row's course_code.
SELECT e.course_code, s.first_name, e.grade FROM enrollment e JOIN student s ON s.student_id = e.student_id WHERE e.grade = (SELECT MAX(e2.grade) FROM enrollment e WHERE e2.course_code = e.course_code) ORDER BY e.course_code;
course_code first_name grade BUS1101 Carol 70 CSC2101 Amina 78 CSC2202 Amina 64 MAT1103 Brian 81
4.8 Views, UPDATE and DELETE
A view is a stored query that behaves like a virtual table. It simplifies repeated joins and can hide columns from users.
5.2 Worked example: attribute closure and candidate keys
The closure X⁺ is the set of all attributes that X determines. If X⁺ contains every attribute of the relation, X is a superkey.
Given R(A, B, C, D, E) with F = { A → B, B → C, CD → E }.
Step 1: compute {A}⁺. Start with {A}. A → B adds B: {A, B}. B → C adds C: {A, B, C}. CD → E needs D, which we do not have. So {A}⁺ = {A, B, C}. A is not a key.
Step 2: notice which attributes never appear on a right-hand side. A and D never appear on the right, so nothing can determine them. They must be in every candidate key.
Step 3: compute {A, D}⁺. Start with {A, D}. Add B (A → B), then C (B → C), then E (CD → E). Result {A, B, C, D, E}: all attributes. AD is a superkey.
Step 4: check minimality. {A}⁺ = {A, B, C} and {D}⁺ = {D}; neither alone is a key. So AD is a candidate key , and since A and D must be in every key, it is the only candidate key.
Step 5: which normal form? Prime attributes: A, D. Non-prime: B, C, E. The FD A → B makes the non- prime B depend on part of the key AD, which is a partial dependency. So R is in 1NF but not 2NF.
6. Update anomalies: why we normalize
Consider this single, badly designed table that records course registrations:
student_id student_name course_code course_title lecturer_id lecturer_name grade 1 Amina CSC2101 Database Systems L07 Dr. Kamau 78 1 Amina CSC2202 Computer Networks L12 Ms. Njeri 64 2 Brian CSC2101 Database Systems L07 Dr. Kamau 55
Anomaly What goes wrong in this table Insertion We cannot record a new course and its lecturer until at least one student enrols, because student_id is part of the key and cannot be NULL. Update If CSC2101 is renamed, we must change every row that mentions it. Missing one leaves the database contradicting itself. Deletion If Amina withdraws from CSC2202 and that was its only row, we also lose the fact that Ms. Njeri teaches Computer Networks.
All three anomalies come from redundancy : one fact stored in many places. Normalization removes redundancy by splitting the table so each fact is stored once, while making sure the split is lossless (joining the pieces gives back exactly the original data) and, ideally, dependency-preserving.
7. Normalization step by step
7.1 The starting point: an unnormalized form (UNF)
A paper registration form has one header per student and a list of courses below it. Written as one record per student:
REGISTRATION (student_id, student_name, programme_code, programme_name, { course_code, course_title, credits, lecturer_id, lecturer_name, grade })
The braces { } mark a repeating group : one student has many courses.
For example, Amina's form lists two courses (CSC2101 and CSC2202) under one header, and Brian's lists one.
Business rules (functional dependencies):
student_id → student_name, programme_code programme_code → programme_name
course_code → course_title, credits, lecturer_id (each course has one lecturer) lecturer_id → lecturer_name {student_id, course_code} → grade
7.2 First Normal Form (1NF)
Rule: every attribute holds a single atomic value, there are no repeating groups, and the table has a primary key.
Action: flatten the repeating group so each student-course pair gets its own row. The key becomes the composite {student_id, course_code}.
REGISTRATION_1NF (student_id, student_name, programme_code, programme_name, course_code, course_title, credits, lecturer_id, lecturer_name, grade)
student_id student_name programme_code programme_name course_code course_title credits lecturer_id 1 Amina BIT Business IT CSC2101 Database Systems
1 Amina BIT Business IT CSC2202 Computer Networks
2 Brian BIT Business IT CSC2101 Database Systems
The table is now in 1NF, but it still has all three anomalies from Section 6.
7.3 Second Normal Form (2NF)
Rule: the table is in 1NF and no non-prime attribute is partially dependent on a candidate key. (2NF only matters when a key is composite. A 1NF table with a single-attribute key is automatically in 2NF.)
Find the partial dependencies against the key {student_id, course_code}:
student_name, programme_code, programme_name depend on student_id alone. course_title, credits, lecturer_id, lecturer_name depend on course_code alone. Only grade depends on the whole key.
Action: move each group into its own table, keyed by the part of the key it depends on.
STUDENT (student_id, student_name, programme_code, programme_name) COURSE (course_code, course_title, credits, lecturer_id, lecturer_name) ENROLMENT (student_id, course_code, grade) — student_id and course_code are also foreign keys
Now a course can be added without any student (insertion anomaly fixed for courses), and renaming a course is a one-row change.
7.4 Third Normal Form (3NF)
Rule: the table is in 2NF and no non-prime attribute is transitively dependent on a key. A common formal statement: for every non-trivial FD X → A, either X is a superkey or A is a prime attribute.
Find the transitive dependencies:
In STUDENT: student_id → programme_code → programme_name. In COURSE: course_code → lecturer_id → lecturer_name.
Action: move each transitively dependent attribute into a table keyed by its real determinant.
Table Attributes Primary key Foreign keys PROGRAMME programme_code, programme_name
programme_code none
STUDENT student_id, student_name, programme_code
student_id programme_code → PROGRAMME
Normal form
Condition (must also satisfy the previous form) Problem removed Typical fix
2NF No non-prime attribute depends on part of a candidate key
Partial dependencies Move attributes to a table keyed by the part they depend on
3NF For every non-trivial X → A: X is a superkey, or A is prime
Transitive dependencies Move attributes to a table keyed by their real determinant BCNF For every non-trivial X → Y: X is a superkey
Remaining anomalies from overlapping candidate keys
Decompose on the violating FD (lossless, may lose dependency preservation) 4NF (beyond BCNF)
BCNF and no non-trivial multi-valued dependencies
Independent multi-valued facts in one table
Split each independent multi- valued fact into its own table
SQL item Remember WHERE vs HAVING WHERE filters rows before grouping; HAVING filters groups after COUNT() vs COUNT(col) COUNT() counts rows; COUNT(col) skips NULLs = NULL Never true; use IS NULL / IS NOT NULL INNER vs LEFT JOIN INNER keeps only matches; LEFT keeps all left rows, NULL-filling the right Many-to-many Always needs a junction (bridge) table with a composite key DELETE vs TRUNCATE vs DROP Rows (filterable) / all rows / whole table
9. Practice questions
Questions 1 to 10 are on SQL (use the sample database in Section 4, before the UPDATE and DELETE in 4.9). Questions 11 to 20 are on dependencies and normalization. Answers follow on the next pages.
Write a query that lists every course title with its number of credits, sorted from most to fewest credits, then alphabetically by title. Write a query that shows the total number of credits each student is taking, highest first. Show student_id, first_name and the total. What does SELECT COUNT(dept_id) FROM student; return, and why is it different from SELECT COUNT(*) FROM student;? Write a query that lists courses that have no enrolments at all. Explain why this query fails and correct it: SELECT course_code, AVG(grade) FROM enrollment WHERE AVG(grade) > 60 GROUP BY course_code; Write a statement that adds a column email VARCHAR(100) to the student table. What is the difference between a primary key and a unique constraint? Write a query that returns the names of students enrolled in Database Systems , using a join (not a hard-coded course code). A new requirement says each course may have several prerequisite courses. Design the table needed, with its keys. Which rows would DELETE FROM enrollment WHERE grade < 60; remove from the original data? Define a functional dependency and give one example from the sample database. Given T(P, Q, R, S) with F = { P → Q, Q → R, R → S }, find the candidate key(s) and the highest normal form. Given R(A, B, C, D) with F = { AB → C, C → D }, find the candidate key and the highest normal form. Normalize to 3NF. Given R(A, B, C) with F = { AB → C, C → B }, find all candidate keys. Is R in 3NF? Is it in BCNF? Why is every relation with only two attributes automatically in BCNF? A table ORDER_LINE(order_no, product_no, product_name, qty, unit_price) has key {order_no, product_no}, and product_no → product_name, unit_price. Which normal form is it in? Normalize it to 3NF. State the difference between a lossless and a lossy decomposition. Name the three update anomalies and give a one-line example of each.
A table EMPLOYEE(emp_id, emp_name, dept_no, dept_name, dept_location) has key emp_id. Identify the dependency that breaks 3NF and normalize it. True or false, with a reason: "A table in 3NF is always in BCNF."
Answers
SELECT title, credits FROM course ORDER BY credits DESC, title ASC;
Result: Computer Networks 3, Database Systems 3, Discrete Mathematics 3, Principles of Management
2.
SELECT s.student_id, s.first_name, SUM(c.credits) AS total_credits FROM student s JOIN enrollment e ON e.student_id = s.student_id JOIN course c ON c.course_code = e.course_code GROUP BY s.student_id, s.first_name ORDER BY total_credits DESC;
Result: Amina 6 and Brian 6 (tied, so either may appear first), David 5, Carol 2. (Esther does not appear because an inner join drops students with no enrolments.)
3. COUNT(dept_id) returns 4 because it ignores the NULL in Esther's row. COUNT(*) returns 5 because it counts rows regardless of NULLs.
4.
SELECT c.course_code, c.title FROM course c LEFT JOIN enrollment e ON e.course_code = c.course_code WHERE e.course_code IS NULL;
With the sample data the result is empty: every course has at least one enrolment.
5. Aggregates cannot appear in WHERE because WHERE is evaluated before groups exist. Use HAVING :
SELECT course_code, AVG(grade) AS avg_grade FROM enrollment GROUP BY course_code HAVING AVG(grade) > 60;
Result: CSC2101 (66.3), CSC2202 (64), MAT1103 (81). BUS1101 (59) is excluded.
6. ALTER TABLE student ADD COLUMN email VARCHAR(100); (The word COLUMN is optional in several systems.) 7. Both enforce uniqueness. A table has only one primary key, and its columns cannot be NULL. A table can have many unique constraints, and most systems allow NULLs in a unique column. The primary key is also the usual target of foreign keys.
8.
SELECT s.first_name, s.last_name FROM student s JOIN enrollment e ON e.student_id = s.student_id JOIN course c ON c.course_code = e.course_code WHERE c.title = 'Database Systems';
Result: Amina Hassan, Brian Otieno, David Mutua.