CS50 Week 7: Data Tools
- 98Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
Why is it useful for programmers to choose different languages or tools for different tasks?
98 questions
- 1
Why is it useful for programmers to choose different languages or tools for different tasks?
Model answer
Different tools are optimized for different jobs. For example, Python can make some tasks more pleasant than C, while SQL is better suited to querying large amounts of database data.
Explanation
Using one language for every problem can make development unnecessarily difficult. The goal is to select the tool that minimizes effort and best matches the task.
- 2
What is a flat-file database?
Model answer
A flat-file database is a text file containing data, commonly using delimiters to separate values.
Explanation
Files ending in
.txtor.csvcan serve as simple databases, although they lack many capabilities of full database systems. - 3
How do CSV files represent rows and columns using plain text?
Model answer
Newline characters separate rows, while commas or other delimiters separate values within a row to represent columns.
Explanation
Because a text file has no graphical rows or vertical columns, special characters imitate that structure.
- 4
Why are CSV files considered globally portable?
Model answer
CSV files use a simple, widely understood text format rather than a proprietary spreadsheet format, so they can be exported and opened by many programs.
Explanation
Google Sheets, Excel, and Numbers can export data as CSV, allowing the same data to be used across platforms.
- 5
How does a CSV file handle a field that contains a comma?
Model answer
The field is surrounded by quotation marks so that its internal comma is not mistaken for a column delimiter.
Explanation
For example, a value such as
Hello, Worldmust be quoted when stored in a CSV file. - 6
What information did the three columns in the favorites CSV file represent?
Model answer
The columns were
timestamp,language, andproblem.Explanation
The language and problem came from users' responses, while the timestamp was added automatically.
- 7
What is a header row in a CSV file, and why might a program skip it?
Model answer
A header row contains column names rather than ordinary data. A program may skip it so that the column descriptions are not processed as responses.
Explanation
In the favorites file, the header identified
timestamp,language, andproblemand therefore was metadata. - 8
How can Python read a CSV file using the
csvmodule?Model answer
A program imports
csv, opens the file, passes it tocsv.readerorcsv.DictReader, and iterates over the resulting reader.Explanation
The module handles locating delimiters and returning rows, avoiding the need to parse commas manually.
- 9
What is the difference between
csv.readerandcsv.DictReader?Model answer
csv.readerreturns each row as a list accessed by numeric indices, whereascsv.DictReaderuses the header row to return each row as a dictionary keyed by column names.Explanation
With a regular reader, the language is accessed as
row[1]; with a dictionary reader, it is accessed asrow["language"]. - 10
Why is accessing a CSV field by its column name more robust than accessing it by a numeric index?
Model answer
Column-name access continues to work if columns are moved, whereas numeric indexing assumes that a particular value will always remain at the same position.
Explanation
The code still depends on the column name remaining unchanged, but it is less vulnerable to rearranged columns.
- 11
What does Python's
with open(...)construct do for a file?Model answer
It opens the file for use within an indented block and automatically closes the file when execution leaves that block.
Explanation
This is a Pythonic alternative to explicitly calling
openand later callingclose, including when the block finishes normally. - 12
How does Python's zero-based indexing affect access to the three CSV columns?
Model answer
The first, second, and third columns have indices 0, 1, and 2, respectively, so
row[1]accesses the middle column.Explanation
For the favorites data, index 0 refers to the timestamp, index 1 to the language, and index 2 to the problem.
- 13
How can separate counters be used to count responses for Scratch, C, and Python?
Model answer
Initialize each counter to zero, inspect the language in every row, and increment the matching counter whenever that language appears.
Explanation
The program uses conditional branches such as
ifandelif; Python uses+= 1rather than the C-style++operator. - 14
What is Python tuple or multiple assignment, and how can it simplify counter initialization?
Model answer
Multiple assignment lets several variables receive values in one statement, such as assigning zero to the Scratch, C, and Python counters simultaneously.
Explanation
The effect is equivalent to writing three separate assignments, but the code is shorter.
- 15
Why is a dictionary a suitable data structure for counting categories?
Model answer
A dictionary associates each category as a key with its count as a value, allowing the program to update counts by category name.
Explanation
For example, the key
Pythoncan map to the number of responses selecting Python. - 16
How can a program update a dictionary-based counter when processing a row?
Model answer
If the category is already a key, increment its value; otherwise, create the key with an initial value of one.
Explanation
The first occurrence must start at one because the current row has already been observed.
- 17
What does
if favorite in countstest in Python?Model answer
It tests whether
favoriteis already a key in thecountsdictionary.Explanation
This determines whether the program should increment an existing count or initialize a new category.
- 18
How can Python iterate over all keys in a dictionary?
Model answer
A loop such as
for favorite in countsiterates through the dictionary's keys.Explanation
Each iteration assigns one key to the loop variable, which can then be used to retrieve its associated value.
- 19
What does Python's
sortedfunction do when applied to a dictionary in this context?Model answer
It provides the dictionary's keys in sorted order, which by default is alphabetical or ascending by key.
Explanation
Sorting the keys changes the order in which the categories are displayed, not the counts themselves.
- 20
How can
sortedbe instructed to order dictionary keys by their values instead of their keys?Model answer
Pass the dictionary's
getmethod as the sorting key, such askey=counts.get.Explanation
For each dictionary key,
counts.getsupplies its associated count, so sorting is based on the right-hand value. - 21
How can Python sort results from largest count to smallest count?
Model answer
Use the named argument
reverse=Truewithsorted.Explanation
The default order is ascending, so reversing it produces descending order.
- 22
What is the distinction between positional arguments and named parameters in Python?
Model answer
Positional arguments are interpreted according to their order, while named parameters are supplied using explicit parameter names.
Explanation
Named parameters make it clear which optional behavior is being selected and do not depend solely on argument position.
- 23
What is the purpose of Python's
Counterclass?Model answer
Counteris a specialized object that automatically keeps track of counts for values.Explanation
It initializes unseen items to zero, so a program can increment a category without manually testing whether the key exists.
- 24
What does the
most_commonmethod of aCounterreturn?Model answer
It returns category-count pairs ordered from the most common category to the least common.
Explanation
The pairs can be unpacked into two loop variables, such as a favorite and its count.
- 25
How could the Python counting program be changed to count favorite problems instead of favorite languages?
Model answer
Change the dictionary lookup from the
languagefield to theproblemfield.Explanation
The rest of the counting logic can remain the same because it treats the selected field generically as a category.
- 26
What does it mean for a Python data-analysis program to be interactive?
Model answer
It accepts input from a user and uses that input to query or analyze data before displaying a result.
Explanation
The example uses
inputto ask for a problem name and then reports that problem's count. - 27
What is SQL, and what does its name stand for?
Model answer
SQL is a database-specific language that stands for Structured Query Language.
Explanation
It is designed for working with relational databases rather than general-purpose programming tasks.
- 28
Why is SQL described as a declarative language?
Model answer
SQL describes the data or result a user wants rather than usually specifying loops and step-by-step control flow for obtaining it.
Explanation
The database system determines how to execute the request from the relatively small SQL grammar.
- 29
What does the CRUD paradigm represent?
Model answer
CRUD represents Create, Read, Update, and Delete, the four fundamental operations performed on stored data.
Explanation
Relational database systems provide commands corresponding to these basic operations.
- 30
Which SQL keywords correspond to the CRUD operations?
Model answer
Create commonly uses
INSERT, read usesSELECT, update usesUPDATE, and delete usesDELETE;DROPcan delete an entire table.Explanation
The word “read” is usually expressed as selecting data, while
DROPis a particularly destructive deletion operation. - 31
What is a relational database?
Model answer
A relational database stores data in multiple tables whose rows and columns can be connected through relationships.
Explanation
Unlike a single spreadsheet, a relational database can distribute related information across many tables while linking it systematically.
- 32
What is SQLite, and why was it used in this context?
Model answer
SQLite is a lightweight implementation of SQL that provides core relational-database functionality in a compact format.
Explanation
It is widely used on computers and mobile devices and is suitable for learning database fundamentals.
- 33
What is the difference between a SQLite database file and a CSV file?
Model answer
A CSV file is plain text organized with delimiters, whereas a SQLite database file is a binary database format designed to support efficient database operations.
Explanation
Importing a CSV into SQLite converts the data into a form that supports SQL queries and other database features.
- 34
What does the SQLite command
.importdo?Model answer
It loads data from an external file, such as a CSV file, into a specified database table.
Explanation
The CSV mode must be selected first so SQLite interprets commas and rows correctly.
- 35
What is the purpose of the SQLite command
.schema?Model answer
.schemadisplays the structure or creation statements for the database tables.Explanation
It can reveal table names, columns, data types, constraints, and relationships such as foreign keys.
- 36
What is a table in a relational database?
Model answer
A table is a collection of rows and columns that stores a particular kind of related data.
Explanation
A database may contain multiple tables, similar in some respects to multiple sheets in a spreadsheet.
- 37
What does the query
SELECT * FROM favoritesreturn?Model answer
It returns every column and every row from the
favoritestable.Explanation
The asterisk is a wildcard meaning all columns, and
FROMidentifies the table being queried. - 38
What does the SQL
LIMITclause do?Model answer
It restricts the number of rows returned by a query.
Explanation
For example,
LIMIT 10returns at most ten rows, which is useful for inspecting a large table. - 39
How can SQL count all rows in a table?
Model answer
Use
SELECT COUNT(*) FROM table_name.Explanation
Counting the rows of the imported favorites table produced 398 data rows because the original file also contained one header row.
- 40
Why is
COUNT(*)conventionally used when the goal is simply to count rows?Model answer
It counts rows without requiring the programmer to choose a particular column.
Explanation
If every row has the same number of columns and the relevant columns are non-null, counting a specific column gives the same result, but
COUNT(*)expresses the intention more directly. - 41
What does
DISTINCTdo in a SQL query?Model answer
It removes duplicate values from the query result.
Explanation
Selecting distinct languages from the favorites table returns each language only once.
- 42
How can SQL count the number of distinct languages in a table?
Model answer
Nest
DISTINCTinsideCOUNT, as inCOUNT(DISTINCT language).Explanation
SQL functions can be nested so that the distinct values are produced first and then counted.
- 43
What is the purpose of the
WHEREclause?Model answer
It filters rows so that only records satisfying a specified condition are used or returned.
Explanation
For example,
WHERE language = 'C'restricts the query to responses that selected C. - 44
How does SQL express equality in a condition?
Model answer
SQL uses a single equals sign, such as
language = 'C', to compare values.Explanation
This differs from C and Python, where equality comparison uses two equals signs.
- 45
How does SQL combine multiple conditions with Boolean logic?
Model answer
It uses keywords such as
ANDto require that multiple conditions are true.Explanation
A query can require both
language = 'C'andproblem = 'Hello, World'to identify a narrower group of rows. - 46
What does
GROUP BYdo in SQL?Model answer
It groups rows with the same value in a specified column so aggregate functions such as
COUNTcan be applied to each group.Explanation
Grouping by language effectively combines all Python rows, all C rows, and all Scratch rows for separate counting.
- 47
How can a SQL query produce a ranking of languages by popularity?
Model answer
Select the language and its count, group by language, and order the groups by the count.
Explanation
Adding descending order places the most frequently selected language first.
- 48
What is the difference between ascending and descending order in SQL?
Model answer
Ascending order, written
ASC, goes from lower to higher values, while descending order, writtenDESC, goes from higher to lower values.Explanation
A descending count order produces a most-popular-to-least-popular ranking.
- 49
What does the SQL keyword
ASdo?Model answer
It assigns an alias, or temporary alternative name, to a column or expression in a query result.
Explanation
For example,
COUNT(*) AS nlets the count be referenced and displayed under the shorter namen. - 50
How can a query return only the most popular category?
Model answer
Order the grouped results by their count in descending order and apply
LIMIT 1.Explanation
The ordering establishes the ranking, and the limit keeps only the first result.
- 51
How does an
INSERT INTOstatement add a row to a table?Model answer
It names the target table and columns, then supplies corresponding values in a
VALUESclause.Explanation
The listed columns and values must correspond by position; omitted columns may receive
NULLwhen permitted. - 52
What does
NULLrepresent in SQL?Model answer
NULLrepresents the absence of a value.Explanation
In the example, the inserted row had no timestamp, so its timestamp was
NULL; this use is unrelated to memory pointers. - 53
What is the danger of executing
DELETE FROM table_namewithout aWHEREclause?Model answer
It deletes every row in the specified table.
Explanation
A
WHEREcondition should be used when only selected rows should be removed. - 54
How can a SQL statement delete only rows with missing timestamps?
Model answer
Use
DELETE FROM favorites WHERE timestamp IS NULL.Explanation
The condition limits deletion to rows whose timestamp has no value instead of deleting the entire table's contents.
- 55
How does an
UPDATEstatement change existing data?Model answer
It uses
UPDATEwith aSETclause to assign new values, optionally restricting affected rows withWHERE.Explanation
Without a
WHEREclause, the new values are applied to every row in the table. - 56
What is data normalization in the context of relational databases?
Model answer
Normalization organizes data to reduce unnecessary duplication by storing each fact in an appropriate place and relating tables through keys.
Explanation
Separating shows, people, and their associations avoids repeatedly storing the same show and person names.
- 57
Why is using a separate column for every possible star of a TV show poor database design?
Model answer
Different shows have different numbers of stars, producing sparse, uneven rows and requiring more columns whenever a show has additional stars.
Explanation
A variable number of related values does not fit naturally into a fixed set of columns.
- 58
Why is repeating a show's title on multiple rows inefficient?
Model answer
It wastes storage and creates opportunities for inconsistent edits or typographical errors.
Explanation
A normalized design stores the title once and refers to it through an identifier.
- 59
What is the purpose of a table that contains only
show_idandperson_id?Model answer
It associates shows with people without duplicating their names or other descriptive data.
Explanation
This intermediary table records which people are connected to which shows.
- 60
Why is duplicating numeric identifiers generally more efficient than duplicating strings?
Model answer
Numeric identifiers use less storage and can generally be processed more efficiently than repeatedly storing long text strings.
Explanation
Repeating a show ID does not duplicate the full title text, so the association table remains compact.
- 61
What is a primary key?
Model answer
A primary key is a column or set of columns whose value uniquely identifies each row in a table.
Explanation
The
idcolumn identifies each show or person uniquely within its respective table. - 62
What is a foreign key?
Model answer
A foreign key is a column containing values that refer to primary-key values in another table.
Explanation
For example,
ratings.show_idrefers toshows.id, linking each rating to a show. - 63
How do primary and foreign keys create relationships between tables?
Model answer
A foreign-key column stores values that match primary-key values in another table, allowing related rows to be connected.
Explanation
This relationship lets a query combine information such as a show's title from one table and its rating from another.
- 64
What is a one-to-one relationship?
Model answer
A one-to-one relationship means that each row in one table corresponds to one row in another table.
Explanation
The example treats each show as having one corresponding rating, although those fields could technically be stored in one wider table.
- 65
What is a one-to-many relationship?
Model answer
A one-to-many relationship means that one row in one table can correspond to multiple rows in another table.
Explanation
A single show may have several genres, so one show row can relate to many genre rows.
- 66
What is a many-to-many relationship, and how is it implemented?
Model answer
A many-to-many relationship occurs when many rows in each of two tables can relate to one another. It is implemented with an intermediary table containing foreign keys to both tables.
Explanation
A show can have many people in its cast, and a person can appear in many shows, so the
starstable bridges the relationship. - 67
Why can a one-to-many join produce repeated information in the result set?
Model answer
The row on the “one” side is matched once for each related row on the “many” side, so its columns appear repeatedly in the temporary result.
Explanation
Joining one show to three genre rows produces three result rows containing the same show title and three different genres.
- 68
Why is repetition caused by a one-to-many join not necessarily a flaw in the stored database?
Model answer
The repetition exists only in the temporary result set produced for a query; the original normalized tables do not store duplicate copies of the same show data.
Explanation
The repeated rows are useful for displaying or analyzing each relationship.
- 69
What data types were identified as common SQL types?
Model answer
The main types discussed were
BLOB, integer, numeric, real, and text.Explanation
BLOBrepresents binary data, numeric can represent values such as dates and times, real represents decimal values, and text stores strings. - 70
What is a
BLOBin SQL?Model answer
A
BLOB, or Binary Large Object, is binary data such as a file or other sequence of zeros and ones.Explanation
The content noted that files are often better stored in a file system than directly inside a database.
- 71
What does the
NOT NULLconstraint enforce?Model answer
It prevents a column from containing an absent
NULLvalue.Explanation
This gives a database stronger protection over data integrity than an unrestricted spreadsheet.
- 72
What does a
UNIQUEconstraint enforce?Model answer
It requires values in a column to be different from one another.
Explanation
For example, a unique email column can help prevent one person from registering the same email address multiple times.
- 73
How do database constraints improve data integrity compared with ordinary spreadsheets?
Model answer
Constraints can prevent invalid or duplicate values from being inserted or updated, whereas spreadsheets generally allow users to enter arbitrary values.
Explanation
Rules such as
NOT NULLandUNIQUEmake the database enforce assumptions about its data. - 74
How can SQL join a shows table with a ratings table?
Model answer
Use
JOINwith anONcondition matching the related key columns, such asshows.id = ratings.show_id.Explanation
The join creates a temporary wider result containing information from both tables.
- 75
Why is table-qualified notation such as
shows.iduseful in SQL?Model answer
It explicitly identifies which table a column belongs to and prevents ambiguity when multiple tables contain similarly named columns.
Explanation
In a join,
shows.idandratings.show_idmake the intended relationship clear even when the database could infer it. - 76
How can a nested query find the titles of highly rated shows?
Model answer
First select show IDs from
ratingssatisfying a rating condition, then select titles fromshowswhose IDs appear in that subquery's results.Explanation
The nested query replaces the error-prone process of manually copying IDs from one query into another.
- 77
What is a subquery?
Model answer
A subquery is a query nested inside another SQL query, often supplying a set of values to the outer query.
Explanation
Parentheses indicate the nested portion and help establish that it should be evaluated as part of the larger query.
- 78
How can nested queries find all people who starred in a particular show?
Model answer
Find the show's ID, use it to retrieve associated person IDs from the intermediary table, and then use those IDs to retrieve names from the people table.
Explanation
The intermediary
starstable is required because the show and person information are stored separately. - 79
How can nested queries find all shows associated with a particular person?
Model answer
Find the person's ID, use it to retrieve show IDs from the intermediary table, and then retrieve the corresponding show titles.
Explanation
This reverses the same relationship-traversal process used to find a show's cast.
- 80
What are two alternative ways to connect three related SQL tables?
Model answer
A query can use explicit
JOINclauses withONconditions, or list the tables together and connect them with matching conditions in aWHEREclause.Explanation
Both approaches can connect shows, the intermediary stars table, and people to answer the same question.
- 81
What is the purpose of the
writerstable in the IMDb-style database?Model answer
It associates shows with the people who wrote them by storing a show ID and a person ID.
Explanation
Like the
starstable, it uses foreign keys that refer to the shows and people tables. - 82
What is an index in a relational database?
Model answer
An index is an auxiliary data structure that makes searches and other queries on selected columns faster.
Explanation
An index can be created on a column that an application frequently uses for filtering or lookup.
- 83
How is an index created in SQL?
Model answer
Use
CREATE INDEX, provide an index name, and specify the table and column to index.Explanation
For example, an index can be created on the
titlecolumn of theshowstable. - 84
Why can a B-tree make database searches faster than linear search?
Model answer
A B-tree is a short, wide tree that reduces the number of steps needed to find a value compared with checking every row sequentially.
Explanation
Its many children per node keep the tree's height small, and target values are located in its leaves.
- 85
Why are primary-key searches often fast in SQLite?
Model answer
SQLite automatically creates an index for a primary key, so searches on that column do not require a simple linear scan.
Explanation
Primary keys are indexed by default, unlike ordinary foreign-key or text columns.
- 86
Are foreign keys automatically indexed by default in SQLite?
Model answer
No. Foreign keys are not automatically indexed by default, so they may need explicit indexes when frequently searched or joined.
Explanation
The example created indexes on foreign-key columns in the
starstable to speed up multi-table queries. - 87
What is the trade-off involved in creating database indexes?
Model answer
Indexes improve query speed but consume additional storage and can slow inserts, updates, and deletes because the index must be maintained.
Explanation
Therefore, indexing every column is usually an overcorrection; frequently searched columns are better candidates.
- 88
Why can indexing several columns dramatically improve a multi-table query?
Model answer
Indexes allow the database to locate matching rows quickly in each table instead of repeatedly scanning entire columns or tables.
Explanation
Indexing the relevant foreign keys and person name changed the example query from several seconds to nearly instantaneous.
- 89
How can Python and SQL be used together?
Model answer
Python can collect user input and control the application while sending SQL queries to a database and processing the returned results.
Explanation
This combines Python's strengths in application or interface development with SQL's strengths in database querying.
- 90
Why should a database query use placeholders for user input?
Model answer
Placeholders allow the database library to safely escape special characters and prevent user input from being interpreted as SQL code.
Explanation
The example uses a question mark placeholder and supplies the user's value separately rather than constructing the query through string interpolation.
- 91
What is a race condition in a database application?
Model answer
A race condition occurs when concurrent operations read and modify shared data in an interleaved order, causing the final result to be incorrect.
Explanation
Multiple servers updating a like count can all read the same old value and overwrite one another's increments.
- 92
How can a race condition cause lost likes in a counter update?
Model answer
If several requests read the same current count before any update is completed, they may all write back that count plus one, causing multiple clicks to produce only one increment.
Explanation
For example, three requests can all read 1,000,000 and repeatedly write 1,000,001.
- 93
What is a transaction, and how does it address race conditions?
Model answer
A transaction groups related database operations so they occur atomically: all succeed together or none take effect.
Explanation
Wrapping the read and update operations in a transaction prevents other operations from interrupting the logical sequence.
- 94
What is a SQL injection attack?
Model answer
A SQL injection attack occurs when malicious input is inserted into a dynamically constructed SQL statement and changes the statement's intended meaning.
Explanation
An attacker may use SQL syntax in a form field to bypass authentication or perform unintended database operations.
- 95
How can the SQLite comment sequence
--enable a SQL injection attack?Model answer
It causes the remainder of the SQL line to be treated as a comment, potentially removing conditions such as password checks from the executed query.
Explanation
If an input closes a quoted username and then adds
--, the password portion of an unsafe query may be ignored. - 96
Why is constructing SQL queries with Python f-strings unsafe?
Model answer
F-strings directly interpolate untrusted input into SQL, allowing special characters and SQL commands supplied by a user to alter the query.
Explanation
A user could insert a quote to end a string literal and then add SQL syntax such as a comment.
- 97
How do parameterized queries prevent SQL injection?
Model answer
They keep the SQL structure separate from user-supplied values and use a library to escape potentially dangerous characters correctly.
Explanation
A placeholder such as
?is bound to the input as data rather than allowing the input to become part of the SQL command. - 98
What does
DROPdo in SQL, and why is it especially dangerous?Model answer
DROPcan delete an entire database table, including its structure and data.Explanation
It is more destructive than deleting selected rows and should be used with extreme caution and appropriate backups.

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