Sub topic 1
What a Database Is and Why Applications Need One
Prerequisites
This chapter assumes you have the following background:
- You have worked with spreadsheets or other tabular data, and you know what rows, columns, and cells are.
- You can read short code snippets in any language, including a few lines of SQL.
- You have a general idea of what it means for an application to store data, such as a shop that remembers its customers.
You do not need to have installed or used a database before. The SQL in this chapter is there to show ideas, and the later chapters explain each statement in detail.
What a database is
A database is an organized collection of data that is stored and managed so that programs can read, add, change, and remove that data reliably. The word has two parts that people often mix up:
- The data itself: the customers, orders, and products you want to keep.
- The software that manages the data, called a database management system (DBMS). PostgreSQL, MySQL, and SQLite are examples.
In everyday speech, "the database" often means both. When the difference matters, this tutorial says "database" for the stored data and "DBMS" for the software.
A database is more than a pile of files. A DBMS gives you a defined way to describe the data, rules that keep the data valid, a query language to ask questions, and guarantees about what happens when several users or a crash interfere with each other.
Why an application cannot just use variables
Every application handles data while it runs. The question is where that data lives. The simplest place is memory, such as a list or dictionary in your program. Memory has a basic limit: it is lost when the program stops or crashes. An online shop that forgot every order on restart would be useless.
So applications need persistence: data that survives after the program that created it has ended. Persistence is the first reason to use a database, but not the only one.
Other needs appear quickly as an application grows:
- Sharing. A web application runs many server processes, and many users act at the same time. They must all see the same data.
- Size. Data can grow larger than memory. You need to find a few rows among millions without loading everything.
- Correctness. An order must refer to a customer who exists. An email address must not be registered twice. A price must not be negative.
- Concurrency. Two users buying the last item at the same moment must not both succeed.
- Recovery. If the machine loses power halfway through an operation, the data must not be left half changed.
A database is the component built to meet these needs, so every application does not have to rebuild them.
The alternative: storing data in files
Before choosing a database, it helps to see what happens without one. Suppose you store customers in a CSV file.
import csv
# Append a customer to a CSV file, then look one up by email.
def add_customer(path, customer_id, name, email):
with open(path, "a", newline="") as f:
csv.writer(f).writerow([customer_id, name, email])
def find_by_email(path, email):
with open(path, newline="") as f:
for row in csv.reader(f):
if row[2] == email:
return row
return None
add_customer("customers.csv", 1, "Ada Lovelace", "[email protected]")
print(find_by_email("customers.csv", "[email protected]"))This works for a small demo. It also fails in several ways:
- Lookup is a full scan.
find_by_emailreads the file from the top every time. With ten million rows, each lookup is slow. - Nothing prevents duplicates. Calling
add_customertwice with the same email silently creates two rows. - Concurrent writes can corrupt the file. Two processes appending at once can interleave their bytes or overwrite each other.
- A crash can leave partial writes. A half-written line may break every later read.
- Relationships are manual. To connect an order file to a customer file, you write the matching code yourself, and nothing stops an order from pointing to a customer who was deleted.
- Every program parses the format itself. If another service reads the same file, both must agree on column order and quoting rules.
You can fix each problem by writing more code, but the combined result is a small, poorly tested database. A DBMS provides these features in software that has been tested for decades.
What a DBMS gives you
The features that matter for applications fall into a few groups. Later chapters cover each one in depth.
| Need | What the DBMS provides | Where this tutorial covers it |
|---|---|---|
| Describe the data | A schema of tables, columns, and types | Tables, rows, columns, and the schema |
| Keep data valid | Constraints such as primary keys, foreign keys, NOT NULL, UNIQUE, CHECK | Constraints that protect data integrity |
| Ask questions | A query language (SQL) that states what you want, not how to find it | Reading and writing data with SQL |
| Combine data | Joins across related tables | Combining tables with joins |
| Stay consistent | Transactions with ACID guarantees | Transactions and ACID guarantees |
| Stay fast | Indexes and a query planner | Indexes and the cost of speed |
Two ideas in this table deserve emphasis now, because they separate a database from a file.
Declarative queries. In the Python example you wrote the loop that finds the row. In SQL, you describe the result and the DBMS decides how to compute it:
SELECT name, email
FROM customers
WHERE email = '[email protected]';The same statement works whether the table has ten rows or ten million. The DBMS may scan the table, use an index, or pick another plan. You do not change your application code when the plan changes.
Rules that live with the data. A constraint is enforced by the DBMS for every program that connects, not just for the one application you wrote. A bug in a script, or a manual fix typed at a console, still cannot break the rule.
How an application talks to a database
Most databases run as a separate process, called a server. Your application is a client. It opens a connection, sends a statement as text, and receives results.
Some databases, such as SQLite, run inside your application process and store everything in one file. The application still sends SQL and receives results, but there is no separate server. The ideas in this tutorial apply to both designs.
The application never opens the data files directly. This indirection is what lets the DBMS coordinate many clients, enforce rules, and change its storage format without breaking applications.
A first look at a relational database
There are several kinds of databases. Document stores keep nested documents, key-value stores map a key to a value, and graph databases focus on connections. This tutorial covers the relational kind, which is the most widely used for business data.
A relational database stores data in tables. Each table has named columns, and each row holds one record. Tables are linked by shared values called keys, rather than by copying data from one place to another.
Here is a small example, which later chapters explain piece by piece:
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0)
);Even without knowing every keyword, you can read the intent:
customersandordersare two separate tables.PRIMARY KEYmarks the column that identifies each row.NOT NULLmeans a value is required.UNIQUEmeans no two customers can share an email.REFERENCES customers (customer_id)means every order must point to a real customer.CHECK (total_amount >= 0)rejects negative totals.
The database now enforces all of these rules. The CSV example could not do any of that.
Common misconceptions and edge cases
A database is not the same as a spreadsheet. A spreadsheet is built for a person to look at and edit cells. A database is built for programs to read and write concurrently, with typed columns, enforced rules, and queries over millions of rows. A table does look like a sheet, which is why the comparison is useful at first, but a spreadsheet has no concept of a foreign key, a transaction, or an enforced type.
"Relational" does not mean "relationships between tables." The name comes from the mathematical term relation, which is the formal name for a table. The next chapter explains this. Relationships between tables are an important feature, but they are not the origin of the word.
Not every application needs a database. A script that processes one file and exits does not need one. A small configuration file is fine as a file. A database pays off when data must persist, be shared, be queried in varied ways, or be kept consistent.
A database does not remove the need to design. The DBMS enforces the rules you declare. If you declare none, it stores whatever you send. Good design, such as choosing keys and constraints, is what makes a database trustworthy.
A DBMS adds operational cost. A server has to be installed, secured, backed up, and upgraded. Connections, credentials, and schema changes are new things to manage. For a single-user tool, an embedded database like SQLite gives most of the benefits with little of this cost.
Summary
A database is organized, persistent data managed by a DBMS. Applications need one because memory is temporary and files give no help with sharing, validation, speed, concurrency, or crash safety. A DBMS supplies a schema, constraints, a declarative query language, transactions, and indexes. The relational kind stores data in linked tables, and the rest of this tutorial builds that model step by step.
Exercise
A small web app stores orders in a JSON file on the server. Name two problems that appear when two users place orders at the same moment, and name the DBMS feature that addresses each.
Show answer
First, both requests may read the file, change their copy, and write it back, so one order overwrites the other and is lost. Transactions with isolation (part of ACID) prevent this by making concurrent changes behave as if they ran one at a time. Second, a crash during a write can leave the file half written and unreadable. Transactions with atomicity and durability prevent this, because a change is either fully applied or not applied at all. Constraints (such as UNIQUE on the order ID) also stop duplicate orders from being stored.
Exercise
In the CSV example, find_by_email reads every row for each lookup. In SQL, the equivalent statement does not say how to search. Who decides how the search is done, and why does that help when the table grows?
Show answer
The DBMS decides, using its query planner. It can choose to scan the table or use an index, depending on the table's size and available indexes. This helps because the application's SQL does not change when the table grows or an index is added. Only the plan the DBMS picks changes.