1. Home
  2. Explore
  3. Computer Science
  4. CS50 Week 7: Data Tools

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

CS50 Week 7: Data Tools

From Python Data Analysis to Relational Databases and SQL

Modern software development rarely depends on one programming language. Different tools are designed for different jobs. C provides close control over memory and hardware, Python makes many programming tasks shorter and more readable, and SQL is designed specifically for working with data stored in databases.

This lesson follows the progression from simple text files to structured relational databases. Along the way, it explains how Python can analyze data, how SQL can express the same questions more directly, how tables relate to one another, and how databases address performance, concurrency, and security.

1. Why Different Tools Are Used for Different Jobs

A programming language is a tool. Although a sufficiently determined programmer might solve almost any problem in C, doing so would often require unnecessary effort. Python provides built-in features and libraries that make many data-processing tasks easier than they would be in C.

However, even Python is not always the best tool for large-scale data. If an application must store and search millions of records, manually opening files and writing loops can become inefficient and complicated. A database system is designed specifically for this task.

A typical modern application may therefore combine several technologies:

  • Python for application logic and user interaction
  • SQL for asking questions of stored data
  • HTML and CSS for structuring and styling web pages
  • JavaScript for behavior in web applications
  • C when low-level control or efficiency is especially important

The important idea is not that one language is universally superior. The important idea is that each tool should be matched to the job it handles well.

Good software engineering often means choosing the right tool rather than writing everything from scratch in one language.

Think About It

Why might a programmer prefer a database query over writing a Python loop when the data contains millions of rows?

2. Collecting Data in Rows and Columns

A form can collect structured information from many people. For example, a form might ask for:

  • A person’s favorite programming language
  • A person’s favorite problem set

The responses can be stored in a spreadsheet. Spreadsheet programs such as Google Sheets, Microsoft Excel, and Apple Numbers represent data using rows and columns.

A spreadsheet is convenient for humans because it displays data graphically. Each row represents one response, and each column represents one property of that response.

For example:

TimestampLanguageProblem
time valuePythonHello, World
time valueCCredit
time valueScratchMario

A spreadsheet can also export data into a more portable format, such as a CSV file.

3. Flat Files and CSV Data

A flat file database is a simple text file containing data. The file might end in .txt, but a common format is .csv.

CSV stands for comma-separated values. It represents the structure of a spreadsheet using ordinary text:

  • A newline separates one row from the next.
  • A comma separates one column from the next.

A simplified CSV file might look like this:

Timestamp,Language,Problem
2023-10-30 13:20,Python,"Hello, World"
2023-10-30 13:21,C,Credit
2023-10-30 13:22,Scratch, Mario

The first row is often a header row. It does not represent an actual response. Instead, it describes what the columns mean.

In the example:

  • Timestamp identifies when the response was submitted.
  • Language identifies the selected programming language.
  • Problem identifies the selected problem.

Handling Commas Inside Values

CSV files have a subtle problem: a comma normally means “move to the next column.” What happens when a value itself contains a comma?

For example, the problem name Hello, World includes a comma. If the file contained:

Python,Hello, World

a basic reader might interpret this as three values rather than two.

CSV conventions solve this by placing values containing commas inside quotation marks:

Python,"Hello, World"

The quotation marks tell a CSV-reading program that the comma inside them belongs to the value rather than separating columns.

This is an example of escaping or protecting special characters so that data does not accidentally change the meaning of the format.

Think About It

Why would a CSV file need special rules for values containing commas, while a spreadsheet can display those values without confusion?

4. Reading CSV Files in Python

Python includes a module called csv that understands CSV rules. Using this module is safer and easier than manually searching for commas, allocating memory, and interpreting each line.

Opening and Closing a File

A direct approach resembles file handling in C:

file = open("favorites.csv", "r")

# Work with the file here

file.close()

The "r" means that the file is opened for reading. In Python, reading is the default, so the second argument can technically be omitted.

A more common Python style uses with:

with open("favorites.csv") as file:
    # Work with the file here

The with statement creates a block. When execution leaves that block, Python automatically closes the file. This prevents the programmer from forgetting to close it manually.

The benefit is both convenience and reliability: the file is cleaned up even when the programmer does not explicitly call close.

Using csv.reader

