CS50 Week 7: Data Tools


CS50 Week 7: Data Tools

Simon
Welcome back to CS50. Today we are introducing SQL, or Structured Query Language, but the point is not simply to add another language to the list. The larger lesson is that software engineering involves choosing the right tool for the job. C is powerful, and Python is often more pleasant for certain tasks, but when data becomes large or relational, SQL and databases are usually a better fit.

Anna
And this is part of a broader toolkit for the rest of the course. SQL will help us work with data, while later topics include HTML, CSS, and JavaScript for web programming. The same principle applies to mobile programming too: different problems call for different tools rather than trying to force every problem into C or Python.

Simon
To make the discussion concrete, the class first collected live data with a Google Form. Students chose a favorite programming language and a favorite problem set problem. Google Forms could display the responses in Google Sheets, which stores information in rows and columns much like Microsoft Excel or Apple Numbers.

Anna
But a spreadsheet interface is not the only possible representation. The data can be exported as a CSV file, meaning comma-separated values. In a flat-file database, the data is simply stored as text: newline characters separate rows, and commas or other delimiters separate columns.

Simon
The exported file had three columns: a timestamp added automatically by Google, the selected language, and the selected problem. The first line was a header row describing those columns, so although the file contained about 399 lines, only 398 were actual responses.

Anna
CSV files have a subtle complication. What if a value contains a comma, as in the problem name Hello, World? A program reading the file might mistake that comma for a column separator. CSV conventions solve this by placing strings containing commas inside quotation marks, so the embedded comma is treated as part of the value.

Simon
Python can analyze this file without manually searching for commas or managing memory. You can import Python's csv module, open favorites.csv, and use csv.reader to process the file row by row. The Python functions open and close correspond roughly to fopen and fclose in C.

Anna
A more Pythonic approach is to write 'with open' and indent the file-processing code inside that block. The with statement ensures that the file is closed automatically when execution leaves the block, so the programmer does not have to remember to call close manually.

Simon
With a normal CSV reader, each row is treated like a list. Since Python lists use zero-based indexing, row[0] is the timestamp, row[1] is the language, and row[2] is the problem. Calling next on the reader skips the header row, allowing the loop to process only actual responses.

Anna
That approach works, but it is fragile. If someone moves the columns around in the spreadsheet, row[1] may no longer contain the language. A DictReader is more robust because it uses the header row to create a dictionary for each response. Then the code can ask for row['language'] or row['problem'] by name instead of relying on column positions.

Simon
The remaining assumption is that the column names themselves stay the same. But changing the order of the columns will not break the program. This illustrates a useful design idea: code is generally more reliable when it refers to meaningful names rather than unexplained numeric positions.

Anna
The first counting solution used separate counters for Scratch, C, and Python. Each counter started at zero, and a loop incremented the appropriate counter when it encountered a matching language. Python allows multiple assignments such as scratch, c, python = 0, 0, 0, and it uses plus-equals rather than the plus-plus operator.

Simon
That manual solution works, but a dictionary is a better general-purpose structure. It can associate each language with its count. If a language is already a key, increment its value; otherwise, create the key with a value of one. This works even if a fourth language appears later, without requiring a new variable and another conditional.

Anna
Once the dictionary exists, 'for favorite in counts' iterates over its keys. The sorted function can arrange those keys alphabetically. To sort by the counts instead, sorted can use counts.get as its sorting function, and reverse=True changes the order from smallest-to-largest to largest-to-smallest.

Simon
Those are examples of Python's built-in conveniences. Python supports positional arguments, but it also supports named parameters such as reverse=True. Instead of implementing a sorting algorithm like bubble sort or selection sort ourselves, we can rely on library functionality and focus on the question we want answered.

Anna
Python's collections module provides an even cleaner tool: Counter. A Counter automatically starts unseen items at zero, so the program can simply increment counts[favorite] for every row. Its most_common method then returns key-and-count pairs in popularity order, which can be unpacked into two variables during a loop.

Simon
Because the code refers to a column by name, changing the analysis from languages to problems requires only changing 'language' to 'problem.' In the sample, Hello, World was the most popular problem, followed by Filter and Scratch. The same program can also become interactive: input can ask the user for a particular problem, and the program can print that problem's count.

Anna
That is useful, but large-scale data makes flat files less attractive. A proper database is software running on a computer or server that is designed to store substantial amounts of data and answer questions about it efficiently. A relational database can contain multiple tables, with relationships connecting the data across them.

