CS50 Week 7: Data Tools
Databases, SQL, and Data Analysis
Choosing the Right Tool for the Job
Software development often requires different tools for different tasks. C provides detailed control over memory and computation, while Python offers concise syntax and a large ecosystem of libraries. However, neither C nor Python alone is always the best tool for working with large amounts of structured data.
A database-specific language, SQL, is designed to store, retrieve, analyze, modify, and organize data efficiently. SQL becomes especially useful when data grows beyond a small spreadsheet or text file and must support many users or applications simultaneously.
A typical modern application may combine several technologies:
Python for application logic, user interaction, data processing, or web development.
SQL for querying and managing structured data.
HTML and CSS for structuring and styling web pages.
JavaScript for browser-side interactivity.
SQLite or another database system for persistent data storage.
The general principle is to use the tool that is best suited to each part of the problem rather than forcing one language to handle everything.
Flat-File Databases and CSV Files
Flat Files
The simplest way to store structured data is as a plain text file. A flat-file database is a text file containing data organized into rows and columns using special characters as delimiters.
Common file extensions include:
.txtfor general text files..csvfor comma-separated values.
A flat file is easy to create and transfer, but it becomes increasingly inconvenient as data grows or as applications require fast, safe, simultaneous access.
Representing Rows and Columns in Text
Because a text file does not have graphical rows and columns, it uses characters to simulate them:
A newline character, represented in programming as
\n, separates rows.A comma separates values within a row.
For example:
timestamp,language,problem
2023-10-31 13:00,Python,"Hello, World"
2023-10-31 13:01,C,CreditThe first line is a header row. It names and describes the columns rather than representing an ordinary data record.
CSV Escaping and Quoting
A CSV file becomes ambiguous if a data value contains a comma. For example, the problem name Hello, World contains a comma, but that comma is part of the problem name rather than a column separator.
CSV conventions solve this by placing the entire value in quotation marks:
"Hello, World"A CSV reader can then distinguish between:
Commas that separate columns.
Commas contained inside a quoted value.
Spreadsheet programs such as Google Sheets, Microsoft Excel, and Apple Numbers automatically apply this escaping when exporting data to CSV.
Advantages and Limitations
Advantages of CSV files:
Simple and human-readable.
Easy to export and import.
Portable across platforms and software.
Requires no specialized database software.
Limitations of CSV files:
Searching may require scanning the entire file.
Relationships between different sets of data are difficult to represent.
Data types are not enforced strongly.
Duplicate information is common.
Concurrent access is difficult to manage safely.
Updating or deleting individual records can require rewriting the file.
Large files become cumbersome to process efficiently.
Reading CSV Files with Python
Python provides a built-in csv module for processing comma-separated data. Using this module is preferable to manually searching for commas because it correctly handles quoting, delimiters, and other CSV rules.
Opening and Closing Files
A direct approach uses open and close:
file = open("favorites.csv", "r")
# Work with the file
file.close()The "r" indicates that the file is opened for reading. Reading is the default mode, so the second argument can technically be omitted.
A more common Python approach uses a with statement:
with open("favorites.csv") as file:
# Work with the fileThe with statement automatically closes the file when execution leaves the indented block, including in many situations where an error occurs.
Key idea:
with open(...) as fileis the standard Python pattern for safely opening and automatically closing files.
Using csv.reader
The csv.reader function parses the file and returns rows one at a time:
import csv
with open("favorites.csv") as file:
reader = csv.reader(file)
next(reader)
for row in reader:
print(row[1])Each row is a list. If the file has three columns, the indices are:
row[0]: timestamprow[1]: languagerow[2]: problem
Python lists use zero-based indexing, so the first element has index 0.
Skipping the Header
The first row of a CSV file often contains column names rather than actual data. The next(reader) statement advances the reader past the header:
next(reader)Without this statement, the program might incorrectly process the words timestamp, language, and problem as if they were user responses.
Positional Indexing and Fragility
Code such as the following assumes that the language is always the second column:
favorite = row[1]This is fragile. If someone moves, deletes, or inserts a column in the spreadsheet, the program may read the wrong data without producing an obvious error.
Reading CSV Files with DictReader
Python's csv.DictReader provides a more robust way to process CSV files. Instead of representing each row as a list, it represents each row as a dictionary whose keys come from the header row.
import csv
with open("favorites.csv") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["language"])Each row behaves conceptually like:
{
"timestamp": "...",
"language": "Python",
"problem": "Hello, World"
}The program refers to a column by name rather than by position:
favorite = row["language"]Advantages of DictReader
The header row is processed automatically.
There is no need to call
next(reader).Columns can be reordered without breaking the program.
Code is easier to understand.
The program depends only on column names rather than column positions.
The code still assumes that the column is actually named "language". Renaming the header would require changing the program.
Key idea:
DictReaderreduces dependence on a spreadsheet's physical layout by accessing values through meaningful column names.
Counting Values in Python
Suppose a dataset records favorite programming languages. The goal is to count how many people selected Scratch, C, and Python.
Manual Counters
One approach creates one variable for each possible value:
scratch = 0
c = 0
python = 0Python supports multiple assignment:
scratch, c, python = 0, 0, 0The program can then examine each row:
for row in reader:
favorite = row["language"]
if favorite == "Scratch":
scratch += 1
elif favorite == "C":
c += 1
elif favorite == "Python":
python += 1Python does not use the C-style ++ operator. Instead, the usual increment syntax is:
scratch += 1After processing all rows, formatted strings can display the results:
print(f"Scratch: {scratch}")
print(f"C: {c}")
print(f"Python: {python}")An f-string allows expressions inside curly braces to be evaluated and inserted into a string.
Problems with Manual Counters
This method works, but it has several disadvantages:
It requires a separate variable for every possible value.
New languages require new variables and new conditional branches.
The code becomes longer as the number of categories grows.
It duplicates the structure of the data in the program itself.
A dictionary is a better general-purpose solution.
Counting with Dictionaries
A dictionary associates keys with values. For this problem:
The key is a language name.
The value is the number of times that language has appeared.
The program begins with an empty dictionary:
counts = {}For each row, it checks whether the language has already appeared:
for row in reader:
favorite = row["language"]
if favorite in counts:
counts[favorite] += 1
else:
counts[favorite] = 1The logic is:
Extract the current language.
Check whether it is already a key in
counts.If it is present, increment its value.
If it is absent, create the key with an initial count of 1.
The final dictionary might look conceptually like:
{
"Python": 280,
"C": 78,
"Scratch": 40
}Iterating over Dictionary Keys
Python can iterate directly over a dictionary's keys:
for favorite in counts:
print(f"{favorite}: {counts[favorite]}")This approach automatically handles any number of languages. If a new language appears in the file, the program creates a new key without requiring additional code.
Key idea: A dictionary is useful whenever a program must associate each category with a changing value, such as a count.
Sorting Results
Sorting by Key
The built-in sorted function can sort dictionary keys alphabetically:
for favorite in sorted(counts):
print(f"{favorite}: {counts[favorite]}")By default, sorting a dictionary iterates through its keys.
Sorting by Value
To sort according to the counts rather than the language names, 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]}")The expression counts.get is a reference to a dictionary method. For each key, sorted uses that method to obtain the associated count.
Reverse Sorting
By default, sorting is ascending. The reverse named parameter reverses the order:
for favorite in sorted(counts, key=counts.get, reverse=True):
print(f"{favorite}: {counts[favorite]}")This produces a ranking from most common to least common.
Python functions can accept:
Positional arguments, whose meaning depends on their position.
Named arguments, such as
key=counts.getandreverse=True.
Named arguments make code more explicit and allow optional parameters to be selected without specifying every earlier parameter.
The Counter Class
Python's collections module provides a specialized class called Counter for counting values.
from collections import Counter
counts = Counter()The counting loop becomes shorter:
for row in reader:
favorite = row["language"]
counts[favorite] += 1A Counter automatically treats an unseen key as having a count of zero, so the program does not need an explicit if statement.
Finding the Most Common Values
The most_common method returns pairs containing each key and its count, ordered from most common to least common:
for favorite, count in counts.most_common():
print(f"{favorite}: {count}")Python supports unpacking multiple values during iteration:
for favorite, count in counts.most_common():On each iteration, the key is assigned to favorite and the corresponding count is assigned to count.
Reusing General-Purpose Code
If the program uses dictionary-like access rather than hard-coded language names, the same code can analyze favorite problems instead of favorite languages. Changing:
favorite = row["language"]to:
favorite = row["problem"]is sufficient to count the problems.
This illustrates the value of writing general-purpose code: the same algorithm can answer different questions by changing the field being analyzed.
Interactive Data Analysis in Python
Instead of printing every category, a program can ask the user about one specific category:
favorite = input("Favorite problem: ")
for favorite, count in counts.most_common():
...Or, after building the counter, it can look up a particular value:
print(counts[favorite])This makes the program interactive. A user can enter a problem name and receive its count.
Interactive data analysis follows a common pattern:
Ask a question or receive input.
Query or process the data.
Return the requested answer.
This pattern is central to data analysis, consulting, web applications, search systems, and many other fields.
Relational Databases and SQL
Why Use a Database?
A CSV file is a simple form of storage, but a database is a specialized software system designed to manage large collections of data.
A database program can:
Store large quantities of data.
Search data efficiently.
Enforce rules about valid data.
Support multiple tables.
Represent relationships between data.
Handle many users and requests.
Perform updates and deletions.
Provide specialized query operations.
Use indexes to accelerate searches.
A database may run on a local computer, a phone, or a remote server. Unlike a flat file, it actively manages the data and provides tools for accessing it.
Relational Databases
A relational database stores information in multiple tables and allows relationships between those tables.
A table resembles a spreadsheet:
Rows represent records.
Columns represent attributes or fields.
Each table represents a particular type of entity or relationship.
The word relational refers to the relationships among tables, not merely to the rows and columns inside one table.
SQL
SQL, or Structured Query Language, is a declarative language used to interact with relational databases.
SQL is declarative because the programmer describes what data is wanted rather than explicitly writing every procedural step required to retrieve it.
In Python, a programmer might write:
A loop over every row.
An
ifstatement for each category.A dictionary or counter.
Sorting logic.
In SQL, the programmer can state the desired result using a compact query. The database system determines how to perform the operation.
SQL has a relatively small grammar but provides powerful built-in operations for:
Filtering.
Counting.
Grouping.
Sorting.
Joining tables.
Inserting records.
Updating records.
Deleting records.
The CRUD Paradigm
Most database operations fall into four broad categories, known as CRUD:
Create: Add new data or database structures.
Read: Retrieve or analyze existing data.
Update: Modify existing data.
Delete: Remove data.
SQL keywords associated with CRUD include:
INSERTfor adding rows.SELECTfor reading or retrieving data.UPDATEfor changing existing rows.DELETEfor removing rows.CREATE TABLEfor defining a table.DROPfor destructively removing an entire table or database object.
DROP is especially dangerous because it can remove an entire table rather than merely deleting selected rows.
SQLite
SQLite as an SQL Implementation
Different database systems implement SQL with minor differences. SQL is standardized, but vendors may add their own features or interpret some details differently.
SQLite is a lightweight implementation of SQL. It is widely used in:
Mobile applications.
Games.
Desktop software.
Embedded systems.
Mac and PC applications.
SQLite stores a database in a file, often with a .db extension. The database file is generally a binary file containing data in a format optimized for database operations.
SQLite includes the core relational database functionality needed for many applications while remaining relatively small and easy to use.
Creating and Loading a Database
A CSV file can be imported into SQLite. Conceptually, the process is:
Start SQLite and specify a new database file.
Tell SQLite that the input uses CSV formatting.
Import the CSV file into a named table.
Exit SQLite.
The imported CSV becomes a table inside the database. Future operations can use SQL rather than repeatedly parsing the text file.
SQLite also provides commands beginning with a period, such as:
.mode csvto set CSV mode..importto import a file..schemato inspect table definitions..timer onto measure query execution time..quitto exit SQLite.
These dot commands are SQLite-specific rather than standard SQL.
SQL Tables and Basic Queries
Inspecting a Schema
A table's schema describes its structure:
Table name.
Column names.
Data types.
Constraints.
Primary keys.
Foreign keys.
The schema is conceptually equivalent to the table definition created with CREATE TABLE.
For example, a table containing survey responses might have:
timestamplanguageproblem
A more carefully designed television database might have:
An ID.
A title.
A debut year.
A number of episodes.
Selecting Data
The basic SQL retrieval operation uses SELECT and FROM:
SELECT column
FROM table;To retrieve every column:
SELECT *
FROM favorites;The asterisk * is a wildcard meaning all columns.
To retrieve only the language column:
SELECT language
FROM favorites;SQL statements conventionally end with a semicolon.
Limiting Results
The LIMIT clause restricts the number of rows returned:
SELECT language
FROM favorites
LIMIT 10;This returns the first 10 matching rows. It does not necessarily return the 10 most significant or highest-ranked rows unless the query also specifies an ordering.
Aggregate Functions
SQL provides built-in functions for summarizing data.
Counting Rows
To count all rows:
SELECT COUNT(*)
FROM favorites;COUNT(*) counts rows regardless of column names or values. If every row contains the same number of columns, counting a particular column may produce the same result, but COUNT(*) clearly expresses the intention to count rows.
Distinct Values
The DISTINCT keyword removes duplicate values:
SELECT DISTINCT language
FROM favorites;This might return:
Python
Scratch
C
The result can also be counted:
SELECT COUNT(DISTINCT language)
FROM favorites;SQL functions can be nested. The output of DISTINCT becomes the input to COUNT.
Other common SQL aggregate or data-processing functions include operations for:
Averages.
Minimum values.
Maximum values.
Counts.
Distinct values.
Lowercase or uppercase conversion.
Filtering with WHERE
The WHERE clause filters rows according to a condition:
SELECT COUNT(*)
FROM favorites
WHERE language = 'C';This query counts only rows where the language is C.
SQL uses a single equals sign for equality comparison:
language = 'C'This differs from C and Python, where equality is generally written using ==.
SQL uses logical operators such as:
ANDORNOT
For example:
SELECT COUNT(*)
FROM favorites
WHERE language = 'C'
AND problem = 'Hello, World';String values are conventionally written in single quotes. Numeric values do not require quotation marks:
year = 2005Grouping Data with GROUP BY
GROUP BY combines rows that have the same value in a specified column.
To count responses for each language:
SELECT language, COUNT(*)
FROM favorites
GROUP BY language;Conceptually, the database:
Places all rows with the same language into one group.
Counts the rows in each group.
Returns one result row per language.
This single query replaces the longer Python approach involving:
Separate counters.
Conditional branches.
Manual dictionary management.
The same pattern can count problems:
SELECT problem, COUNT(*)
FROM favorites
GROUP BY problem;Sorting with ORDER BY
ORDER BY sorts a result set.
Ascending order is the default:
SELECT language, COUNT(*)
FROM favorites
GROUP BY language
ORDER BY COUNT(*);Descending order uses DESC:
SELECT language, COUNT(*)
FROM favorites
GROUP BY language
ORDER BY COUNT(*) DESC;The abbreviations are:
ASC: ascending.DESC: descending.
A descending query can produce a ranking from most popular to least popular.
Aliases with AS
Long expressions can be given temporary names using AS:
SELECT language, COUNT(*) AS n
FROM favorites
GROUP BY language
ORDER BY n DESC;Here, n is an alias for COUNT(*). The alias applies to the result set and makes later references shorter and clearer.
Top Results
A top-one query can combine sorting and limiting:
SELECT language, COUNT(*) AS n
FROM favorites
GROUP BY language
ORDER BY n DESC
LIMIT 1;This returns the most popular language and its count.
Inserting, Updating, and Deleting Data
Inserting Rows
The INSERT INTO command adds a new row:
INSERT INTO favorites (language, problem)
VALUES ('SQL', 'Fiftyville');The first parenthesized list names the columns receiving data. The second list provides the corresponding values.
The values must align with the columns in order:
languagereceives'SQL'.problemreceives'Fiftyville'.
Columns not specified may receive a missing value represented by NULL, if the schema allows it.
NULL
NULL represents the absence of a value. In SQL, it does not mean zero, an empty string, or a memory address. It indicates that no value is present.
For example, if a timestamp was not supplied, the timestamp field may be NULL.
SQL uses special logic when testing for missing values. A condition involving NULL is generally tested using IS NULL rather than = NULL:
WHERE timestamp IS NULLUpdating Rows
The UPDATE command changes existing records:
UPDATE favorites
SET language = 'SQL',
problem = 'Fiftyville';Without a WHERE clause, this updates every row in the table.
A safer, targeted update includes a condition:
UPDATE favorites
SET language = 'SQL'
WHERE problem = 'Fiftyville';Updates can be highly destructive because SQL does not automatically provide a general undo operation. Backups are essential when modifying important data.
Deleting Rows
The DELETE FROM command removes rows:
DELETE FROM favorites
WHERE timestamp IS NULL;This removes only rows whose timestamp is missing.
The following command is extremely dangerous:
DELETE FROM favorites;Without a WHERE clause, it deletes every row in the table.
Similarly, DROP can remove an entire table or database object. Database administrators should use destructive commands carefully and maintain reliable backups.
Database Design and Normalization
Poor Design: Repeated Star Columns
Suppose a spreadsheet records television shows and their actors:
Title | Star 1 | Star 2 | Star 3 | Star 4 |
|---|
This design has a variable number of star columns. Some shows may have one major actor, while others may have many. The result is a sparse or jagged table with many empty cells.
Problems include:
An arbitrary limit on the number of stars.
Many unused columns.
Difficult queries.
Inconsistent row structure.
The need to keep adding columns as requirements change.
Poor Design: Repeating Show Titles
Another design may use one star column:
Title | Star |
|---|---|
The Office | Steve Carell |
The Office | Rainn Wilson |
The Office | John Krasinski |
This solves the variable-column problem but repeats the title in every row.
Repeated strings cause:
Wasted storage.
Increased risk of typographical inconsistencies.
Difficult updates.
Possible contradictions if one copy is changed and another is not.
Normalized Design
A more robust relational design separates distinct entities into different tables.
Shows Table
The shows table stores each show once:
idtitleyearepisodes
People Table
The people table stores each person once:
idname
Stars Table
The stars table connects shows to people:
show_idperson_id
The same show ID may appear multiple times in stars, once for each person associated with that show. Repeating compact numeric IDs is much more efficient than repeating long text strings such as "The Office".
Key idea: Normalization stores each fact in one canonical place and uses relationships to connect facts rather than duplicating large values.
This design may be less immediately readable to humans because the complete information is distributed across tables. However, it improves consistency, reduces redundancy, and supports efficient database operations.
Keys and Relationships
Primary Keys
A primary key is a column, or combination of columns, that uniquely identifies each row in a table.
Examples:
shows.iduniquely identifies a show.people.iduniquely identifies a person.
A primary key should be:
Unique.
Stable.
Present for every row.
Suitable for identifying a record unambiguously.
Primary keys are often integers because integers use relatively little storage and are efficient for comparisons and indexing.
Foreign Keys
A foreign key is a column containing values that refer to primary keys in another table.
For example:
ratings.show_idrefers toshows.id.stars.show_idrefers toshows.id.stars.person_idrefers topeople.id.
Foreign keys establish relationships across tables.
The term foreign is relative: a value may be the primary key in its original table but function as a foreign key when it appears in another table.
Constraints
Databases can enforce rules that spreadsheets generally do not enforce automatically.
NOT NULL
A NOT NULL constraint requires a value to be present:
title TEXT NOT NULLThis prevents rows from being inserted without a title.
UNIQUE
A UNIQUE constraint prevents duplicate values:
email TEXT UNIQUEThis can ensure that a user registers only one account per email address.
Constraints help protect data integrity by preventing invalid or contradictory data from entering the database.
SQL Data Types
SQLite supports several broad data types.
BLOB
A BLOB, or Binary Large Object, stores binary data such as raw bytes or files. In many applications, files are better stored in a file system, with the database storing only their paths or identifiers.
INTEGER
An integer stores whole-number values.
Examples include:
IDs.
Counts.
Number of episodes.
Number of votes.
NUMERIC
NUMERIC represents numeric-like data that may include dates, times, or other values that are not strictly integers or floating-point values.
REAL
REAL stores numbers with decimal portions, such as ratings.
TEXT
TEXT stores strings, such as:
Names.
Titles.
Genres.
Languages.
Other database systems may provide more specialized types, but these categories represent core SQL data types.
Relationships Between Tables
One-to-One Relationships
A one-to-one relationship means each row in one table corresponds to one row in another table.
In the television database:
Each show has one rating.
Each rating belongs to one show.
The shows table and ratings table could technically be combined into one wider table. They remain separate because database designers may choose to organize related information into distinct tables.
One-to-Many Relationships
A one-to-many relationship means one row in one table can correspond to many rows in another table.
For example:
One show can have multiple genres.
The
genrestable may contain several rows with the sameshow_id.
A show such as Catweazle could be associated with:
Adventure.
Comedy.
Family.
The relationship is represented by multiple rows rather than multiple genre columns.
Many-to-Many Relationships
A many-to-many relationship occurs when:
One show can have many people.
One person can appear in many shows.
This requires an intermediate table, sometimes called a junction table or association table.
The stars table connects:
shows.idpeople.id
Each row represents one association between one show and one person.
The same design applies to writers:
A show can have multiple writers.
A person can write multiple shows.
A
writerstable connects show IDs and person IDs.
Nested Queries and Subqueries
A subquery is a query placed inside another query. It allows the database to use the result of one operation as input to another.
To find shows whose ratings are at least $6.0:
SELECT *
FROM shows
WHERE id IN (
SELECT show_id
FROM ratings
WHERE rating >= 6.0
);The inner query first produces a set of show IDs. The outer query then retrieves rows from shows whose IDs appear in that set.
A subquery is useful when the desired information is distributed across tables but the programmer wants to avoid manually copying values from one query into another.
Nested queries can be composed in several levels. For example, finding all shows starring Steve Carell can involve:
Finding Steve Carell's person ID.
Finding show IDs associated with that person in
stars.Finding titles associated with those show IDs in
shows.
Conceptually:
SELECT title
FROM shows
WHERE id IN (
SELECT show_id
FROM stars
WHERE person_id IN (
SELECT id
FROM people
WHERE name = 'Steve Carell'
)
);The innermost query is evaluated first, followed by the surrounding queries.
Joining Tables
Purpose of JOIN
A JOIN combines related rows from multiple tables into a temporary result set.
For example, the shows table may contain:
Show ID.
Title.
Year.
Episodes.
The ratings table may contain:
Show ID.
Rating.
Votes.
A query joining the tables can return the show title and rating together:
SELECT title, rating
FROM shows
JOIN ratings
ON shows.id = ratings.show_id
WHERE rating >= 6.0
LIMIT 10;The ON clause specifies how the rows correspond:
shows.id = ratings.show_idThe same value is a primary key in one table and a foreign key in the other.
Qualified Column Names
When multiple tables are involved, table-qualified names make the query explicit:
shows.id
ratings.show_idThe dot notation means “the specified column from the specified table.” It is especially useful when multiple tables contain columns with the same name.
Join Results and Temporary Duplication
A one-to-one join generally produces one wider row for each original row.
A one-to-many join may repeat information in the result set. For example, joining a show with its genres may produce:
title | genre |
|---|---|
Catweazle | Adventure |
Catweazle | Comedy |
Catweazle | Family |
The title is repeated in the temporary result because it is being paired with multiple genres. This does not mean the original shows table stores the title multiple times. The repeated rows exist only in the query's result set.
This temporary duplication is useful because it makes related information easy to inspect and analyze.
Querying Many-to-Many Relationships
To find the people associated with The Office from 2005, the database must travel through three tables:
showsidentifies the correct show.starsmaps the show ID to person IDs.peopleconverts person IDs into names.
A nested-query approach is:
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 same task can be solved by joining all three tables:
SELECT people.name
FROM shows
JOIN stars
ON shows.id = stars.show_id
JOIN people
ON stars.person_id = people.id
WHERE shows.title = 'The Office'
AND shows.year = 2005;Another equivalent style lists tables separated by commas and connects them with WHERE conditions:
SELECT people.name
FROM shows, stars, people
WHERE shows.id = stars.show_id
AND stars.person_id = people.id
AND shows.title = 'The Office'
AND shows.year = 2005;The explicit JOIN syntax is generally clearer and more modern, but the approaches express the same relationships.
Combining Python and SQL
SQL is effective for querying databases, while Python is useful for user interfaces, application logic, and web development. They can be used together.
A Python program can:
Open a database connection.
Ask the user for input.
Execute an SQL query.
Receive the result set.
Display or process the result.
Conceptually:
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 Python program handles input and output, while SQL performs the database query.
Parameterized Queries
The question mark is a placeholder. The actual user input is supplied separately as an argument.
WHERE problem = ?This approach is safer than constructing a query by directly inserting user input into a string.
The database library treats the supplied value as data rather than as SQL code.
Key idea: One language can be embedded within another so that each language handles the task it is best suited for.
Indexes and Query Performance
Measuring Query Time
Database systems can measure how long queries take. Timing helps identify inefficient operations and evaluate the effect of indexes.
A query that searches for a title may initially scan every row in the table. This is effectively a linear search.
If the table contains hundreds of thousands or millions of rows, a linear search can become expensive.
What Is an Index?
An index is an additional data structure that helps a database find rows more quickly.
An index can be created on a frequently searched column:
CREATE INDEX title_index
ON shows(title);Once the index exists, queries filtering by title can become much faster:
SELECT *
FROM shows
WHERE title = 'The Office';Creating the index itself may take time, but it is generally a one-time setup operation. The database must maintain the index when rows are inserted, updated, or deleted.
B-Trees
Database indexes are commonly implemented using a B-tree.
A B-tree is a balanced, wide tree:
A node can have many children.
The tree is shorter than a binary tree with the same number of values.
Values are typically found at the leaves.
The small height reduces the number of steps required to locate a value.
The database can therefore search an indexed column much more efficiently than scanning every value from top to bottom.
Primary keys are generally indexed automatically, at least in SQLite. Foreign keys and ordinary text columns are not necessarily indexed automatically.
For a query involving shows, stars, and people, useful indexes might include:
CREATE INDEX person_index
ON stars(person_id);
CREATE INDEX show_index
ON stars(show_id);
CREATE INDEX name_index
ON people(name);These indexes can greatly accelerate searches involving:
stars.person_idstars.show_idpeople.name
Index Trade-Offs
Indexes exchange storage space and update cost for faster reads.
Benefits
Faster searches.
Faster joins involving indexed columns.
Better performance for large datasets.
Greater capacity for handling many users.
Costs
Additional storage space.
Slower inserts, updates, and deletes because indexes must be maintained.
Time required to create and maintain the index.
Unnecessary indexes may waste resources.
Therefore, it is usually better to index columns that are frequently searched, joined, or sorted rather than indexing every column automatically.
Key idea: Indexes are a space-for-time trade-off: they consume additional resources to make common queries faster.
Race Conditions and Transactions
The Read-Modify-Write Problem
Consider a system that tracks the number of likes on a post. A naive implementation may:
Read the current number of likes.
Add one in application code.
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 may appear correct for one user, but it can fail when many users act simultaneously.
Race Conditions
A race condition occurs when multiple operations access and modify shared data concurrently, and the result depends on the order in which those operations occur.
Suppose a post has 1,000,000 likes and three users click “like” nearly simultaneously:
Server A reads 1,000,000.
Server B reads 1,000,000.
Server C reads 1,000,000.
Each server computes 1,000,001.
Each server writes 1,000,001.
The final value is 1,000,001 rather than 1,000,003. Two likes have been lost.
The problem is that each operation read stale data before another operation's update became visible.
The Shared-Milk Analogy
A similar problem occurs when two roommates independently inspect an empty refrigerator, decide to buy milk, and both return with milk. Each person made a decision based on the same old state, unaware that the other person was already updating that state.
The database equivalent is that multiple requests make decisions based on the same old counter value.
Transactions
A transaction groups several database operations into one logical unit.
A transaction should be atomic:
Either all operations occur.
Or none of them occur.
No other operation should interrupt the transaction midway.
A transaction can be represented conceptually as:
db.execute("BEGIN TRANSACTION")
# Read and update related data
db.execute("COMMIT")Transactions prevent other operations from observing an inconsistent intermediate state and help ensure that concurrent updates are processed safely.
Transactions are especially important for:
Counters.
Financial transfers.
Inventory updates.
Reservations.
Account balances.
Any operation involving multiple dependent changes.
SQL Injection Attacks
The Danger of Direct String Construction
Applications often use user input in database queries. If user input is inserted directly into an SQL string, a malicious user may supply SQL syntax rather than ordinary data.
Unsafe code may look conceptually like:
query = f"""
SELECT *
FROM users
WHERE username = '{username}'
AND password = '{password}'
"""The problem is that the user controls part of the SQL statement. Special characters can alter the meaning of the query.
SQL Comments
In SQLite, two hyphens begin a comment:
--Everything after the comment marker on that line is ignored by the database.
Suppose a malicious user enters a username containing:
user@example.com'--When directly interpolated into the unsafe query, the quotation mark may close the developer's string literal, and -- may cause the password check to be ignored.
The resulting query may effectively check only the username and disregard the password. An attacker could then gain access to an account by knowing or guessing a username.
Parameterized Queries as the Solution
The safe approach uses placeholders:
rows = db.execute(
"""
SELECT *
FROM users
WHERE username = ?
AND password = ?
""",
username,
password
)The database library separates:
The SQL command.
The user-provided values.
The values are escaped or encoded so that quotation marks, comment characters, and other special input are treated as data rather than executable SQL.
Key idea: User input must never be inserted directly into SQL strings. Parameterized queries prevent SQL injection by separating code from data.
Escaping Special Characters
SQL systems use escaping rules to represent literal special characters safely. In SQL, a single quote inside a string may be represented using two single quotes. Database libraries normally handle this escaping automatically when placeholders are used.
The exact syntax can vary among database systems, but parameterized queries are the standard defense against SQL injection.
Core SQL Concepts to Remember
Essential Commands
CREATE TABLE: Defines a table and its columns.INSERT INTO: Adds rows.SELECT: Retrieves data.UPDATE: Modifies rows.DELETE: Removes rows.DROP: Removes an entire database object.JOIN: Combines related tables.WHERE: Filters rows.GROUP BY: Groups rows with common values.ORDER BY: Sorts results.LIMIT: Restricts the number of returned rows.DISTINCT: Removes duplicate values.AS: Creates an alias.COUNT: Counts rows or values.
Essential Database Ideas
CSV files are simple flat-file databases.
SQL is a declarative language for relational databases.
Tables contain rows and columns.
Primary keys uniquely identify rows.
Foreign keys connect tables.
Normalization reduces redundant data.
One-to-one relationships connect one row to one row.
One-to-many relationships connect one row to multiple rows.
Many-to-many relationships require an intermediate table.
Subqueries use one query's result inside another.
Joins combine related tables into a temporary result set.
Indexes speed up frequent searches.
Transactions prevent inconsistent concurrent updates.
Parameterized queries prevent SQL injection attacks.
A well-designed database stores each fact once, connects related facts through keys, uses indexes selectively for performance, and protects multi-step operations and user input through transactions and parameterized queries.

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