The simplest CSV reader is csv.reader:

import csv

with open("favorites.csv") as file:
    reader = csv.reader(file)

    next(reader)

    for row in reader:
        print(row[1])

Here is what happens:

  1. The csv module is imported.
  2. The file is opened.
  3. csv.reader(file) creates an object that understands CSV structure.
  4. next(reader) skips the header row.
  5. The for loop processes one row at a time.
  6. row[1] accesses the second column.

Python lists use zero-based indexing:

  • row[0] is the first column.
  • row[1] is the second column.
  • row[2] is the third column.

If the columns are timestamp, language, and problem, then row[1] represents the language.

The Fragility of Numeric Indexes

The previous program assumes that the language will always remain in the second column. If someone moves the columns in the spreadsheet, the code may silently begin reading the wrong data.

For example, if the columns are reordered to:

ProblemTimestampLanguage

then row[1] refers to the timestamp rather than the language.

This illustrates fragile code: code that depends heavily on a particular arrangement of data.

Using csv.DictReader

A more robust approach uses DictReader:

import csv

with open("favorites.csv") as file:
    reader = csv.DictReader(file)

    for row in reader:
        print(row["language"])

DictReader automatically uses the header row as dictionary keys. Each row becomes a dictionary similar to:

{
    "timestamp": "...",
    "language": "Python",
    "problem": "Hello, World"
}

The code can then access a value by its column name:

row["language"]

This is more robust because moving columns does not matter. The code still works as long as the column is still named language.

The remaining assumption is that the header name itself will not change.

Named columns are generally safer than numeric positions because the code describes what data it wants rather than where that data happens to be located.

5. Counting Values in Python

Suppose the goal is to count how many people selected Scratch, C, and Python.

Manual Counters

A direct approach creates one counter for each language:

scratch = 0
c = 0
python = 0

Python also supports multiple assignment:

scratch, c, python = 0, 0, 0

The file can then be processed row by row:

for row in reader:
    favorite = row["language"]

    if favorite == "Scratch":
        scratch += 1
    elif favorite == "C":
        c += 1
    elif favorite == "Python":
        python += 1

After the loop, the counters can be printed:

print(f"Scratch: {scratch}")
print(f"C: {c}")
print(f"Python: {python}")

An f-string allows a variable’s value to be inserted into a string. Curly braces mark the expression to be evaluated.

This approach works, but it has limitations:

  • It requires a separate variable for each possible language.
  • New languages require new variables and new conditional branches.
  • The code becomes longer as the number of categories grows.

Using a Dictionary as a Counter

A dictionary can associate each language with its count:

counts = {}

For each row, the code checks whether the language is already a key:

for row in reader:
    favorite = row["language"]

    if favorite in counts:
        counts[favorite] += 1
    else:
        counts[favorite] = 1

The logic is:

  1. If the language has been seen before, increase its existing count.
  2. If it has not been seen before, create the key and initialize its count to one.

The results can be printed by iterating over the dictionary:

for favorite in counts:
    print(f"{favorite}: {counts[favorite]}")

This design is more flexible. It works whether the data contains three languages or many more because the program does not need a separate variable for every possible value.

Sorting Dictionary Results

By default, dictionary iteration follows the order in which keys were encountered. Python’s sorted function can sort the keys alphabetically:

for favorite in sorted(counts):
    print(f"{favorite}: {counts[favorite]}")

To sort according to the count rather than the language name, the dictionary’s get method can be supplied as the sorting key:

for favorite in sorted(counts, key=counts.get):
    print(f"{favorite}: {counts[favorite]}")

By default, the order is ascending. To reverse it:

for favorite in sorted(counts, key=counts.get, reverse=True):
    print(f"{favorite}: {counts[favorite]}")

This produces the least common values first without reverse=True, and the most common values first with it.

Python supports both:

  • Positional arguments, whose meaning depends on their position
  • Named parameters, such as key=counts.get and reverse=True

Named parameters make the programmer’s intention clearer. Many Python function parameters are optional and can be supplied by name.

Using Counter

Python’s collections module includes a specialized object called Counter:

from collections import Counter

counts = Counter()

The Counter automatically treats unseen values as having a count of zero. The loop can therefore be shortened:

