Python Master Course V2 — 082. SQL Fundamentals
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · LESSON 082 OF 200 · MODULE 09 — DATABASES AND SQLITE
SQL Fundamentals
Study time: 70–100 minutes. Prerequisites: functions, exceptions, structured data and Lesson 81.
Video
Video not yet available. This section is reserved for a verified lesson video URL or embedded player.
Learning outcomes
Query relational data with SELECT and WHERE. Explain the concept, trace a sample program, test a boundary condition and implement a small real-world solution.
Detailed explanation
SQL describes the result you want. Use parameters for values instead of concatenating user input into SQL strings.
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: SQL Fundamentals
Read SQL as a description of the result
SQL is declarative: SELECT names the columns to return, FROM identifies the source, WHERE restricts rows and ORDER BY defines the presentation order. The database chooses an execution strategy. Unlike a Python loop, you usually describe the whole set you want rather than instructing the engine how to visit each row.
A Python sqlite3 call combines a fixed SQL template with a separate collection of parameter values. Question marks stand for values, not table names or keywords. This separation lets the driver handle quoting correctly and prevents a supplied value from becoming executable SQL syntax. A one-item argument tuple needs a comma: (80,) is a tuple, while (80) is simply the integer 80.
Python example
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:")) as db:
db.execute("CREATE TABLE scores(name TEXT NOT NULL, score INTEGER)")
with db:
db.executemany("INSERT INTO scores VALUES (?, ?)",
[("Asha", 90), ("Ravi", 80), ("Mina", None), ("Ben", 80)])
rows = db.execute("""
SELECT name, score FROM scores
WHERE score >= ?
ORDER BY score DESC, name ASC
""", (80,)).fetchall()
print(rows)
print(db.execute("SELECT name FROM scores WHERE score IS NULL").fetchall())
Expected output
[('Asha', 90), ('Ben', 80), ('Ravi', 80)]
[('Mina',)]
Asha comes first because 90 is highest. Ben precedes Ravi because the name is the explicit tie-breaker for equal scores. Mina is absent from the threshold query because an unknown score cannot satisfy score >= 80. SQL NULL represents missing or unknown data and is not the same as zero or an empty string. Use IS NULL or IS NOT NULL; equality to NULL does not test missingness.
Understand the Python result shape
execute returns a cursor. fetchall returns a list of row tuples, one tuple per row; selected columns determine tuple positions. Selecting only name still yields one-item tuples such as ('Mina',). fetchone returns one row or None when nothing remains. A cursor is consumable: fetching advances it, so a second fetchall does not replay rows already read.
Use explicit column names instead of SELECT * in application interfaces so an added schema column does not unexpectedly change the result shape. Without ORDER BY, do not rely on insertion order or a previous run’s arrangement. For large results, iterate over the cursor rather than loading every row with fetchall. Limit and paginate deliberately when the caller needs only a small page.
Practice by changing the threshold to 91, which returns an empty list; then select all names in alphabetical order. Keep sorting choices in a fixed allowlist if the user may choose a sort field, because a placeholder cannot safely substitute a column identifier. Parameterization protects syntax separation; it does not validate whether a negative score is meaningful in your domain.
The project’s first milestone should implement filtering and deterministic sorting using this fixture. A later milestone can count and group results after Lesson 086 introduces aggregation. Test a quoted name such as O'Neil to demonstrate that parameters handle data containing quote characters without hand-built escaping.
Runnable Python example
Requires Python 3.10+. Save as lesson82.py, run with python lesson82.py or python3 lesson82.py. Examples use only the standard library.
import sqlite3
c=sqlite3.connect(':memory:')
c.execute('CREATE TABLE scores(name TEXT, score INTEGER)')
c.execute('INSERT INTO scores VALUES (?,?)',('Asha',90))
print(c.execute('SELECT name FROM scores WHERE score>=?',(80,)).fetchall())
c.close()
Expected output:
[('Asha',)]
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: Write parameterized queries for filtering and deterministic ordering of student scores. Extend the project with aggregation after Lesson 086.
- 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.
What is the purpose of the comma in (80,)?
It creates a one-element tuple of parameter values. Parentheses alone only group the integer, so (80) is not the required one-item sequence.
Why is Mina excluded from score >= 80?
Her score is NULL, meaning unknown. The comparison does not evaluate to true. Use score IS NULL to select missing scores explicitly.
What does fetchone return when a lookup finds no rows?
None. Check it before indexing a column; attempting None[0] is an application error, not a special database result.
Can SELECT ? FROM scores choose the name column?
No. The parameter is a literal value and would be repeated for each row. Dynamic identifiers require an explicit allowlist and carefully selected fixed SQL fragments.
Why add name ASC after score DESC?
It defines the order of tied scores. Without an explicit tie-breaker, equally ranked rows may appear in a different order, which makes reports and pagination unpredictable.
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.