What is a database?
- Published
- 30 Nov 2026
- Subject
- Databases
When you start tracking data for a project, whether logging entries in a spreadsheet by hand or writing a small script to record events, a CSV file is usually the easiest place to put it. One script appends new lines as data comes in, and any other script that needs an answer opens the file and reads through it.
Plain files hold up fine at small scale, until the project grows. Once multiple sources or scripts are writing into the same CSV, a single malformed value like N/A in a numeric column lands straight in the file and breaks downstream code expecting integers. Passing the file to a teammate or another tool quickly turns into separate copies that drift out of sync. On top of that, reading and searching a plain file gets slower as it grows. Every lookup has to scan the file from top to bottom, which goes unnoticed on a few hundred rows and turns slow once the file reaches millions of lines and hundreds of megabytes.
Around that point, people start telling you, "just move the data into a database!" and you have no idea where to start.

Search online and you immediately run into a pile of overlapping terms: database, DBMS, database engine, storage engine, and database system. Even when you find the accepted definitions, they leave the real questions unanswered:
- Database: the organized collection of data itself. Okay, but where does that data sit, and what does it look like?
- DBMS (database management system): the full software that manages the data. What kind of software is it, and how do you run it?
- Database engine (or storage engine): the core layer inside a DBMS that reads and writes the data. What does that engine do in code, and how is it separate from the rest of the DBMS?
- Database system: the database, the DBMS, and the applications using them together. How do those pieces connect and talk to each other?
Wikipedia's opening paragraph on "database" notes how loosely people use "database" to mean the DBMS, the database system, or an application using it. None of those definitions show what you open, run, or write in code.
That is what this post and the series after it are for. Over this series, we are going to build a DBMS in Python called BigishDatabaseManagementSystem, or bidbms, starting with the database engine itself before adding outer layers like a network server or SQL interface. In this first post, bidbms puts Python code in front of plain CSV files so programs can define a table's structure, insert rows with type checks, and read and filter rows back out. Updating existing rows, serving multiple writers, and finding records without scanning every line will come as we expand the engine across later posts. Code for this post lives at github.com/jackschultz/bidbms.
The files: tables and the catalog
Even when a DBMS manages your data, the database (remember, "the organized collection of data itself"!) is still, simply, files saved in a folder on a computer, whether that is your laptop or a server. For bidbms, we will say that the whole database needs to be in a single folder of plain CSV files. That's right, CSV files in a folder can count as a database. And to start, we will need two kinds of CSV files in that folder: one file per table to store the data, and one shared catalog file to record the structure of every table.
Tables (readings.csv)
Imagine you had sensors in the wild that would gather environmental readings around Milwaukee. The file, readings.csv, might look like the following.
taken_at,location,metric,value
2026-11-30 07:00,Bay View,temp_f,31
2026-11-30 07:00,Bay View,pm25,9
2026-11-30 07:00,Milwaukee,pm25,11
2026-11-30 07:00,Wauwatosa,temp_f,29
2026-11-30 07:00,Brown Deer,temp_f,28
2026-11-30 08:00,Bay View,temp_f,33
2026-11-30 08:00,Bay View,pm25,12
2026-11-30 08:00,Milwaukee,pm25,14
2026-11-30 08:00,Wauwatosa,temp_f,30
2026-11-30 08:00,Brown Deer,temp_f,29
This file structure will be what we call a table. Relational databases organize data into tables, made of named columns and rows of individual records. In most relational databases, every column holds one type of value, such as text or an integer, and each row holds one value per column.[1] Each row in our readings table has four columns: taken_at for the time, location for where the reading was taken, metric for what was measured (pm25 for fine-particle air quality or temp_f for temperature in Fahrenheit), and an integer value. We will store taken_at as plain text for now until a later post adds real timestamps with time zones.
Most databases keep several tables side by side, such as readings for sensor measurements and locations for station details. In bidbms, each table will be its own CSV file inside the data folder: readings.csv today, and something like locations.csv later.
The catalog (_catalog.csv)
Storing each table in its own CSV file leaves an obvious gap: line 1 of readings.csv lists the column names, and nothing more. A standalone CSV has no built-in way to record that value must be an integer, or to list which files in the folder belong to the database.
An engine could try to guess on every read by listing *.csv files and scanning rows to infer column types, the way quick analysis tools do. That approach breaks down for a database. Scanning a whole file just to guess types is slow, an empty table gives nothing to inspect, and guessing on read cannot stop a script from writing N/A into a numeric column in the first place.
Relational databases avoid guessing by declaring structure up front in a catalog (PostgreSQL uses pg_catalog and SQLite uses sqlite_schema). In bidbms, the catalog will be a second CSV file in the same database folder called _catalog.csv, with three columns (table, column, and type) and one row per column of every user table. After creating readings, _catalog.csv will hold four rows:
table,column,type
readings,taken_at,str
readings,location,str
readings,metric,str
readings,value,int
Putting both files in one folder gives us the database piece of the system: readings.csv stores the rows, and _catalog.csv stores the rules for every table in that folder.
The engine
With the files clear, we can build the database engine that manages them from scratch, starting from an empty folder. Our engine lives in bidbms/engine.py as a BIDBMS class. Creating a BIDBMS instance takes only one argument, the folder holding the files (data_dir, as a string or Path). Because one folder can hold many tables, each table method takes the table's name first. Methods that return data return plain Python dictionaries ({"location": "Bay View", ...}) rather than application-specific classes, keeping the engine separate from any one program.
class BIDBMS:
def __init__(self, data_dir: str | Path) -> None: ...
def create_table(
self, table: str, columns: dict[str, type]
) -> None: ...
def insert(
self, table: str, /, **values: str | int
) -> dict[str, str | int]: ...
def find_by(
self, table: str, /, **filters: str | int
) -> list[dict[str, str | int]]: ...Creating a table
The top of engine.py holds the supported types, the naming rule, the catalog's own three columns, and the code that reads _catalog.csv into a dictionary of tables:
TYPES: dict[str, type] = {"int": int, "str": str}
# Lowercase letters, digits and underscores, starting with a letter.
NAME = re.compile(r"[a-z][a-z0-9_]*")
CATALOG = "_catalog"
CATALOG_COLUMNS: dict[str, type] = {
"table": str,
"column": str,
"type": str,
}
class BIDBMS:
def __init__(self, data_dir: str | Path) -> None:
self.data_dir = Path(data_dir)
def _load_catalog(self) -> dict[str, dict[str, type]]:
catalog = self.data_dir / f"{CATALOG}.csv"
tables: dict[str, dict[str, type]] = {
CATALOG: CATALOG_COLUMNS
}
for row in self._scan(catalog, CATALOG_COLUMNS):
if row["type"] not in TYPES:
raise ValueError(f"Unsupported type: {row['type']}")
columns = tables.setdefault(row["table"], {})
columns[row["column"]] = TYPES[row["type"]]
return tables
To define and save a new table, a caller passes a table name and a dictionary mapping each column name to a supported Python type (int or str for now) in column order, such as db.create_table("readings", {"taken_at": str, "location": str, "metric": str, "value": int}). create_table takes four steps:
- It validates the table name, column names, and types before touching the filesystem.
- If
_catalog.csvdoes not exist yet, it creates the data folder and writes the catalog's header row, then loads the catalog and checks that the table does not already exist. - It creates an empty
readings.csvwith its header row (taken_at,location,metric,value), failing if that file already exists. - It appends the four column rows to
_catalog.csv.
def create_table(
self, table: str, columns: dict[str, type]
) -> None:
if not NAME.fullmatch(table):
raise ValueError(f"Bad table name: {table}")
if not columns:
raise ValueError("A table needs at least one column")
names = {t: name for name, t in TYPES.items()}
for col, col_type in columns.items():
if not NAME.fullmatch(col):
raise ValueError(f"Bad column name: {col}")
if col_type not in names:
raise ValueError(
f"Unsupported type for {col}: {col_type}"
)
catalog = self.data_dir / f"{CATALOG}.csv"
if not catalog.exists():
self.data_dir.mkdir(parents=True, exist_ok=True)
catalog.write_text(
",".join(CATALOG_COLUMNS) + "\n", encoding="utf-8"
)
tables = self._load_catalog()
if table in tables:
raise ValueError(f"Table already exists: {table}")
path = self.data_dir / f"{table}.csv"
with open(path, "x", newline="", encoding="utf-8") as f:
csv.writer(f, lineterminator="\n").writerow(columns)
with open(catalog, "a", newline="", encoding="utf-8") as f:
writer = csv.writer(f, lineterminator="\n")
for col, col_type in columns.items():
writer.writerow([table, col, names[col_type]])
The catalog is itself a table. It is a CSV file with a header, read by the same _scan method as readings.csv, shown below under Reads. As a result, find_by can query it, and db.find_by("_catalog", table="readings") returns the four catalog rows for readings as dictionaries.
Table and column names may use only lowercase letters, digits, and underscores, starting with a letter. Because of that first letter, no user table can collide with _catalog.[2] Only create_table writes to the catalog, and insert refuses to.
Inserts
To insert a row, a program says which table it goes in, and gives each column's name and value.
db.insert(
"readings",
taken_at="2026-11-30 07:00",
location="Bay View",
metric="temp_f",
value=31,
)
insert then takes five steps:
- It refuses
_catalog, which onlycreate_tablechanges. _load_catalogreads_catalog.csv, and_pathrefuses any table the catalog does not list and returns its CSV path._validaterefuses an unknown column or a value of the wrong type.- It refuses a row with a column missing.
- It opens
readings.csvin append mode and writes one new row at the end, leaving every existing row untouched.
Both insert and find_by share _path and _validate:
def _path(
self, table: str, tables: dict[str, dict[str, type]]
) -> Path:
if table not in tables:
raise ValueError(f"Unknown table: {table}")
return self.data_dir / f"{table}.csv"
def _validate(
self, columns: dict[str, type], values: dict
) -> None:
for col, val in values.items():
if col not in columns:
raise ValueError(f"Unknown column: {col}")
if type(val) is not columns[col]:
raise TypeError(
f"{col} must be {columns[col].__name__}"
)
def insert(
self, table: str, /, **values: str | int
) -> dict[str, str | int]:
if table == CATALOG:
raise ValueError("Use create_table to add a table")
tables = self._load_catalog()
path = self._path(table, tables)
columns = tables[table]
self._validate(columns, values)
missing = [c for c in columns if c not in values]
if missing:
raise ValueError(f"Missing columns: {missing}")
row = {col: values[col] for col in columns}
with open(path, "a", newline="", encoding="utf-8") as f:
writer = csv.writer(f, lineterminator="\n")
writer.writerow(row.values())
return row
The / in insert and find_by makes table positional-only, so a table can also have a column named table, as _catalog does.
Reads
To read rows, a program names the table and gives the values to match as column=value pairs, such as db.find_by("readings", metric="pm25"). _load_catalog, _path, and _validate check the table name, column names, and filter types first. find_by then reads the table through _scan, which opens readings.csv and checks that its header still matches the catalog. For each row, _scan turns every value into its column's type, so '9' comes back as 9. find_by keeps the rows where every filter matches, which for metric="pm25" is four rows (Bay View and Milwaukee, at 07:00 and 08:00).
def _scan(
self, path: Path, columns: dict[str, type]
) -> Iterator[dict[str, str | int]]:
with open(path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
if reader.fieldnames != list(columns):
raise ValueError(
f"{path.name} header {reader.fieldnames} "
f"does not match catalog {list(columns)}"
)
for row in reader:
yield {c: columns[c](row[c]) for c in columns}
def find_by(
self, table: str, /, **filters: str | int
) -> list[dict[str, str | int]]:
tables = self._load_catalog()
path = self._path(table, tables)
columns = tables[table]
self._validate(columns, filters)
return [
row
for row in self._scan(path, columns)
if all(row[c] == v for c, v in filters.items())
]
Because the engine checks rows one after another from the start of the file, databases call this a sequential scan. That is fine for ten readings. Indexes, a few posts from now, are how a database avoids reading them all.
That answers the question from the start about how a database engine separates from the rest of a DBMS. Right now bidbms has no SQL parser, query planner, or network server wrapped around it, so this engine is the entire DBMS for this first post. Full DBMSs like PostgreSQL layer those outer pieces on top of an underlying storage engine.
Using the DBMS
Any program using our database talks only to BIDBMS methods and never opens the CSV files itself. The files could change to a binary format without the program changing. In return, bidbms checks what it is given. insert refuses a missing column, an unknown column, or a value of the wrong type. Every read checks that the table's header still matches the catalog, so a column renamed by hand in readings.csv is caught at the next read. What it does not handle yet is a crash halfway through a write, or two programs writing at once.
In the folder layout below, the demo splits into the three parts of a database system: the reusable engine library (bidbms/), the application project sitting beside it (sensor-app/), and the database files inside sensor-app/data/. The two folders sit side by side here only so PYTHONPATH=.. finds bidbms without installing a package.
Usually the engine and application live apart. SQLite comes with Python as the sqlite3 module, and a PostgreSQL server runs on its own, reached through a driver installed with pip. The data folder can sit anywhere the application points it, and .gitignore keeps it out of version control.
├── bidbms/
│ ├── __init__.py
│ └── engine.py
└── sensor-app/
├── .gitignore # ignores data/
├── create.py
├── query.py
├── sample_readings.py
└── data/ # made by create.py
├── _catalog.csv
└── readings.csv
create.py creates the table and inserts the ten readings, which sample_readings.py holds as a list of tuples.
from bidbms import BIDBMS
from sample_readings import READINGS
db = BIDBMS("data")
db.create_table(
"readings",
{
"taken_at": str,
"location": str,
"metric": str,
"value": int,
},
)
for taken_at, location, metric, value in READINGS:
db.insert(
"readings",
taken_at=taken_at,
location=location,
metric=metric,
value=value,
)
Run from sensor-app/, create.py leaves two files in data/. Running it a second time stops at create_table with ValueError: Table already exists: readings, and writes nothing.
$ PYTHONPATH=.. python3 create.py
$ ls data
_catalog.csv readings.csv
query.py finds the latest temperature reading in Bay View.
from bidbms import BIDBMS
db = BIDBMS("data")
bay_view_temps = db.find_by(
"readings", location="Bay View", metric="temp_f"
)
latest = max(bay_view_temps, key=lambda r: r["taken_at"])
print(latest)
# {'taken_at': '2026-11-30 08:00', 'location': 'Bay View',
# 'metric': 'temp_f', 'value': 33}
max can compare taken_at as text because text compares character by character from the left. Every time has the same zero-padded form, YYYY-MM-DD HH:MM, so alphabetical order is also time order.
Notice where the work splits right now. bidbms handles filtering by location and metric, while finding the latest reading (max(..., key=lambda r: r["taken_at"])) still lives in application code because our engine does not support sorting, limits, or aggregations yet. Deciding which work belongs inside the engine (sorting, limits, aggregations, joins) versus staying in application code is a big part of building out a full DBMS, and we will move more of those pieces inside bidbms as this series continues.
Other DBMSs
Stripped down to plain CSVs, bidbms follows the same basic split other DBMSs use. The table below compares all three on the same ten readings, measured with SQLite 3.53 and PostgreSQL 18.6.
| bidbms | SQLite | PostgreSQL | |
|---|---|---|---|
| Runs | inside the application | inside the application | as its own server |
| Connect with | a folder | a file path | a connection string |
| Create a table with | create_table | CREATE TABLE | CREATE TABLE |
| Structure kept in | _catalog.csv, a row per column | sqlite_schema, a row per table | pg_attribute, a row per column (plus six system columns) |
| Readings kept in | readings.csv, 390 bytes | readings.db, 8,192 bytes, with the catalog | a numbered file under base/, 8,192 bytes |
| Keep only Bay View temperatures | find_by | WHERE | WHERE |
| Pick the latest of them | Python's max, in the application | ORDER BY taken_at DESC LIMIT 1 | the same SQL |
SQLite and PostgreSQL replace CSVs with binary files divided into fixed-size chunks called pages, so they can read and update small parts of a table without rewriting the whole file. SQLite's pages are 4,096 bytes by default (page 1 holds sqlite_schema and page 2 holds readings, giving the 8,192-byte file above). PostgreSQL's pages are 8,192 bytes by default, and its catalog tables have files of their own. We will cover how pages work in a later post. Even with pages, a database is still just files on the filesystem.
Where an ORM fits
If you have used an ORM (object-relational mapper), db.find_by("readings", location="Bay View") may look familiar. Here is the question query.py asks, the latest temperature reading in Bay View, in three ORMs. Each one, run against the same ten readings in SQLite, returned the 08:00 reading of 33.
| Language | ORM | The call |
|---|---|---|
| Python | Django 6.1 | Reading.objects.filter(location="Bay View", metric="temp_f").order_by("-taken_at").first() |
| Ruby | Active Record 8.1, from Rails | Reading.where(location: "Bay View", metric: "temp_f").order(taken_at: :desc).first |
| JavaScript | Prisma 7.10 | prisma.reading.findFirst({ where: { location: "Bay View", metric: "temp_f" }, orderBy: { taken_at: "desc" } }) |
An ORM is not a DBMS, though. None of the three reads a database file. Each is a library inside the application that turns its call into SQL and sends the SQL to SQLite, which does the reading. Django logged this SQL, shown here across several lines:
SELECT "readings"."id", "readings"."taken_at",
"readings"."location", "readings"."metric",
"readings"."value"
FROM "readings"
WHERE ("readings"."location" = 'Bay View'
AND "readings"."metric" = 'temp_f')
ORDER BY "readings"."taken_at" DESC
LIMIT 1
All three ORMs passed 'Bay View' and 'temp_f' separately as query parameters (Django's query log fills them in for display), while Active Record and Prisma generated the same WHERE, ORDER BY, and LIMIT with their own quoting. In all three ORM runs, the readings table also had an id column. Django and Active Record add one by default, and Prisma refuses a model without a unique field.
bidbms is not an ORM either. An ORM keeps no data of its own, and it maps rows to application models or typed objects, such as a Reading. bidbms stores the rows itself and returns plain dictionaries, so it does SQLite's job here, not the ORM's. It looks like an ORM only because it has no SQL yet, so method calls are its whole interface.
Conclusion
We now have all three pieces of a working database system sitting side by side: sensor-app/data/ holds the files, bidbms/ wraps a catalog, inserts, and reads around them, and create.py and query.py talk through that interface without ever touching a CSV directly.
We started with plain files in the filesystem, and we ended with files in the filesystem too. Putting a single piece of software in front of them gives every program one shared boundary, enforcing table structure now and, as the engine grows, coordinating multiple writers and finding specific entries without scanning everything.
This CSV version leaves out plenty of features that production databases need, and I'm sure those with experience have been yelling at their screens about them. The next post starts with one of those gaps: bidbms cannot change or delete a row yet, since no row has an ID to say which one. As we add IDs, richer queries, and binary pages inside bidbms across the coming posts, the application will gain new methods to call while never opening the underlying files directly.
-
SQLite is the well-known exception: by default it lets you store
'N/A'in anINTEGERcolumn unless the table is created withSTRICT.bidbmschecks types strictly. ↩ -
SQLite reserves a prefix, and refuses any table name that starts with
sqlite_. PostgreSQL accepts a table namedpg_readings, because its own catalog tables live apart, in a namespace calledpg_catalog. It refuses any new namespace whose name starts withpg_. Both refuse a SQL keyword such asselectas a table name, unless it is in double quotes. ↩