for row in reader:
    favorite = row["language"]
    counts[favorite] += 1

The most_common method can return values in descending order of frequency:

for favorite, count in counts.most_common():
    print(f"{favorite}: {count}")

This loop uses a Python feature called unpacking. Each item returned by most_common() contains two values:

  • The key, such as "Python"
  • The count associated with that key

The two values are assigned to favorite and count.

The same program can analyze problems instead of languages simply by changing the selected column:

favorite = row["problem"]

This demonstrates the value of writing general-purpose code. Once the counting logic is organized around keys and values, it can analyze many columns without being rewritten from scratch.

Interactive Data Queries in Python

A Python program can ask the user which problem to look up:

favorite = input("Favorite problem: ")

for favorite, count in counts.most_common():
    if favorite == requested:
        print(count)

A more direct database version will appear later. The broader idea is that a program can:

  1. Ask a human a question.
  2. Search stored data.
  3. Compute an answer.
  4. Display the result.

This pattern is common in data analysis, consulting, web applications, and mobile applications.

Think About It

What makes a dictionary or Counter more adaptable than separate variables named scratch, c, and python?

6. What a Database Adds

A CSV file is useful for small or simple datasets, but it has important limitations:

  • It is just text.
  • Searching may require scanning the file from beginning to end.
  • Data is not automatically protected from invalid entries.
  • Relationships between different sets of data are difficult to represent.
  • Multiple users or programs modifying the file can cause conflicts.
  • The programmer must write much of the processing logic manually.

A proper database is a software system running on a computer or server. It is designed to store, organize, search, and modify large amounts of data.

A relational database stores data in tables. Tables resemble spreadsheet sheets, but relational databases can manage several tables and define relationships between them.

The relationships allow the database to avoid unnecessary duplication while still combining information when needed.

7. SQL and the CRUD Model

SQL, pronounced “S-Q-L” or sometimes “sequel,” stands for Structured Query Language. It is a database-specific language.

Python is generally an imperative language: the programmer describes steps, loops, and conditions. SQL is primarily a declarative language. The programmer describes the desired data, and the database determines how to retrieve it.

SQL follows the CRUD model:

  • Create data
  • Read data
  • Update data
  • Delete data

SQL uses several keywords for these operations:

CRUD ideaCommon SQL keyword
Create new rowsINSERT
Read dataSELECT
Update existing dataUPDATE
Delete rowsDELETE
Delete an entire table or database objectDROP

SQL is relatively small in terms of its basic grammar, but those keywords can express powerful operations.

SQLite

The database system used here is SQLite. SQLite is an implementation of SQL designed to be lightweight. It is commonly used on computers and mobile devices.

SQLite stores its database in a file, often with a .db extension. Unlike a CSV file, the database file is stored in a structured binary format.

SQLite contains the core ideas of relational databases while remaining convenient for small applications, teaching, desktop software, and mobile software.

Different database systems—including systems associated with major commercial database products—may support additional features or slightly different syntax. They share a common foundation, but SQL is not implemented identically everywhere.

SQLite-Specific Commands

SQLite provides commands beginning with a dot. These are SQLite program commands rather than standard SQL:

  • .mode csv changes how SQLite interprets CSV data.
  • .import loads external data.
  • .schema displays table definitions.
  • .timer on measures query execution time.
  • .quit exits SQLite.

A SQL statement itself generally ends with a semicolon.

8. Importing a CSV File into SQLite

A CSV file can be imported into a new SQLite database:

sqlite3 favorites.db

Within SQLite, CSV mode can be enabled:

.mode csv

The file can then be imported into a table:

.import favorites.csv favorites

This creates a table called favorites and loads the CSV data into it.

After leaving SQLite:

.quit

the directory contains both:

  • favorites.csv, the original text file
  • favorites.db, the structured SQLite database

The import is typically a one-time operation. Once the data is inside the database, SQL can be used to analyze and modify it.

9. Inspecting Tables with SELECT

The basic SQL query has this structure:

SELECT columns
FROM table;

To retrieve every column and every row from the favorites table:

SELECT * FROM favorites;

The asterisk is a wildcard meaning “all columns.” It has no relationship to pointer syntax in C.

To retrieve only the language column:

SELECT language
FROM favorites;

To limit the number of returned rows:

