How data is organized into tables, connected through relationships, queried with SQL, and protected through transactions — the systems that power every school, hospital, bank, and website you use
Every time you search for a product online, check your grade in a school portal, look up a library book, withdraw money from an ATM, or log into a streaming service, a database is running behind the scenes. Databases are organized systems for storing, retrieving, updating, and protecting data. They are one of the most important technologies in modern computing — and yet, from the user's perspective, they are completely invisible.
This chapter introduces databases as systems, not merely as storage containers. You will learn how data is organized into tables, how rows and columns represent real-world records, how keys connect related information, how queries retrieve exactly the data you need, how SQL expresses those queries in a precise language, and how database management systems ensure that data stays consistent and reliable even when thousands of users access it at once.
The chapter also introduces information systems — the larger organizational structures that combine databases, software, people, and processes to support decision-making in schools, hospitals, banks, governments, stores, libraries, and every other institution that manages information.
When a student logs into a school portal and sees their grade for last week's assignment, what happened between clicking the login button and seeing that grade appear on screen? The answer involves a database receiving a query, searching millions of records in a fraction of a second, returning exactly the right information, and sending it to the browser — all without the student seeing any of it. Understanding that system is what this chapter is about.
Before databases existed, organizations stored information in filing cabinets, paper ledgers, and card catalogs. A hospital might keep patient records in one cabinet, billing records in another, and appointment schedules in a third. Finding all the information about one patient required searching multiple places. Updating an address meant changing it in every location where it appeared. Mistakes were common. Information got lost.
Early computer programs tried to solve this by storing data in files — text files, spreadsheet files, or custom binary files. This was better than paper, but it still created problems. Each program managed its own files in its own format. Two programs that needed to share data had to copy information back and forth, which caused inconsistencies. If a student's address changed, the admissions program might be updated but the billing program might not. The same data existed in multiple places with different values. This problem is called data redundancy — the same information stored in multiple places in ways that can become contradictory.
A database solves these problems by providing a single organized system for storing and accessing data. Instead of scattered files managed by individual programs, a database creates a central repository with consistent structure, controlled access, and reliable retrieval.
A database is an organized collection of related data. The data is structured so that it can be stored, searched, updated, and retrieved efficiently. A database is not just a pile of information — it is information arranged according to a design that reflects how the information relates to the real world.
A database management system, or DBMS, is the software that manages the database. The DBMS handles storing the data, executing queries, controlling access, maintaining consistency, and protecting the data from errors or corruption. Users and programs interact with the DBMS rather than directly with the raw data files. Together, the database and the DBMS form a database system.
| Organization | What the Database Stores |
|---|---|
| School | Student names, enrollment, grades, schedules, attendance, teacher assignments |
| Hospital | Medical histories, test results, prescriptions, appointments, insurance, billing |
| Bank | Account numbers, balances, transaction histories, customer information, loan records |
| Online store | Product listings, prices, inventory, customer accounts, orders, shipping |
| Library | Book titles, authors, ISBNs, shelf locations, borrower records, due dates |
| Government | Census data, tax records, vehicle registrations, voter rolls, public benefits |
| Search engine | Indexed web pages, links, rankings, and user data |
Disorganized data is almost as useless as no data at all. If a student named "James Smith" appears twice with different GPAs, which is correct? A well-designed database eliminates this by storing each piece of information exactly once and connecting pieces together through relationships — which is what the rest of this chapter explains.
The most common type of database in business, education, and web development is the relational database. A relational database organizes information into tables that are connected by relationships. The concepts of tables, records, and fields are the foundation of everything that follows.
A table is a structured collection of related data organized into rows and columns. Each table represents one type of entity — one kind of thing the database stores information about. A school database might have a Students table, a Courses table, a Teachers table, and an Enrollments table. You would not mix student information and course information in the same table because they are different kinds of entities with different properties.
Each row in a table is called a record. A record represents one instance of the entity the table describes. In a Students table, each row is one student. Each column is called a field. A field represents one property or attribute of the entity.
| StudentID (PK) | FirstName | LastName | GradeLevel | GPA |
|---|---|---|---|---|
| 1001 | Maria | Garcia | 11 | 3.20 |
| 1002 | James | Obi | 10 | 3.75 |
| 1003 | Priya | Sharma | 12 | 3.90 |
| 1004 | Carlos | Vega | 11 | 2.85 |
| 1005 | Aiko | Tanaka | 10 | 3.40 |
Every field has a data type — the kind of value it is allowed to contain. Data types include Integer (whole numbers), Decimal or Float (numbers with decimal points), Text or String (character sequences), Date, and Boolean (true/false). Data types matter because they determine what operations are valid. You can calculate an average GPA because it is a number. You can sort LastName alphabetically because it is text.
Constraints are rules that the database enforces automatically. Common constraints include NOT NULL (a field must have a value), UNIQUE (no two records can share the same value in this field), and range constraints (GradeLevel might only permit values 9 through 12). Constraints enforce data quality without relying on whoever enters the data to remember the rules.
A spreadsheet allows any value in any cell with little enforcement. A database table enforces consistent structure: every record has exactly the same fields, every field has a defined type, and constraints prevent illegal values. This strict structure is what makes reliable querying across millions of records possible.
One of the most important design decisions in a database is choosing how to uniquely identify each record. In a table of students, two students might have the same first name, or even the same full name. If you search for "James Smith," how does the database know which James Smith you mean? The solution is a key — a field whose value uniquely identifies each record.
A primary key is a field whose value is unique for every record and never changes. In the Students table, StudentID is the primary key. Every student has a different StudentID. Even if two students are both named Maria Garcia, they will have different StudentIDs — perhaps 1001 and 2047 — and the database can distinguish them precisely.
• Unique — No two records share the same primary key value.
• Never null — Every record must have a primary key value.
• Stable — The primary key does not change after it is assigned.
• Simple — A single field is preferred over a combination of fields.
A natural key is drawn from real-world data that naturally identifies the entity — for example, an ISBN for a book. A surrogate key is an artificial identifier created by the database, such as StudentID: 1001. Surrogate keys are often preferred because real-world identifiers can change (a person's name, email, or phone number) while surrogate keys never need to be updated. Once 1001 is assigned to Maria Garcia, it stays with her record permanently.
A foreign key is a field in one table that refers to the primary key of another table. Foreign keys create connections between tables. Consider a Courses table with a TeacherID field — TeacherID is a foreign key that references the TeacherID primary key in the Teachers table. Each course record points to the teacher who teaches it.
Referential integrity is the rule that every foreign key value must match a real primary key in the referenced table. If a foreign key in the Enrollments table contains StudentID 9999, but there is no student with ID 9999 in the Students table, the DBMS rejects that record. This prevents orphaned records — records that refer to things that do not exist.
| CourseID (PK) | CourseName | TeacherID (FK) |
|---|---|---|
| C101 | Introduction to CS | T07 |
| C102 | Algebra II | T12 |
| C103 | World History | T03 |
Gold = Primary Key (PK) · Teal = Foreign Key (FK) referencing Teachers.TeacherID
The power of a relational database comes from relationships — the connections between tables that allow you to combine information from multiple sources in a single query. There are three fundamental types of relationships.
A one-to-many relationship means that one record in Table A can be associated with many records in Table B, but each record in Table B is associated with only one record in Table A. One teacher can teach many courses, but each course has only one teacher. The foreign key lives in the "many" side of the relationship — TeacherID lives in the Courses table, not the Teachers table.
A many-to-many relationship means that records in each of two tables can be associated with multiple records in the other. One student can enroll in many courses, and one course can have many students enrolled. Many-to-many relationships cannot be stored directly with two tables alone. They require a junction table — a linking table that sits between the two main tables and holds foreign keys to both.
| LoanID (PK) | StudentID (FK) | CourseID (FK) |
|---|---|---|
| E001 | 1001 | C101 |
| E002 | 1001 | C102 |
| E003 | 1002 | C101 |
| E004 | 1003 | C103 |
The Enrollments table is the junction table. Each row records one enrollment — one student in one course. Student 1001 (Maria) is enrolled in both C101 and C102. Course C101 has both student 1001 and 1002. By searching this table, you can find all courses a student is in, or all students in a course.
A one-to-one relationship means each record in Table A is associated with exactly one record in Table B, and vice versa. These are less common and are sometimes used to split a large table for performance, or to separate sensitive information from general information.
Database designers use Entity-Relationship Diagrams (ER Diagrams) to plan a database's structure visually before writing any code. An ER Diagram shows the tables (entities), their fields (attributes), primary keys, and the relationships between tables. Reading ER Diagrams is a foundational skill for any database work.
[Students] [Enrollments] [Courses] +-----------+ +-----------+-------+ +----------+ |StudentID |◄─────|StudentID |CourseID|─►|CourseID | |FirstName | +-----------+-------+ |CourseName| |LastName | (junction table) |TeacherID |──►[Teachers] |GradeLevel | +----------+ |TeacherID| |GPA | |Name | +-----------+ +---------+ ◄── = foreign key reference one-to-many: one Teacher teaches many Courses many-to-many: Students ↔ Courses through Enrollments
A query is a request for data from a database. Queries are the primary way that users and programs interact with a database. A query specifies what data you want, where to find it, what conditions it must meet, and how to organize the results.
| Operation | What It Does | Plain-English Example |
|---|---|---|
| Selection | Filter which rows are returned based on a condition | "Give me all students in grade 11." |
| Projection | Choose which columns appear in the result | "Show me only first name and last name." |
| Joining | Combine rows from multiple tables into one result | "Show each student's name and their courses." |
| Aggregation | Compute statistics across records | "What is the average GPA of 10th graders?" |
| Sorting | Order results by one or more fields | "List all students alphabetically by last name." |
| Insertion | Add new records to a table | "Add a new student: Leon Mbeki, grade 12." |
| Update | Modify existing records | "Change Maria Garcia's GPA to 3.30." |
| Deletion | Remove records from a table | "Remove the record for student ID 1004." |
The result of a retrieval query is a result set — a temporary table containing the records and fields that match the query. This result set is shown to the user or processed by a program. It is a view of the data, not a stored copy — querying does not change what is in the database.
Every time you search for a product, look up your grades, see a recommended list, or log in to a personalized homepage, a query is executing behind the scenes. The web application sends a query to the database, receives a result set, and uses that data to build what you see on screen.
SQL — pronounced either "S-Q-L" or "sequel" — stands for Structured Query Language. SQL is the standard language for communicating with relational databases. It is used to create tables, insert data, query data, update records, and delete records.
SQL is a declarative language — you describe what you want, and the database figures out how to retrieve it. You do not write step-by-step loops; you state your request, and the DBMS executes it. SQL is one of the most widely used languages in computing, and learning its basics gives you a skill that applies across dozens of database systems.
The SELECT statement retrieves data. Its basic form specifies which columns to return and which table to read from. To retrieve all columns, use * (asterisk, meaning "all").
SELECT FirstName, LastName FROM Students;
| FirstName | LastName |
|---|---|
| Maria | Garcia |
| James | Obi |
| Priya | Sharma |
| Carlos | Vega |
| Aiko | Tanaka |
The WHERE clause filters which rows are included. It supports comparison operators =, <, >, <=, >=, <> (not equal), and logical operators AND, OR, and NOT.
SELECT FirstName, LastName, GPA FROM Students WHERE GradeLevel = 11 AND GPA > 3.0;
| FirstName | LastName | GPA |
|---|---|---|
| Maria | Garcia | 3.20 |
SELECT FirstName, LastName, GPA FROM Students ORDER BY GPA DESC;
| FirstName | LastName | GPA |
|---|---|---|
| Priya | Sharma | 3.90 |
| James | Obi | 3.75 |
| Aiko | Tanaka | 3.40 |
| Maria | Garcia | 3.20 |
| Carlos | Vega | 2.85 |
DESC sorts descending (highest to lowest). ASC sorts ascending (lowest to highest) and is the default.
SQL provides built-in functions for computing statistics across records. These are called aggregate functions.
| Function | What It Computes | Example |
|---|---|---|
COUNT(*) | Number of records | How many students total? |
AVG(column) | Average of a numeric field | Average GPA? |
SUM(column) | Total of a numeric field | Total hours logged? |
MAX(column) | Highest value | Highest GPA in the school? |
MIN(column) | Lowest value | Lowest GPA? |
SELECT GradeLevel, AVG(GPA) AS AverageGPA, COUNT(*) AS StudentCount FROM Students GROUP BY GradeLevel ORDER BY GradeLevel;
| GradeLevel | AverageGPA | StudentCount |
|---|---|---|
| 10 | 3.575 | 2 |
| 11 | 3.025 | 2 |
| 12 | 3.900 | 1 |
The JOIN clause combines rows from two tables based on a related column. This is the feature that makes relational databases powerful — it allows you to retrieve connected information from multiple tables in one query.
SELECT Students.FirstName, Students.LastName, Courses.CourseName FROM Students JOIN Enrollments ON Students.StudentID = Enrollments.StudentID JOIN Courses ON Enrollments.CourseID = Courses.CourseID ORDER BY Students.LastName;
| FirstName | LastName | CourseName |
|---|---|---|
| Maria | Garcia | Introduction to CS |
| Maria | Garcia | Algebra II |
| James | Obi | Introduction to CS |
| Priya | Sharma | World History |
-- Add a new student record INSERT INTO Students (StudentID, FirstName, LastName, GradeLevel, GPA) VALUES (1006, 'Leon', 'Mbeki', 12, 3.65); -- Update an existing record UPDATE Students SET GPA = 3.30 WHERE StudentID = 1001; -- Remove a record DELETE FROM Students WHERE StudentID = 1004;
Running UPDATE Students SET GPA = 4.0 without a WHERE clause sets every student's GPA to 4.0. Running DELETE FROM Students without a WHERE clause deletes every student. Always double-check that your WHERE condition is correct before running UPDATE or DELETE.
SELECT FirstName, LastName, GPA FROM Students WHERE GradeLevel = 10 ORDER BY GPA DESC;
SELECT COUNT(*) FROM Students WHERE GradeLevel = 12;
UPDATE Students SET GradeLevel = 12;
SELECT GradeLevel, COUNT(*), AVG(GPA) FROM Students GROUP BY GradeLevel;
A database management system (DBMS) is the software layer that sits between users or applications and the raw data stored on disk. Users and programs never interact directly with data files; they always go through the DBMS, which handles all the complexity of actually storing and retrieving data.
| Responsibility | What the DBMS Handles |
|---|---|
| Storage management | Organizes data on disk in efficient structures; maintains indexes for fast retrieval |
| Query processing | Parses SQL, creates an execution plan, runs the query, returns the result set |
| Access control | Enforces permissions — read, write, admin — for different users and roles |
| Concurrency control | Coordinates simultaneous access by multiple users without conflicts |
| Transaction management | Ensures groups of operations either fully succeed or fully cancel |
| Integrity enforcement | Enforces data types, constraints, primary keys, foreign keys, referential integrity |
| Recovery | Restores a consistent state after a crash, without leaving data partially written |
Relational DBMSs (RDBMS) store data in tables with SQL as the query language. They are the most common type for business and web applications. Major relational database systems include MySQL (widely used for web applications; open-source), PostgreSQL (powerful open-source system known for standards compliance), SQLite (a lightweight single-file database common in mobile apps and small applications), Microsoft SQL Server (enterprise RDBMS used in many business systems), and Oracle Database (used in large organizations).
NoSQL DBMSs store data in formats other than tables — documents, key-value pairs, graphs, or wide columns. They are used when data does not fit well into a tabular structure or when extreme scale is required. Examples include MongoDB (document store) and Redis (key-value store). NoSQL systems are beyond the scope of this chapter, but they are important to know exist.
User (Browser)
│
│ HTTP request: "Add item to cart"
▼
Web Server
(Application Code: Python / Node / Java / etc.)
│
│ SQL: INSERT INTO Cart (UserID, ItemID) VALUES (42, 789);
▼
Database Management System (DBMS)
┌─────────────────────────────────────────┐
│ Parses SQL → Creates execution plan │
│ Enforces constraints → Runs query │
│ Manages transaction → Returns result │
└─────────────────────────────────────────┘
│
│ Reads / writes data files
▼
Storage (SSD / Hard Drive)
[Data files · Indexes · Transaction logs]
The DBMS is invisible to the user but essential to every operation. When you click "add to cart," log in, search a catalog, or update your profile, a DBMS is handling the underlying data operations in the background.
One of the most important and subtle problems in database design is ensuring that the data remains correct when multiple operations happen together — especially when something goes wrong in the middle.
A transaction is a group of database operations that are treated as a single unit. A transaction either commits — all operations complete successfully and changes are permanently saved — or rolls back — all operations are cancelled and the database returns to its state before the transaction began.
BEGIN TRANSACTION; UPDATE Accounts SET Balance = Balance - 500 WHERE AccountID = 'CHK-001'; UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 'SAV-001'; COMMIT; -- makes all changes permanent
If the system crashes between the two UPDATE statements, the DBMS rolls back the transaction on recovery, undoing the first UPDATE. The database returns to the pre-transfer state. No money is lost or created.
BEGIN TRANSACTION
│
▼
[Operation 1] ──FAIL──► ROLL BACK
│ (database returns to
▼ pre-transaction state)
[Operation 2] ──FAIL──► ROLL BACK
│
▼
[Operation N]
│
▼
COMMIT
(all changes permanent)
Database transactions are designed to guarantee four properties, summarized by the acronym ACID.
Even a perfectly designed database with ACID transactions can lose data if hardware fails, software has bugs, a fire destroys a data center, or a ransomware attack encrypts the data files. Backups are copies of the database that can be used to restore data if the original is lost or corrupted. ACID guarantees consistency within a running system; backups guarantee survival when the system itself is destroyed.
| Backup Type | What It Copies | Advantage | Disadvantage |
|---|---|---|---|
| Full backup | The entire database at a point in time | Simple to restore — one copy is all you need | Slow and storage-intensive for large databases |
| Incremental backup | Only data changed since the last backup | Fast, small files | Restoration requires last full backup plus every incremental since |
| Differential backup | All data changed since the last full backup | Grows over time but simpler to restore than incremental | Grows larger the longer you wait between full backups |
| Transaction log backup | The record of every transaction, continuously | Allows recovery to almost any point in time | Requires more storage and management |
Organizations must decide how often to take backups, how long to keep them, and where to store them. Storing backups on the same server as the database is dangerous — if the server fails, the backup fails too. Reliable systems store backups in separate physical locations or in cloud storage.
Two key measures guide backup strategy. Recovery Point Objective (RPO) is how much data is acceptable to lose in the worst case — if you back up every hour, you could lose up to one hour of data. Recovery Time Objective (RTO) is how long it takes to restore service after a failure.
Replication goes beyond backups by maintaining one or more real-time copies of the database on separate servers. If the primary server fails, a replica takes over immediately, minimizing downtime. High-reliability database systems — used by banks, hospitals, airlines, and large web services — combine ACID-compliant transactions, multiple levels of backup, geographic replication, and regular recovery drills to verify that backups actually work.
Making backups is not enough. Organizations must regularly test that their backups can actually be restored. A backup that cannot be restored is not a backup — it is a false sense of security. Discovering a backup is corrupted during an actual disaster is far worse than discovering it during a routine test.
A database is a technical system — it stores data and answers queries. But databases do not exist in isolation. They are embedded in information systems — larger systems that combine databases, software applications, user interfaces, networks, people, processes, and policies to support the work of organizations.
An information system is more than software. It includes data (the information itself), hardware (servers, computers, storage), software (the DBMS, application programs, interfaces), people (users, administrators, developers, decision-makers), processes (the workflows and procedures that govern how information is collected and used), and policies (rules about who can access what, how long data is retained, and what can be done with it).
| Type | Purpose | Example |
|---|---|---|
| Transaction Processing System (TPS) | Records day-to-day operations as they happen | Point-of-sale system; bank ATM transactions; hospital patient check-in |
| Management Information System (MIS) | Summarizes transaction data into reports for managers | Monthly sales report by region; quarterly inventory summary |
| Decision Support System (DSS) | Helps analysts explore data and model scenarios | "What if we cut prices by 10% — how would revenue change?" |
| Customer Relationship Management (CRM) | Stores customer interactions, purchases, and support history | Salesforce; help desk systems that show a customer's history |
| Enterprise Resource Planning (ERP) | Integrates all organizational data — accounting, HR, inventory, purchasing — into one system | SAP; large manufacturers using one system for all departments |
Database administrators (DBAs) are the specialists who design, maintain, and protect database systems. Their responsibilities include designing database schemas, writing and optimizing queries, managing user permissions, monitoring performance, planning backup and recovery procedures, applying security patches, and ensuring compliance with data privacy regulations. Database administration is a specialized career path within computing, covered further in Chapter 28.
Organizations must make decisions about how their data is governed. Who is allowed to access which tables and fields? How long is data retained before deletion? What regulations apply — for example, student records are governed by FERPA in the United States, and medical records are governed by HIPAA. How is sensitive data (Social Security numbers, medical diagnoses, financial details) protected? Who is responsible when data is lost, stolen, or misused?
These are not purely technical questions — they are legal, ethical, and organizational questions. The database is the technical system; data governance is the human system that determines how the database is used responsibly. Understanding data governance connects directly to Chapter 22 (Privacy, Identity, and Digital Safety) and Chapter 28 (Ethics, Society, Careers, and the Future of Computing).
Table: Students
┌══════════════╤═══════════╤══════════╤════════════╤════════
│ StudentID │ FirstName │ LastName │ GradeLevel │ GPA │
│ (PK INTEGER) │ (TEXT) │ (TEXT) │ (INTEGER) │(REAL) │
╞══════════════╪═══════════╪══════════╪════════════╪═══════╡
│ 1001 │ Maria │ Garcia │ 11 │ 3.20 │
│ 1002 │ James │ Obi │ 10 │ 3.75 │
│ 1003 │ Priya │ Sharma │ 12 │ 3.90 │
└──────────────┴───────────┴──────────┴────────────┴───────┘
↑ ↑
Primary Key Data Type
(unique, not null, REAL = decimal
never changes) numbers allowed
Each ROW = one record (one student)
Each COLUMN = one field (one attribute)
PK = Primary Key · TEXT/INTEGER/REAL = data types
Students Enrollments (junction) Courses
┌────────────┐ ┌────────────┬──────────┐ ┌──────────┬───────────────────┐
│ StudentID │◄─────────│ StudentID │ CourseID │────►│ CourseID │ CourseName │
│ FirstName │ FK │ (FK) │ (FK) │ FK │ TeacherID│ │
│ LastName │ └────────────┴──────────┘ └──────────┴───────────────────┘
│ GradeLevel │ │
│ GPA │ │ FK
└────────────┘ ▼
Teachers
┌──────────┬──────────┐
│ TeacherID│ Name │
└──────────┴──────────┘
◄──── = foreign key reference pointing to a primary key
one-to-many: one Teacher → many Courses
many-to-many: Students ↔ Courses (through Enrollments junction table)
SELECT FirstName, LastName, GPA FROM Students WHERE GradeLevel = 10 ORDER BY GPA DESC;
SELECT Students.FirstName, Students.LastName, Courses.CourseName FROM Students JOIN Enrollments ON Students.StudentID = Enrollments.StudentID JOIN Courses ON Enrollments.CourseID = Courses.CourseID WHERE Courses.CourseName = 'Introduction to CS';
SELECT GradeLevel, COUNT(*) AS StudentCount, AVG(GPA) AS AverageGPA FROM Students GROUP BY GradeLevel ORDER BY GradeLevel;
Complete each sentence with the correct term from the chapter.
SELECT CourseName FROM Courses WHERE TeacherID = 'T07';What is wrong with this SQL? How should it be corrected?
What is the result of this statement? What should the developer have written to update only student ID 1003?
What happens when the DBMS processes this statement? What database concept causes this behavior, and why is the behavior correct?
Identify two specific problems this design causes. How would splitting into separate, related tables solve these problems?
What happens to the backup? What backup strategy would have prevented total data loss?
SELECT * FROM Students WHERE GPA >= 3.75;SELECT COUNT(*) FROM Students WHERE GradeLevel = 10;SELECT FirstName FROM Students WHERE GradeLevel = 11 WHERE GPA > 3.0;DELETE FROM Students; without a WHERE clause. What happens? What should they have done instead?These questions draw on earlier chapters of the textbook.
Chapter 19 begins Part V: Networks, Web, and Security. You have now seen how data is organized and stored in databases on servers. But how does a request from your laptop or phone reach a database server halfway across the world? Chapter 19 explains how computers communicate across networks — through nodes, links, packets, routers, and protocols. You will learn what an IP address is, how domain names are translated into addresses, how protocols govern communication, and how the internet itself is structured as a network of networks. These concepts explain the infrastructure that delivers every web page, database query result, and streaming video you receive.