Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 12 / Topic 7 of 11

Databases: why and what

In Part 8 you saved data to JSON files. That is fine for a to-do list. But as data grows, a JSON file must be read and written whole every time, two programs writing at once can corrupt it, and questions like "total spend per city" need loops you write yourself. A database is a program (or file) built to store a lot of data safely and answer questions about it fast. Think of a JSON file as a notebook and a database as a library with a catalogue: you ask for exactly what you need.

JSON file Database (SQLite)
Read one record Load the whole file Ask for just that row
Questions ("sum per city") Write loops yourself One SQL query
Two writers at once Can lose or corrupt data Safe (transactions)
Rules (no empty names) You check by hand The database checks

A relational database keeps data in tables:

  • A table is like one spreadsheet sheet, e.g. customers.
  • A column is one field with a type: name TEXT, amount INTEGER.
  • A row is one record: (1, 'Asha', 'Pune').
  • A primary key is a column whose value is unique for every row, like a roll number. It is how you point at exactly one row.
  • A foreign key is a column that holds another table's primary key, like orders.customer_id pointing to customers.id. It links tables.
customers                        orders
id | name  | city                id | customer_id | item    | amount | ordered_on
---+-------+-------               ---+-------------+---------+--------+-----------
1  | Asha  | Pune                1  | 1           | Thali   | 250    | 2026-07-01
2  | Ravi  | Mumbai              2  | 2           | Biryani | 320    | 2026-07-01
3  | Meera | Pune                3  | 1           | Thali   | 250    | 2026-07-02
                                 ... 6 orders in total

SQLite is a small database that keeps everything in one file (or in memory). It comes with Python as the sqlite3 module, so there is nothing to install.

Done here? The practice set for Part 12 — 8 exercises with solutions — is on the part page.

Search the guide