SELECT language
FROM favorites
LIMIT 10;

LIMIT restricts the size of the result set. It does not necessarily return the most important or highest-ranked rows. Without an ordering instruction, it simply returns some initial rows according to the database’s retrieval order.

Counting Rows

SQL provides aggregate functions. An aggregate function computes one result from multiple rows.

To count all rows:

SELECT COUNT(*)
FROM favorites;

If the imported file had a header row that was not treated separately, the count might include that header. In the example, the actual response count is lower than the total imported lines because one line described the columns rather than representing a response.

If every row has a value in a particular column, these would produce the same count:

SELECT COUNT(language)
FROM favorites;
SELECT COUNT(problem)
FROM favorites;

However, COUNT(*) is conventional when the goal is specifically to count rows.

Distinct Values

To list each different language only once:

SELECT DISTINCT language
FROM favorites;

The DISTINCT keyword removes duplicate result values.

Functions can be nested. The number of different languages can be counted like this:

SELECT COUNT(DISTINCT language)
FROM favorites;

The inner operation identifies distinct languages, and the outer operation counts them.

Filtering with WHERE

The WHERE clause filters rows:

SELECT COUNT(*)
FROM favorites
WHERE language = 'C';

This asks for the number of rows whose language is C.

Multiple conditions can be combined:

SELECT COUNT(*)
FROM favorites
WHERE language = 'C'
  AND problem = 'Hello, World';

SQL uses:

  • AND rather than C’s &&
  • A single equals sign for comparison
  • Single quotes around text values

The exact symbols used for equality vary between languages. SQL uses = for equality testing, whereas C and Python use ==.

Grouping with GROUP BY

To count every language without writing separate conditions, SQL can group rows:

SELECT language, COUNT(*)
FROM favorites
GROUP BY language;

The database conceptually gathers all rows with the same language and counts the rows in each group.

This single query replaces much of the manual Python code involving:

  • Counters
  • Conditional statements
  • Dictionary updates
  • Iteration over the resulting dictionary

To count problems instead:

SELECT problem, COUNT(*)
FROM favorites
GROUP BY problem;

Ordering with ORDER BY

To order groups by their counts:

SELECT language, COUNT(*)
FROM favorites
GROUP BY language
ORDER BY COUNT(*);

By default, ORDER BY sorts in ascending order. For descending order:

SELECT language, COUNT(*)
FROM favorites
GROUP BY language
ORDER BY COUNT(*) DESC;

The result can be given a simpler column name using AS:

SELECT language, COUNT(*) AS n
FROM favorites
GROUP BY language
ORDER BY n DESC;

Here, n is an alias for the calculated count.

A top result can be selected with LIMIT:

SELECT language, COUNT(*) AS n
FROM favorites
GROUP BY language
ORDER BY n DESC
LIMIT 1;

The query can also return only the count, although returning the language as well is usually more informative.

SQL can often express in one statement what would require many lines of Python loops and conditionals.

Think About It

What information does GROUP BY provide that a simple SELECT language query does not?

10. Inserting, Updating, and Deleting Data

Inserting Rows

A new row can be added with INSERT INTO:

INSERT INTO favorites (language, problem)
VALUES ('SQL', 'Fiftyville');

The first parenthesized list identifies the columns receiving values. The second list supplies the corresponding values.

The timestamp column is omitted, so its value is absent. SQL represents missing data using NULL.

In SQL, NULL means that a value is missing or unknown. It does not refer to a pointer or memory address, even though the word may resemble null terminology in other languages.

Deleting Rows

Rows can be deleted with:

DELETE FROM favorites
WHERE timestamp IS NULL;

IS NULL tests whether a column has no value.

The WHERE clause is extremely important. Without it:

DELETE FROM favorites;

every row in the table would be deleted.

This is a destructive operation. Databases do not necessarily provide a simple undo operation at the command line. Backups are therefore essential when working with important data.

Updating Rows

Existing values can be changed with UPDATE:

UPDATE favorites
SET language = 'SQL',
    problem = 'Fiftyville';

Without a WHERE clause, every row is changed.

A safer, targeted update would include a condition:

UPDATE favorites
SET language = 'SQL'
WHERE problem = 'Fiftyville';

