smartyfy.mrindigi.com

Python Master Course V2 — 086. Queries, Filtering and Aggregation

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — DATABASES AND SQLITE · LESSON 086 / 200

Queries, Filtering and Aggregation

Estimated study: 80–110 minutes · Prerequisite: preceding lesson, functions, exceptions and structured data.

Course hub

Video lesson

Video not yet available; this area is reserved for a verified video link or player.

Learning outcomes

Use WHERE, ORDER BY, COUNT and GROUP BY. Explain the technical mechanism, interpret outputs, diagnose failures, test edge cases and apply the skill in a realistic system.

Detailed explanation and architecture

SQL aggregation reduces rows into groups; WHERE filters input rows while HAVING filters aggregate groups. Always specify ordering when order matters.

Implementation sequence: define a contract; model inputs and outputs; apply explicit validation; use standard-library tools where possible; handle expected failures; write tests; document assumptions. Keep persistence or networking separate from business decisions and output formatting.

Professional concerns: predictable error handling, security boundaries, data integrity, performance under realistic load, logging without secrets, and reproducible environments. An example that works once is not automatically a production-ready service.

Understand and apply: Queries, Filtering and Aggregation

Filtering rows and filtering groups answer different questions

WHERE decides which individual rows enter a query. GROUP BY gathers those surviving rows into groups, and aggregate functions calculate one result per group. HAVING then filters the groups using their aggregate values. ORDER BY specifies the final order. This order of reasoning helps you predict results even when the database chooses a different physical execution plan.

Suppose sales rows contain category and amount. To exclude nonpositive transactions, filter amount in WHERE. To display only categories with a qualifying total, filter SUM(amount) in HAVING. Putting the row rule only in HAVING would not remove individual nonpositive rows from the sum. Put each business rule at the stage where it actually belongs.

Python example

import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:")) as db:
    db.execute("CREATE TABLE sales(category TEXT NOT NULL, amount INTEGER)")
    with db:
        db.executemany("INSERT INTO sales VALUES (?, ?)",
            [("A", 10), ("A", 20), ("A", None), ("B", 5), ("B", -2), ("C", None)])
    print(db.execute("""
        SELECT category, COUNT(*), COUNT(amount), SUM(amount)
        FROM sales GROUP BY category ORDER BY category
    """).fetchall())
    print(db.execute("""
        SELECT category, SUM(amount) AS total
        FROM sales WHERE amount > ?
        GROUP BY category HAVING SUM(amount) >= ?
        ORDER BY total DESC, category
    """, (0, 10)).fetchall())

Expected output

[('A', 3, 2, 30), ('B', 2, 2, 3), ('C', 1, 0, None)]
[('A', 30)]

For A, three rows exist but only two amounts are known. COUNT(*) is three, COUNT(amount) is two and SUM is thirty. B totals three before filtering because five plus negative two is three. C has one row but no known amount, so COUNT(amount) is zero and SUM is NULL. In the second query, WHERE removes negative and NULL amounts; A totals thirty, B totals five, and HAVING removes B because five is below ten.

Missing values and empty results need a policy

SUM ignores NULL inputs, but an all-NULL or empty set produces NULL rather than zero. COALESCE(SUM(amount), 0) can present zero when that is the intended business meaning. It also collapses “no known measurements” into zero, so use it deliberately. A grouped query on an empty table returns no groups, while an aggregate query without GROUP BY still returns one aggregate row.

Every selected nonaggregate column should identify the group rather than an arbitrary row within it. Selecting category, name and SUM(amount) while grouping only by category is ambiguous if names vary. Some databases reject such queries; SQLite’s permissive behavior is not a reason to depend on an unspecified representative value.

For the sales-summary project, accept minimum row amount and minimum category total as validated parameters. Use an explicit category tie-breaker so equal totals have stable order. Hand-calculate the tiny fixture before using large data, then test a header-equivalent empty table, an all-NULL category, negative adjustments, exact-threshold totals and tied categories. Preserve NULL when the report needs to distinguish missing data from genuine zero sales.

Runnable Python example

Requires Python 3.10+. Save as lesson86.py and run using python or python3. The example uses local or in-memory data and makes no external network request.

import sqlite3
from contextlib import closing
with closing(sqlite3.connect(':memory:')) as c:
    c.execute('CREATE TABLE sales(category TEXT, amount INTEGER)')
    c.executemany('INSERT INTO sales VALUES (?,?)',[('A',10),('A',20),('B',5)])
    print(c.execute('SELECT category,SUM(amount) FROM sales GROUP BY category ORDER BY category').fetchall())

Expected output:

[('A', 30), ('B', 5)]

Reasoning walkthrough

Read the imports and setup, identify the data model, then follow each operation until the final result. Change one input and predict the effect before running it. Consider the behavior with empty data, invalid types and missing resources.

Independent validation example

def positive_count(value):
    if not isinstance(value, int) or isinstance(value, bool) or value <= 0:
        raise ValueError("positive integer required")
    return value
assert positive_count(3) == 3
print("Input validated")

Expected: Input validated. Validation belongs at an explicit application boundary.

Guided real-world project

Build a sales summary with parameterized filters.

  1. Write a specification with data schema, required operations and failure conditions.
  2. Implement a minimal solution using small named functions.
  3. Add input validation and deliberate error responses.
  4. Test typical, boundary and invalid inputs.
  5. Verify the result against an independently calculated expectation.
  6. Document setup, limitations and recovery steps.

Acceptance: deterministic tests, correct handling of rejected data, no undocumented destructive behavior, and a clear explanation of architecture. This project is an assignment; its full implementation has not been independently executed.

Common mistakes and debugging

  • Concatenating untrusted input into SQL or URLs without proper encoding and parameterization.
  • Assuming remote services or databases always succeed.
  • Omitting transaction or timeout boundaries.
  • Confusing transport status with validated application data.
  • Testing only success paths and ignoring empty or malformed responses.

To debug, reproduce the failure, inspect the smallest failing input, check types and constraints, 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 are COUNT(*) and COUNT(amount) different for category A?

COUNT(*) counts all three rows. COUNT(amount) counts only non-NULL amount values, of which A has two.

Where should a minimum category total be tested?

In HAVING, because the total exists after grouping. WHERE filters individual source rows before SUM is calculated.

Why is SUM for category C None in Python?

C has no non-NULL amount, so SQL SUM returns NULL. sqlite3 represents that value as Python None.

Does COALESCE(SUM(amount), 0) always preserve meaning?

No. It replaces an unknown or absent total with zero. That is useful only when the report’s contract deliberately treats those cases the same.

Why is a category tie-breaker useful after sorting by total?

Equal totals otherwise have no required order. A secondary category ordering makes reports and paginated results predictable.

Mastery checkpoint

Reproduce the sample, explain the design, complete the guided project, document three test cases and identify a realistic failure mode. No video, certificate or account-synced completion is claimed.

Course hub · Previous lesson 85 in hub · Continue with the next published lesson using the lesson navigation.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.