smartyfy.mrindigi.com

Python Master Course V2 — 084. Creating Tables and Constraints

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · LESSON 084 OF 200 · MODULE 09 — DATABASES AND SQLITE

Creating Tables and Constraints

Study time: 70–100 minutes. Prerequisites: functions, exceptions, structured data and Lesson 83.

Course hub

Video

Video not yet available. This section is reserved for a verified lesson video URL or embedded player.

Learning outcomes

Define primary keys, uniqueness and checks. Explain the concept, trace a sample program, test a boundary condition and implement a small real-world solution.

Detailed explanation

Constraints enforce business invariants at the database boundary. CHECK, NOT NULL, UNIQUE and foreign keys prevent classes of invalid records.

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: Creating Tables and Constraints

Constraints protect the stored state

Application validation gives users helpful feedback, but a database may have several writers. Constraints provide a final boundary that every writer must respect. NOT NULL requires a value, UNIQUE prevents repeated values in the constrained columns, PRIMARY KEY identifies rows and CHECK evaluates a condition. A foreign key links a value to an existing referenced row when enforcement is enabled.

A subtle SQLite rule matters for stock: CHECK(qty >= 0) rejects false results, but a NULL result does not violate the check. Therefore that expression alone permits missing quantity. Combine it with NOT NULL. Ordinary SQLite column declarations also provide type affinity rather than strict Python-like type checking; declaring INTEGER does not by itself reject every other storage type.

Python example

import sqlite3
from contextlib import closing

with closing(sqlite3.connect(":memory:")) as db:
    db.execute("""CREATE TABLE products (
        id INTEGER PRIMARY KEY,
        sku TEXT NOT NULL UNIQUE CHECK(length(trim(sku)) > 0),
        qty INTEGER NOT NULL CHECK(typeof(qty) = 'integer' AND qty >= 0)
    )""")
    with db:
        db.execute("INSERT INTO products(sku, qty) VALUES (?, ?)", ("PEN", 0))
    for sku, qty in [("BOOK", None), ("BAG", -1), ("CUP", 1.5), ("PEN", 2)]:
        try:
            with db:
                db.execute("INSERT INTO products(sku, qty) VALUES (?, ?)", (sku, qty))
        except sqlite3.IntegrityError:
            print("rejected", sku)
    print(db.execute("SELECT sku, qty FROM products").fetchall())

Expected output

rejected BOOK
rejected BAG
rejected CUP
rejected PEN
[('PEN', 0)]

BOOK fails NOT NULL, BAG fails the nonnegative check, CUP fails the integer-storage check and the second PEN fails uniqueness. Every attempted insert has its own transaction, so a failed attempt does not undo the earlier committed product. The exact SQLite error message may differ by version; tests should assert the error category and unchanged state instead of relying on a whole message string.

Storage rules are not input-format rules

SQLite may convert a numeric string such as "3" to integer storage because of affinity before evaluating typeof. That can be acceptable for storage integrity, but it does not prove the original application input was an integer. If booleans, numeric strings or fractional values are forbidden at the Python boundary, check them before binding parameters. SQLite trim here removes ordinary spaces; reject other whitespace-only SKUs in application validation if they are forbidden. Decide separately whether SKUs are case-sensitive; a UNIQUE text column does not automatically implement every business notion of equivalent codes.

For related tables, enable PRAGMA foreign_keys=ON on each connection outside a transaction and verify it returns one. Add NOT NULL when a reference is mandatory. Decide what should happen when a referenced product is deleted: blocking deletion, cascading deletion and preserving a historical snapshot have different consequences. Do not choose cascading deletion for an audit ledger merely because it is convenient.

A useful project acceptance set tries zero stock, one stock, negative stock, missing stock, a fraction, a duplicate SKU and a blank SKU. Check both the exception and the number of stored rows after each failure. SQLite STRICT tables are another option on supporting SQLite versions, but this example uses explicit constraints so the teaching baseline does not silently depend on that feature.

Runnable Python example

Requires Python 3.10+. Save as lesson84.py, run with python lesson84.py or python3 lesson84.py. Examples use only the standard library.

import sqlite3
from contextlib import closing
with closing(sqlite3.connect(':memory:')) as c:
    c.execute('CREATE TABLE stock(id INTEGER PRIMARY KEY, qty INTEGER NOT NULL CHECK(qty>=0))')
    c.execute('INSERT INTO stock(qty) VALUES (0)')
    print(c.execute('SELECT qty FROM stock').fetchone()[0])

Expected output:

0

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 product table with unique codes and nonnegative stock constraints.

  1. Specify the data schema and constraints in a small requirements table.
  2. Create a sample dataset with typical, boundary and invalid records.
  3. Implement separate functions for validation, transformation and reporting.
  4. Handle expected errors with informative messages.
  5. Write three automated tests and compare actual with expected results.
  6. 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 does CHECK(qty >= 0) need NOT NULL too?

A NULL quantity makes the check expression unknown, and SQLite permits a NULL check result. NOT NULL closes that separate gap.

Does INTEGER guarantee that Python callers supplied an int?

No. SQLite affinity may convert other values to integer storage. Enforce the incoming Python type separately if the contract requires it.

Why does the example reject 1.5?

It remains real storage and fails typeof(qty) = 'integer'. The nonnegative condition alone would accept it, so both storage type and range matter.

Why commit the first PEN before testing bad rows?

It establishes a stable valid fixture. Each invalid insertion can then roll back independently without accidentally removing the setup data.

Is UNIQUE enough to reject a blank SKU?

No. An empty string is a value and can be unique. The additional check rejects empty or space-only text; other whitespace needs an explicit application policy. NOT NULL only rejects missing values.

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.

Course hub · Previous Lesson 83 in course 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.