Simon
SQL is a database-specific, declarative language. Instead of writing loops and conditionals to explain how to find an answer, you describe the data or answer you want, and the database determines how to retrieve it. SQL has a relatively small grammar but can replace many lines of Python for common database operations.

Anna
A useful summary is the CRUD paradigm: Create, Read, Update, and Delete. In SQL, creating data often involves INSERT, reading data uses SELECT, updating uses UPDATE, and deleting can use DELETE. DROP is even more destructive because it can remove an entire database table.

Simon
In CS50, the implementation used is SQLite, a lightweight version of SQL. SQLite has the core functionality of larger systems while being convenient on computers and phones. Many applications, including games and mobile apps, store information in SQLite database files.

Anna
A CSV can be imported into SQLite with the SQLite command-line program. After creating favorites.db, the commands '.mode csv' and '.import favorites.csv favorites' load the data into a table called favorites. The database file is a binary file rather than a plain text file, and it is structured for database operations.

Simon
SQLite-specific commands begin with a dot. For example, '.schema' displays the table design, and '.quit' exits SQLite. SQL commands themselves use keywords such as SELECT and FROM, and they conventionally end with semicolons.

Anna
The basic query 'SELECT * FROM favorites;' returns every column and every row. The star is a wildcard meaning all columns. To select only languages, use 'SELECT language FROM favorites;' and to restrict the number of returned rows, add 'LIMIT 10.'

Simon
SQL also includes functions that resemble spreadsheet functionality. 'COUNT(*)' counts rows, so 'SELECT COUNT(*) FROM favorites;' returns 398 responses. 'DISTINCT' removes duplicates, and nesting functions allows a query such as counting the distinct languages, which returns three for this sample.

Anna
The WHERE keyword filters rows without requiring Python conditionals. For example, 'WHERE language = 'C'' counts only responses selecting C. SQL uses a single equals sign for comparison, and Boolean logic uses words such as AND rather than C's double ampersand.

Simon
GROUP BY handles the dictionary-style counting more directly. Selecting the language and COUNT(*) from favorites, then grouping by language, combines identical language values and counts each group. ORDER BY can sort the result, and DESC produces descending order, giving a popularity ranking such as Python, C, then Scratch.

Anna
SQL also lets you create aliases with AS. For example, COUNT(*) AS n gives the calculated column a shorter name, and the query can then ORDER BY n. Adding LIMIT 1 returns only the most popular item, or just its count if the language column is omitted.

Simon
The other CRUD operations change the database. INSERT INTO favorites, followed by a list of columns and a matching list of VALUES, adds a row. If a value is omitted, the database can store NULL, meaning the absence of a value; in SQL, that does not refer to a memory address or pointer.

Anna
DELETE must be handled carefully. 'DELETE FROM favorites;' removes every row because there is no WHERE condition. A safer example is deleting only rows where timestamp IS NULL. UPDATE works similarly: it can set one or more columns, but without a WHERE clause it changes every row. These operations are destructive, so backups matter.

Simon
The lecture then moved to real-world IMDb data. A first spreadsheet design put a title in one column and multiple star columns beside it. That design is sparse and jagged because different shows have different numbers of stars. A second design used one star column but repeated the show title on every row, which wastes space and creates redundancy.

Anna
A normalized relational design avoids both problems by using separate tables. A shows table stores each show once with a unique ID and title. A people table stores each person once with a unique ID and name. A stars table contains show_id and person_id pairs, connecting shows to the people who star in them.

Simon
Repeating a numeric show ID in the stars table is acceptable because an integer takes far less space than repeatedly storing the full title string. The three-table design may be less immediately readable to a human, but it provides a canonical source of truth and avoids duplicating names and titles.

Anna
IMDb data also included tables such as shows, ratings, genres, people, stars, and writers. Tables can have different data types, including BLOB for binary large objects, INTEGER, NUMERIC, REAL, and TEXT. Databases can also impose constraints such as NOT NULL and UNIQUE to protect data integrity.

Simon
A primary key uniquely identifies a row within its table. The ID in shows is the primary key for that table, while the ID in people is the primary key for people. A foreign key is a reference to a primary key in another table, such as ratings.show_id referring to shows.id.

Anna
The relationship between shows and ratings is one-to-one in this design: each show has one rating row. Genres demonstrate a one-to-many relationship because one show can have several genres. Catweazle, for example, was associated with adventure, comedy, and family.