The absence of WHERE can therefore turn a small intended change into a change to the entire table.

Dropping Database Objects

DROP is even more destructive. It can remove an entire table or other database object rather than merely deleting rows.

Because of this, commands such as DROP TABLE should be used with extreme care.

11. Designing Relational Data

A database’s design matters as much as the queries used to access it. Poor design can cause:

  • Redundant data
  • Wasted storage
  • Inconsistent values
  • Difficult updates
  • Tables with irregular or “jagged” structures

Consider a spreadsheet for television shows. A first attempt might use columns such as:

TitleStar 1Star 2Star 3Star 4

This design has a problem: different shows have different numbers of stars. Some rows might require only one star column, while others might require many. Adding more star columns produces a sparse, uneven table.

A second attempt might use one star column and repeat the show title:

TitleStar
The OfficeSteve Carell
The OfficeRainn Wilson
The OfficeJohn Krasinski

This avoids a variable number of star columns, but now the title is duplicated in every row.

Repeated strings waste space and create consistency problems. If the title is edited in one row but not another, the database can contain conflicting information.

Normalization

A better design separates distinct entities:

  1. A table for shows
  2. A table for people
  3. A table connecting shows to people

This process of factoring out repeated information is called normalization.

The goal is to store each fact in one canonical location and represent relationships separately.

The Shows Table

A shows table might contain:

idtitle
386676The Office

The id is a unique identifier for the show.

The People Table

A people table might contain:

idname
136797Steve Carell
933988Rainn Wilson

Each person also receives a unique identifier.

The Stars Table

The relationship between shows and their stars can be represented using:

show_idperson_id
386676136797
386676933988

The same numeric show ID appears multiple times, but this is not the same as duplicating the full string The Office.

Numeric identifiers generally require much less storage than repeated text. They also allow computers to compare and process values efficiently.

The tables may be less immediately readable to a human, but they preserve a clean canonical source of truth:

  • The show name appears once.
  • Each person’s name appears once.
  • The relationship table states who is associated with which show.

12. Primary Keys and Foreign Keys

A primary key is a column whose value uniquely identifies each row in a table.

For the shows table:

id

is the primary key because each show has a distinct ID.

For the people table, the people id column is the primary key.

A foreign key is a column that refers to a primary key in another table.

In the stars table:

  • show_id refers to shows.id
  • person_id refers to people.id

The same numeric value has a different role depending on where it appears:

  • In its original table, it is a primary key.
  • In another table, it is a foreign key referring back to that primary key.

This is how relational databases connect tables without repeatedly storing full descriptions.

13. Database Schemas and Data Types

A database’s schema describes its structure: the tables, columns, data types, and constraints.

SQLite can display a table’s schema:

.schema shows

A schema might specify that:

  • id is an integer
  • title is text
  • year is numeric
  • episodes is an integer
  • title cannot be NULL
  • id is the primary key

A ratings table might specify:

  • show_id as an integer
  • rating as a real number
  • votes as an integer
  • show_id as a foreign key

Common SQL Data Types

Representative SQL data types include:

  • BLOB: a Binary Large Object, representing binary data such as a file
  • INTEGER: whole numbers
  • NUMERIC: numeric values that may represent dates, times, or other number-like data
  • REAL: numbers with decimal values
  • TEXT: strings of characters

Different database systems support additional or more precise types.

Although a database can store binary files as BLOBs, files are often better stored in a file system, with the database storing a reference to the file.

Constraints

A database can enforce rules about valid data.

NOT NULL

A NOT NULL constraint prevents a column from being left without a value.

This is useful when every record must contain a particular piece of information.

UNIQUE

A UNIQUE constraint prevents duplicate values in a column.

For example, a website might require every account to have a distinct email address. A database can enforce that rule directly instead of relying only on Python code to check for duplicates.

Constraints protect data integrity, meaning they help ensure that the stored data remains valid and consistent.

Think About It

Why is enforcing a rule such as unique email addresses inside the database safer than checking for duplicates only in application code?

14. One-to-One and One-to-Many Relationships

A relational database can represent different kinds of relationships.

One-to-One

Suppose every show has one rating. The shows table might contain information about the show, while the ratings table contains:

show_idratingvotes
3866768.9many votes

Each show has one corresponding rating row. This is a one-to-one relationship.

