Python Master Course V2 — 081. Database Fundamentals
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · LESSON 081 OF 200 · MODULE 09 — DATABASES AND SQLITE
Database Fundamentals
Study time: 70–100 minutes. Prerequisites: functions, exceptions, structured data and Lesson 80.
Video
Video not yet available. This section is reserved for a verified lesson video URL or embedded player.
Learning outcomes
Understand relational tables and keys. Explain the concept, trace a sample program, test a boundary condition and implement a small real-world solution.
Detailed explanation
A relational database organizes data in tables with constraints. Primary keys identify rows; foreign keys connect records and support referential integrity.
Engineering workflow: define the input and expected output, choose a representation, enforce constraints, implement the smallest useful operation, test success and failure paths, and document the result. Separate data acquisition from transformation and presentation. Avoid hidden global state and irreversible changes during practice.
Production considerations: validate external inputs, preserve recoverable source data, use explicit types, log failures without exposing secrets, and plan for malformed or missing records. As programs grow, modularize code into functions with clear contracts and add automated regression tests.
Understand and apply: Database Fundamentals
A relational model describes facts and relationships
A table stores rows representing one kind of thing, and columns describe that thing’s attributes. A primary key identifies a row independently of names that may change or repeat. A foreign key records a relationship to another table. Good modeling starts by asking what one row means, which facts can repeat, and which facts must be unique.
Consider students taking courses. One student can take many courses and one course can have many students, so the relationship is many-to-many. An enrollments table connects them. Storing comma-separated course names in a students column makes querying and enforcing uniqueness difficult. Repeating a student’s address on every enrollment creates an update problem: changing one copy may leave the others inconsistent. Separating these facts is a practical introduction to normalization.
Python example
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:")) as db:
db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE courses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL
);
CREATE TABLE enrollments (
student_id INTEGER NOT NULL REFERENCES students(id),
course_id INTEGER NOT NULL REFERENCES courses(id),
PRIMARY KEY (student_id, course_id)
);
""")
with db:
db.execute("INSERT INTO students VALUES (?, ?)", (1, "Asha"))
db.executemany("INSERT INTO courses VALUES (?, ?)", [(10, "Python"), (20, "SQL")])
db.executemany("INSERT INTO enrollments VALUES (?, ?)", [(1, 10), (1, 20)])
print(db.execute("SELECT * FROM enrollments ORDER BY course_id").fetchall())
print(db.execute("PRAGMA foreign_keys").fetchone()[0])
Expected output
[(1, 10), (1, 20)]
1
The composite primary key says the same student-course pair may occur only once, while each individual ID may appear many times. The two foreign keys disallow enrollments referring to nonexistent rows when enforcement is enabled. Enable and verify enforcement for each connection before starting a transaction. The with db block commits successful inserts or rolls them back on an escaping exception; closing handles connection cleanup separately.
Turn business sentences into constraints
“Every enrollment has a student” becomes NOT NULL plus a foreign key. “A student enrolls in a course at most once” becomes uniqueness over the pair. “Students may share a name” means name must not be a unique identity. A course title may need its own uniqueness rule, but do not invent that rule merely because today’s sample titles differ. Database constraints should represent the real domain.
For the project, sketch three boxes, list the columns and underline each primary key. Draw the two one-to-many relationships from students and courses to enrollments. Write two valid enrollment rows, a duplicate pair and an orphan pair. Predict which inserts fail and why before running them. A duplicate raises IntegrityError for uniqueness; an orphan raises IntegrityError for referential integrity.
Normalization does not eliminate every duplicate value, nor does it mean creating the maximum possible number of tables. Its purpose here is to store each independent fact in the appropriate place and connect facts through stable keys. Later lessons show joins for reconstructing reports without duplicating stored student or course details.
Python collection preview
This in-memory check illustrates uniqueness within one list; it is not a database constraint and cannot protect later writes. The database schema above enforces relationships and uniqueness.
Requires Python 3.10+. Save as lesson81.py, run with python lesson81.py or python3 lesson81.py. Examples use only the standard library.
rows=[{'id':1,'name':'Asha'},{'id':2,'name':'Ravi'}]
print(len({r['id'] for r in rows})==len(rows))
Expected output:
True
Walkthrough
Read the imports first, then identify the input and the operation that produces the result. Verify the expected output, change one input, predict the new result and rerun. Explain what should happen if the input is empty, invalid or unavailable.
Guided practical project
Scenario: Design a normalized student enrollment schema with primary and foreign keys.
- Specify the data schema and constraints in a small requirements table.
- Create a sample dataset with typical, boundary and invalid records.
- Implement separate functions for validation, transformation and reporting.
- Handle expected errors with informative messages.
- Write three automated tests and compare actual with expected results.
- Document execution, assumptions and limitations.
Acceptance criteria: reproducible output, safe handling of invalid data, no silent data loss, and clearly documented assumptions. The project is a guided assignment, not a claim that it has been executed here.
Common mistakes and debugging
- Using the wrong data type or assuming input is always valid.
- Failing to validate keys, fields, constraints or encodings.
- Hiding exceptions with a broad catch rather than identifying the cause.
- Changing important records without backups or transaction planning.
- Testing only normal inputs rather than empty and boundary cases.
When debugging, reproduce with a minimal example, inspect the traceback, compare values to the documented contract and add a regression test.
Practice with explained answers
Make a prediction before opening each answer. Then trace the example and explain the result in your own words.
Why is a student name a weak primary key?
Different students can share a name and a person can change their name. A stable ID distinguishes identity from a descriptive attribute.
Why does many-to-many enrollment need a third table?
Each enrollment is one relationship between one student and one course. The linking table represents any number of those pairs without stuffing lists into a single cell.
Does PRIMARY KEY(student_id, course_id) make student_id unique?
No. The pair is unique. Student 1 may appear with course 10 and course 20, but the pair (1, 10) cannot be inserted twice.
What must SQLite do before foreign keys can protect the data?
Enable foreign_keys on the connection before a transaction and verify the setting. Declaring REFERENCES alone is not sufficient if enforcement is disabled.
Where should a course title be updated?
In the courses row identified by that course’s ID. Enrollment rows retain only the reference, so reports see the new title without editing every enrollment.
Mastery checkpoint
Reproduce the sample, explain each operation, complete the guided project and demonstrate at least three test cases. Learner progress is not account-synchronized by this page.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.