Simon
The stars table represents a many-to-many relationship. A show can have many stars, and one person can star in many shows. The intermediary table is necessary to connect any number of shows with any number of people without adding endless columns or repeating names.

Anna
Nested queries let SQL use the result of one question inside another. To find highly rated shows, a query can first select show IDs from ratings where rating is at least 6.0, then select titles from shows whose IDs are in that result. This avoids manually copying IDs from one query into another.

Simon
JOIN combines related tables into a temporary result set. Joining shows with ratings on shows.id = ratings.show_id lets us select both a title and its rating. Qualified names such as shows.id and ratings.show_id make it explicit which table each column comes from, especially when column names overlap.

Anna
Joining a one-to-many relationship can produce repeated information in the result set. A show with three genres will appear in three joined rows, one for each genre. That is not duplicate storage in the original database; it is a temporary result that represents each relationship and can be narrowed by selecting only the columns we need.

Simon
To find the stars of The Office from 2005, SQL can first find that show's ID, then find person IDs in the stars table associated with it, and finally find the corresponding names in people. The same result can be expressed with nested queries, with joins across all three tables, or by listing the tables and connecting them with WHERE conditions.

Anna
The writers table has a structure similar to stars: it associates a show with a person, and both IDs act as foreign keys referencing shows and people. The database schema tells us these relationships, although graphical diagrams may require separate software; in SQLite, '.schema' is the main built-in way to inspect the design.

Simon
Performance becomes important with hundreds of thousands or millions of rows. SQLite's timer showed that searching all shows for the title The Office took measurable time. Creating an index on shows.title made repeated searches much faster because the database could use a prepared data structure rather than scanning every row.

Anna
In SQLite, primary keys are indexed automatically, but foreign keys and ordinary columns are not necessarily indexed by default. Adding indexes to stars.person_id, stars.show_id, and people.name made a multi-table search for Steve Carell's shows dramatically faster. Indexes commonly use a B-tree, a short, wide tree that reduces the number of steps needed to find a value.

Simon
Indexes involve a space-time tradeoff. They consume memory or storage, and they must be maintained when rows are inserted, updated, or deleted. So indexing every column can be wasteful; the best strategy is to index columns that applications search frequently.

Anna
Python and SQL can also work together. Python can create a user interface and collect input, while SQL performs database queries. Using the CS50 Python library, a program can open favorites.db, execute a query such as SELECT COUNT(*) AS n FROM favorites WHERE problem = ?, and pass the user's input as the value for the question-mark placeholder.

Simon
The placeholder is important for both correctness and security. The query returns a result set, Python can take its first row, and then print the n column. This division of labor is common: Python handles application behavior, while SQL handles database storage and retrieval.

Anna
Large systems introduce another challenge: race conditions. Suppose a social-media application reads the current number of likes, adds one, and writes the new value back. If several servers read the same old value before any of them writes, they can all store the same incremented value and lose some likes.

Simon
The milk-in-the-refrigerator example illustrates the same problem. Two roommates independently see that there is no milk and both go shopping, because each makes a decision based on a state that the other person's action is already changing. In databases, transactions solve this by making a group of operations atomic: they all happen together, or none of them happens.

Anna
In Python with the CS50 library, code can begin a transaction and commit it after the related operations. That helps prevent requests from interfering with one another and keeps the database's arithmetic consistent.

Simon
The final security issue is SQL injection. It occurs when an application blindly inserts user input into a SQL query. For example, an attacker might enter a quote followed by two hyphens. In SQLite, two hyphens begin a comment, so the input can terminate the intended string and cause the rest of a query, such as a password check, to be ignored.

Anna
Building a query with a Python f-string or manually formatted string is therefore unsafe. A malicious username could transform a query that checks both username and password into one that checks only the username. The user might then gain access without knowing the password.

Simon
The solution is to use parameterized queries with placeholders such as question marks and provide the input separately. The database library escapes dangerous characters appropriately, so user input is treated as data rather than executable SQL. This is why the earlier Python-and-SQL example used a placeholder instead of interpolating the input into an f-string.

Anna
So the major lessons are connected. Use the right language for the task, use databases instead of fragile flat files when data grows, normalize related data into tables, query with SQL's declarative tools, index thoughtfully for performance, use transactions when operations must be atomic, and always parameterize user input to prevent injection.

Simon
That is the foundation for the web and mobile applications coming later in the course. SQL is only being introduced today, but it already gives us a powerful way to store, connect, analyze, and safely modify data at a scale that would make manually written Python loops increasingly unpleasant.

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