The two tables could technically be combined into one wider table. They may remain separate because the database designers want to organize different kinds of information separately.

One-to-Many

Genres provide a different relationship. One show may belong to several genres:

show_idgenre
63881Adventure
63881Comedy
63881Family

This is a one-to-many relationship: one show can be associated with many genre rows.

This design is better than adding columns called genre1, genre2, and genre3, because it can represent any number of genres without adding more columns.

The source data may contain repeated genre values across different shows. That is not necessarily a design error: many different shows can legitimately belong to the same genre.

15. Nested Queries

A query can use the result of another query. This is called a nested query or subquery.

Suppose a ratings table identifies shows with ratings of at least 6.0, but the show titles are stored in the shows table.

The inner query can retrieve qualifying show IDs:

SELECT show_id
FROM ratings
WHERE rating >= 6.0;

The outer query can use those IDs to retrieve show information:

SELECT *
FROM shows
WHERE id IN (
    SELECT show_id
    FROM ratings
    WHERE rating >= 6.0
)
LIMIT 10;

The inner query runs conceptually first. It produces a collection of show IDs. The outer query then selects shows whose IDs appear in that collection.

To return only the titles:

SELECT title
FROM shows
WHERE id IN (
    SELECT show_id
    FROM ratings
    WHERE rating >= 6.0
)
LIMIT 10;

This is more useful than receiving only numerical IDs, but it still does not show the exact rating.

16. Joining Tables

A join combines related rows from different tables into a temporary result set.

For shows and ratings:

SELECT title, rating
FROM shows
JOIN ratings
  ON shows.id = ratings.show_id
WHERE rating >= 6.0
LIMIT 10;

The ON clause tells the database how the tables are related:

shows.id = ratings.show_id

The result contains information from both tables, such as:

titlerating
show title8.4
show title7.2

The joined result is temporary. The original tables remain normalized and do not acquire duplicated data merely because a query combined them.

Qualifying Column Names

When multiple tables contain related or identical column names, table-qualified notation makes the query clearer:

shows.id
ratings.show_id

The dot indicates a column belonging to a particular table. In this context, it does not refer to object-oriented programming.

Qualification is especially useful when both tables contain a column with the same name or when a query involves several tables.

Joining One-to-Many Data

Joining shows with genres produces one result row for each show-genre relationship:

SELECT title, genre
FROM shows
JOIN genres
  ON shows.id = genres.show_id
WHERE shows.id = 63881;

The output may be:

titlegenre
CatweazleAdventure
CatweazleComedy
CatweazleFamily

The title appears three times in the temporary result because the show has three related genres. This is not duplication in the stored tables. It is a natural consequence of displaying one row for each relationship.

17. Many-to-Many Relationships

The relationship between shows and people is many-to-many:

  • A show can have many actors.
  • An actor can appear in many shows.

A direct two-table design cannot represent this cleanly without repeating information. The solution is a linking table such as stars:

show_idperson_id
show identifierperson identifier

The linking table contains foreign keys pointing to the shows and people tables.

A similar table called writers can connect shows to the people who wrote them.

Finding the Cast of a Show with Nested Queries

To find the actors in The Office from 2005, the steps are:

  1. Find the show ID for the relevant show.
  2. Find the person IDs associated with that show in stars.
  3. Find the names in people corresponding to those person IDs.

The nested query can express these steps:

SELECT name
FROM people
WHERE id IN (
    SELECT person_id
    FROM stars
    WHERE show_id = (
        SELECT id
        FROM shows
        WHERE title = 'The Office'
          AND year = 2005
    )
);

The innermost query identifies the show. The middle query finds associated people. The outer query converts people IDs into names.

Finding Shows Associated with a Person

The reverse question—finding all shows featuring Steve Carell—can also be expressed with nested queries:

SELECT title
FROM shows
WHERE id IN (
    SELECT show_id
    FROM stars
    WHERE person_id = (
        SELECT id
        FROM people
        WHERE name = 'Steve Carell'
    )
);

The innermost query identifies the person. The middle query finds the shows connected to that person. The outer query retrieves the titles.

Joining Three Tables

The same result can be obtained by joining all three tables:

SELECT title
FROM shows
JOIN stars
  ON shows.id = stars.show_id
JOIN people
  ON stars.person_id = people.id
WHERE name = 'Steve Carell';

This query follows the relationship chain:

shows → stars → people

Another older-style syntax lists all tables after FROM and connects them with conditions in WHERE:

SELECT title
FROM shows, stars, people
WHERE shows.id = stars.show_id
  AND stars.person_id = people.id
  AND name = 'Steve Carell';

Both styles can express the same relationship. Explicit JOIN syntax generally makes the relationship structure easier to read.

Think About It

Why is a third table necessary when both shows and people can be connected to many records?

18. Indexes and Query Performance

A query that works correctly may still be inefficient. When databases contain hundreds of thousands or millions of rows, performance becomes important.

A simple search such as:

SELECT *
FROM shows
WHERE title = 'The Office';

may require the database to examine many titles one by one if no special structure exists.

An index is an additional data structure that makes searching faster.

An index can be created like this:

CREATE INDEX title_index
ON shows(title);

The database builds a structure that helps it locate titles without scanning the entire column from top to bottom.

B-Trees

A common index structure is a B-tree. A B-tree is a tree with many children per node. Unlike a narrow binary tree, it is relatively short and wide.

The shorter height means fewer steps are needed to locate a value. The records or references are found near the leaves of the tree.

The result is that a search can be much faster than a linear scan.

Indexes on Keys

Primary keys are automatically indexed in SQLite. This makes searches involving primary-key columns efficient.

Foreign keys are not necessarily indexed automatically. If a query frequently searches a foreign-key column, an explicit index may help:

CREATE INDEX person_index
ON stars(person_id);
CREATE INDEX show_index
ON stars(show_id);

If searches frequently filter by a person’s name:

CREATE INDEX name_index
ON people(name);

Once the relevant columns are indexed, a query joining shows, stars, and people can become dramatically faster.

The Space-Time Trade-Off

Indexes improve read performance, but they have costs:

  • They require additional storage.
  • They require memory or disk space.
  • Inserts, updates, and deletes may become slightly slower.
  • The database must maintain each index as the underlying data changes.

This is a space-time trade-off: additional space is used to reduce the time required for searches.

Indexing every column is usually unnecessary. Good database design indexes columns that are frequently searched, filtered, or used to connect tables.

Indexes speed up common queries, but every index must be stored and maintained.

19. Combining Python and SQL

SQL does not need to replace Python. The two can work together.

Python can:

  • Ask users for input
  • Create a user interface
  • Run application logic
  • Build a web or mobile application

SQL can:

  • Search database tables
  • Count rows
  • Filter records
  • Group and order results
  • Insert, update, and delete data

A Python program can connect to SQLite and execute a parameterized query:

from cs50 import SQL

db = SQL("sqlite:///favorites.db")

favorite = input("Favorite problem: ")

rows = db.execute(
    """
    SELECT COUNT(*) AS n
    FROM favorites
    WHERE problem = ?
    """,
    favorite
)

row = rows[0]
print(row["n"])

The program works as follows:

  1. The database is opened.
  2. The user enters a problem name.
  3. Python sends an SQL query to the database.
  4. The query counts matching rows.
  5. The result is returned as a temporary collection of rows.
  6. The first row is accessed.
  7. The value in the n column is printed.

The question mark is a placeholder. The user’s input is supplied separately as an argument rather than being directly pasted into the SQL string.

This arrangement combines the strengths of both languages: Python handles interaction, while SQL handles data retrieval.

20. Transactions and Race Conditions

Large applications often have many users making changes at the same time. This introduces a concurrency problem.

Suppose an application stores the number of likes for a post. A naive implementation might:

  1. Read the current number of likes.
  2. Add one in application code.
  3. Write the new number back to the database.

Conceptually:

rows = db.execute(
    "SELECT likes FROM posts WHERE id = ?",
    post_id
)

likes = rows[0]["likes"]

db.execute(
    "UPDATE posts SET likes = ? WHERE id = ?",
    likes + 1,
    post_id
)

This appears correct for one user. However, it can fail when multiple users act simultaneously.

The Race Condition

Suppose a post currently has one million likes. Three users click the like button around the same time.

Each server might read the same value:

1,000,000

Each server then adds one and writes:

1,000,001

The final database value becomes one million and one, even though three likes occurred. Two updates were effectively lost.

This is a race condition: the correctness of the result depends on the timing and order of operations performed by multiple processes.

The Refrigerator Analogy

Consider two roommates who both discover that the refrigerator is out of milk. Each leaves to buy milk. Neither knows that the other person is already purchasing it. They return with two containers even though only one was needed.

Both people made a decision based on the same old state. The problem was that the state was being changed concurrently.

Transactions and Atomicity

A transaction groups multiple database operations into one logical unit.

The operations should be atomic, meaning they either:

  • All complete together, or
  • Do not take effect at all

A transaction prevents other operations from interrupting the grouped work in an unsafe way.

In a Python database library, the structure may be represented conceptually as:

db.execute("BEGIN TRANSACTION")

# Related database operations

db.execute("COMMIT")

The exact syntax varies by library, but the purpose is consistent: protect a sequence of dependent operations from being interleaved incorrectly with operations from other users.

Transactions are essential in systems where many users or servers modify shared data.

Think About It

Why can reading a value, changing it in application code, and writing it back produce an incorrect result when many users act simultaneously?

21. SQL Injection Attacks

Another major database risk comes from using user input unsafely.

Suppose a login system constructs a query by directly inserting a username and password into a formatted string:

query = f"""
SELECT *
FROM users
WHERE username = '{username}'
  AND password = '{password}'
"""

This is dangerous because the user’s input becomes part of the SQL program itself.

How Injection Works

SQL uses single quotes to mark strings. SQLite uses two hyphens, --, to begin a comment. Everything after the comment marker on that line is ignored.

A malicious user might enter a username containing:

someone@example.com' --

When directly inserted into the query, the input can close the string that the programmer started. The -- then causes the password check to be treated as a comment.

The resulting query may effectively check only the username and ignore the password. This could allow someone to log in as another user without knowing that user’s password.

The critical mistake is treating untrusted input as if it were trusted SQL code.

Parameterized Queries

The safe approach uses placeholders:

rows = db.execute(
    """
    SELECT *
    FROM users
    WHERE username = ?
      AND password = ?
    """,
    username,
    password
)

The query structure and the user’s values are supplied separately. The database library escapes or handles dangerous characters so that user input remains data rather than becoming executable SQL syntax.

This distinction is fundamental:

  • Unsafe formatting mixes data with program code.
  • Parameterized queries keep data separate from program code.

A single quote in user input is then treated as an ordinary character rather than the end of a SQL string.

User input should never be directly concatenated into an SQL query. Placeholders and parameterized queries are the standard defense against SQL injection.

22. Comprehensive Review

The central progression is from simple data files to robust database systems.

  1. A spreadsheet stores information in visible rows and columns.
  2. A CSV file represents similar rows and columns using newlines and delimiters.
  3. Python’s csv module reads CSV data without requiring manual parsing.
  4. DictReader makes code more robust by using column names instead of numeric positions.
  5. Dictionaries and Counter objects efficiently count repeated values.
  6. A database stores data in structured tables and supports more powerful operations.
  7. SQL is a declarative language for creating, reading, updating, and deleting data.
  8. SELECT, WHERE, GROUP BY, ORDER BY, LIMIT, and aggregate functions allow concise data analysis.
  9. INSERT, UPDATE, and DELETE modify stored rows and must be used carefully.
  10. Normalization separates repeated information into appropriate tables.
  11. Primary keys uniquely identify rows, while foreign keys connect related tables.
  12. One-to-one, one-to-many, and many-to-many relationships describe how records are associated.
  13. Linking tables make many-to-many relationships possible without repeating full strings.
  14. Nested queries and joins retrieve related information across multiple tables.
  15. Indexes, often implemented with B-trees, make frequent searches faster.
  16. Indexes trade additional space and maintenance work for improved query speed.
  17. Python and SQL can be combined so each handles the job it is best suited to perform.
  18. Transactions protect multi-step operations from race conditions.
  19. Parameterized queries prevent SQL injection by separating user data from SQL code.

A well-designed database stores each fact in an appropriate place, connects related information through keys, protects data with constraints, retrieves information efficiently through queries and indexes, and handles concurrent and untrusted input safely.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent