CS50 Week 7: Data Tools
- 68Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
Why might a programmer choose SQL instead of Python for working with very large datasets?
Why might a programmer choose SQL instead of Python for working with very large datasets?
68 questions
- 1
Why might a programmer choose SQL instead of Python for working with very large datasets?
- A
SQL automatically converts all data into machine code before execution
- B
SQL is designed specifically to query and manipulate database data efficiently
- C
SQL eliminates the need to store data in files or database tables
- D
SQL is the only language that can represent numerical values
Correct answer
BSQL is designed specifically to query and manipulate database data efficiently
Explanation
SQL is a database-centric language designed for querying and manipulating data, often allowing database tasks to be expressed more concisely than in general-purpose Python code.
- A
- 2
What is a flat-file database in the context of the lecture?
- A
A binary database containing only numerical values
- B
A database that stores every value in a separate program
- C
A spreadsheet that must contain exactly one row
- D
A text file containing data, often separated by delimiters
Correct answer
DA text file containing data, often separated by delimiters
Explanation
A flat-file database is essentially a text file containing data, commonly organized with delimiters such as commas or tabs.
- A
- 3
How do CSV files represent rows and columns using plain text?
- A
Spaces separate rows, and quotation marks separate columns
- B
Commas separate rows, and newline characters separate columns
- C
Newline characters separate rows, and commas commonly separate columns
- D
Binary markers separate rows, and tabs always separate columns
Correct answer
CNewline characters separate rows, and commas commonly separate columns
Explanation
CSV stands for comma-separated values. Newline characters separate records, while commas commonly separate values within each record.
- A
- 4
Why might a CSV exporter place quotation marks around a field such as "Hello, World"?
- A
The field contains a comma that could otherwise be mistaken for a column delimiter
- B
The field is always the first value in every CSV record
- C
The field contains a number that must be converted into text
- D
The field contains a newline that separates two database tables
Correct answer
AThe field contains a comma that could otherwise be mistaken for a column delimiter
Explanation
Quotation marks protect commas that are part of a field's actual text so that a CSV reader does not interpret them as separators between columns.
- A
- 5
What was the purpose of the header row in the exported favorites CSV file?
- A
It stored the first student's responses before the other rows
- B
It recorded the database password needed to open the file
- C
It converted the CSV file from text into binary format
- D
It identified the meanings of the columns, such as timestamp, language, and problem
Correct answer
DIt identified the meanings of the columns, such as timestamp, language, and problem
Explanation
The header row contained column names and therefore described the data rather than representing an ordinary response.
- A
- 6
What does Python's
csv.readerreturn for each row of a CSV file?- A
A list whose elements correspond to the row's columns
- B
A tuple containing only the first and last columns
- C
A single string containing the entire file
- D
A dictionary whose keys are automatically generated database names
Correct answer
AA list whose elements correspond to the row's columns
Explanation
The CSV reader yields rows as lists. For the favorites data, the three columns could be accessed using indices 0, 1, and 2.
- A
- 7
Why was
next(reader)used before looping through the rows with Python's CSV reader?- A
It advanced directly to the last row of the file
- B
It skipped the header row so the program would process only response data
- C
It converted each row from a list into a dictionary
- D
It closed the file before the loop began
Correct answer
BIt skipped the header row so the program would process only response data
Explanation
The first row was metadata describing the columns, so
next(reader)consumed it before the program processed the actual data rows. - A
- 8
What advantage does Python's
DictReaderprovide over the basic CSV reader?- A
It converts every field into an integer automatically
- B
It automatically sorts every row alphabetically before returning it
- C
It lets code access values by column name instead of fixed numeric position
- D
It removes all duplicate values from the CSV file
Correct answer
CIt lets code access values by column name instead of fixed numeric position
Explanation
DictReaderuses the header row as dictionary keys, allowing code such asrow["language"]and making it less dependent on column order. - A
- 9
Why is code using
row[1]considered fragile when reading a spreadsheet-derived CSV file?- A
Python lists cannot contain strings at index 1
- B
Moving or deleting columns can cause index 1 to refer to different data
- C
The second column is always ignored by CSV readers
- D
Numeric indices can be used only with binary database files
Correct answer
BMoving or deleting columns can cause index 1 to refer to different data
Explanation
A positional index assumes that the desired field will always remain in the same column. Accessing a named dictionary key is more robust when columns are rearranged.
- A
- 10
What happens when Python code uses
with open(...) as file:?- A
The file remains open until the entire Python program terminates
- B
The file is automatically closed when execution leaves the
withblock - C
The file is automatically converted into a database table
- D
The file can only be opened for writing inside the block
Correct answer
BThe file is automatically closed when execution leaves the
withblockExplanation
The
withstatement manages the file resource and automatically closes it after the indented block finishes, including in many error situations. - A
- 11
What is the purpose of a dictionary used as a counting structure?
- A
It preserves only the most recently encountered item
- B
It stores every item only once and prevents numerical updates
- C
It associates each item, such as a language, with its current count
- D
It automatically replaces all strings with their ASCII codes
Correct answer
CIt associates each item, such as a language, with its current count
Explanation
A dictionary can map keys such as
Python,C, andScratchto integer counts that are initialized and incremented as rows are processed. - A
- 12
When using a dictionary to count values without
Counter, why should a newly encountered item usually be assigned a count of 1 rather than 0?- A
Python dictionaries reject values equal to zero
- B
The first row is always the header and must be counted
- C
A value of zero causes the dictionary key to be deleted
- D
The current row is already the first occurrence of that item
Correct answer
DThe current row is already the first occurrence of that item
Explanation
If an item is not yet in the dictionary, encountering it means it has already appeared once, so its initial count should be 1.
- A
- 13
What does Python's
Counterclass provide?- A
A sorting algorithm that orders values by their spelling
- B
A database connection that automatically stores every Python variable
- C
A mapping with counting behavior that initializes unseen items to zero
- D
A file reader that understands only comma-free text
Correct answer
CA mapping with counting behavior that initializes unseen items to zero
Explanation
Counteris a specialized dictionary-like object that allows a program to increment counts even for keys that have not previously been encountered. - A
- 14
What does the
most_commonmethod of a PythonCounterreturn?- A
Rows from the original CSV file in their original order
- B
Only the alphabetically first item in the counter
- C
Items paired with their counts in descending order of frequency
- D
All items with their values replaced by zero
Correct answer
CItems paired with their counts in descending order of frequency
Explanation
most_commonreturns key-count pairs ordered from the most frequent item to the least frequent item. - A
- 15
What does Python's
sortedfunction do by default when given a dictionary for iteration?- A
It sorts the dictionary's values by numerical size
- B
It sorts the dictionary's keys
- C
It removes keys that have duplicate values
- D
It reverses the order in which keys were inserted
Correct answer
BIt sorts the dictionary's keys
Explanation
By default,
sortedorders dictionary keys. Supplying a key function such ascounts.getmakes it sort according to the associated values instead. - A
- 16
What effect does
reverse=Truehave when passed to Python'ssortedfunction?- A
It reverses the resulting sort order
- B
It sorts according to dictionary keys instead of values
- C
It removes the sorting operation entirely
- D
It causes the function to modify the original file
Correct answer
AIt reverses the resulting sort order
Explanation
reverse=Truechanges ascending order to descending order, or reverses whatever ordering the sort would otherwise produce. - A
- 17
What distinguishes a positional argument from a named parameter in Python?
- A
A positional argument is optional, while a named parameter is always required
- B
A positional argument is identified by location, while a named parameter is identified explicitly by name
- C
A positional argument must be a number, while a named parameter must be a string
- D
A positional argument belongs to SQL, while a named parameter belongs only to C
Correct answer
BA positional argument is identified by location, while a named parameter is identified explicitly by name
Explanation
Positional arguments are interpreted according to their order. Named parameters, such as
reverse=True, explicitly identify which option is being set. - A
- 18
What does SQL stand for?
- A
Sequential Question Logic
- B
Structured Query Language
- C
System Query Library
- D
Stored Quantitative List
Correct answer
BStructured Query Language
Explanation
SQL is the abbreviation for Structured Query Language, a language designed for working with databases.
- A
- 19
Why is SQL described as a declarative language?
- A
The programmer must write a loop for every row returned
- B
The database executes only commands written in a graphical interface
- C
The programmer describes the desired data rather than specifying every procedural step
- D
The language can only declare variables and cannot query data
Correct answer
CThe programmer describes the desired data rather than specifying every procedural step
Explanation
SQL generally expresses what data should be returned or changed, leaving the database system to determine how to perform the operation.
- A
- 20
What does the CRUD acronym represent in database operations?
- A
Connect, Retrieve, Use, and Disconnect
- B
Count, Rank, Understand, and Display
- C
Compile, Run, Upload, and Debug
- D
Create, Read, Update, and Delete
Correct answer
DCreate, Read, Update, and Delete
Explanation
CRUD summarizes the four fundamental categories of database operations: creating, reading, updating, and deleting data.
- A
- 21
Which SQL keywords correspond most directly to the CRUD operations?
- A
OPEN,READ,WRITE, andCLOSE - B
IMPORT,GROUP,ORDER, andLIMIT - C
INSERT,SELECT,UPDATE, andDELETE - D
CREATE,COUNT,SORT, andDROP
Correct answer
CINSERT,SELECT,UPDATE, andDELETEExplanation
SQL commonly uses
INSERTto add rows,SELECTto read data,UPDATEto modify data, andDELETEto remove rows.DROPcan remove an entire table. - A
- 22
In a relational database, what is a table most analogous to in a spreadsheet?
- A
A chart generated from several sheets
- B
A sheet containing rows and columns
- C
A file extension used to export data
- D
A single formula in a cell
Correct answer
BA sheet containing rows and columns
Explanation
A database table stores related data in rows and columns, much like a spreadsheet sheet.
- A
- 23
What does
SELECT * FROM favorites;request?- A
The number of unique rows in the
favoritestable - B
Only the first column from the
favoritestable - C
Every column and row from the
favoritestable - D
Every table whose name contains the word
favorites
Correct answer
CEvery column and row from the
favoritestableExplanation
In SQL,
*is a wildcard meaning all columns. Without a filtering condition, the query returns all rows from the named table. - A
- 24
What is the purpose of the SQL
LIMITclause?- A
It restricts the number of columns that may exist in a table
- B
It restricts the number of rows returned by a query
- C
It limits values to integers rather than text
- D
It prevents users from inserting more rows permanently
Correct answer
BIt restricts the number of rows returned by a query
Explanation
LIMIT 10, for example, asks SQL to return no more than 10 rows in the result set. - A
- 25
What does
COUNT(*)calculate in a query over a table?- A
The sum of all numerical values in the table
- B
The number of columns in the selected table
- C
The number of rows in the selected result
- D
The number of distinct values in every column
Correct answer
CThe number of rows in the selected result
Explanation
COUNT(*)counts rows, regardless of the particular values stored in their columns. - A
- 26
What does the SQL keyword
DISTINCTdo?- A
It deletes duplicate rows from the original table
- B
It changes all text values to uppercase
- C
It sorts values from smallest to largest
- D
It removes duplicate values from the query result
Correct answer
DIt removes duplicate values from the query result
Explanation
DISTINCTreturns only unique values in the selected result. It does not delete records from the underlying table. - A
- 27
How does a SQL
WHEREclause function?- A
It creates a backup copy before a query runs
- B
It filters rows according to a specified condition
- C
It groups every row with the same column name
- D
It permanently changes the table's column order
Correct answer
BIt filters rows according to a specified condition
Explanation
A
WHEREclause selects only rows satisfying a condition, such aslanguage = 'C'. - A
- 28
Which SQL expression correctly filters rows where the language is C and the problem is Hello, World?
- A
WHERE language = 'C' AND problem = 'Hello, World' - B
WHERE language := 'C' PLUS problem := 'Hello, World' - C
WHERE language == C && problem == Hello, World - D
WHERE language IN C OR problem IN Hello, World
Correct answer
AWHERE language = 'C' AND problem = 'Hello, World'Explanation
SQL uses
ANDfor conjunction and generally uses a single equals sign for equality comparisons. Text values are written as quoted strings. - A
- 29
What is the default ordering produced by
ORDER BYin SQL?- A
Order of insertion only
- B
Ascending order
- C
Random order
- D
Descending order
Correct answer
BAscending order
Explanation
SQL orders ascending by default. The keyword
DESCrequests descending order. - A
- 30
What does
GROUP BY languageaccomplish when combined with a count?- A
It sorts all individual responses alphabetically without combining them
- B
It deletes every language that appears more than once
- C
It combines rows by language so the number of rows for each language can be counted
- D
It limits the result to one language regardless of its frequency
Correct answer
CIt combines rows by language so the number of rows for each language can be counted
Explanation
GROUP BYforms groups of rows sharing a value. Counting each group produces frequencies such as the number of responses for each language. - A
- 31
What is the purpose of the SQL keyword
ASin a query such asCOUNT(*) AS n?- A
It converts the expression into a string
- B
It sorts the expression in ascending order
- C
It restricts the expression to one row
- D
It assigns an alias to a column or expression in the result
Correct answer
DIt assigns an alias to a column or expression in the result
Explanation
AS ngives the computed column a shorter, more convenient name:n. - A
- 32
What is the difference between
DELETE FROM favorites;andDELETE FROM favorites WHERE timestamp IS NULL;?- A
The first deletes every row, while the second deletes only rows meeting the condition
- B
There is no difference because
WHEREis ignored by SQL - C
The first deletes the table itself, while the second deletes only its columns
- D
The first deletes only null rows, while the second deletes every row
Correct answer
AThe first deletes every row, while the second deletes only rows meeting the condition
Explanation
Without a
WHEREclause,DELETEaffects all rows. With the condition, only rows whose timestamp is null are deleted. - A
- 33
What does a SQL
NULLvalue represent?- A
An empty database file
- B
A pointer to the beginning of a table
- C
The absence of a value
- D
The numerical value zero
Correct answer
CThe absence of a value
Explanation
NULLindicates that no value is present. In SQL, it is not a pointer or memory address. - A
- 34
What is the effect of an
UPDATEstatement without aWHEREclause?- A
It changes the table schema but not any stored values
- B
It changes the specified columns in every row of the table
- C
It fails because SQL requires a
WHEREclause for updates - D
It changes only the first row returned by the table
Correct answer
BIt changes the specified columns in every row of the table
Explanation
An
UPDATEwithout a condition applies to all rows, which can be highly destructive. - A
- 35
Why is database normalization useful in the TV-show example?
- A
It eliminates the need for relationships between tables
- B
It forces every table to contain exactly the same number of columns
- C
It stores every repeated name in a longer text field for readability
- D
It factors out repeated information so each show and person can be stored canonically
Correct answer
DIt factors out repeated information so each show and person can be stored canonically
Explanation
Normalization reduces redundant strings by storing entities such as shows and people once and relating them through identifiers.
- A
- 36
Why was using separate star columns for each television show considered poor design?
- A
Every star must have the same name as the show
- B
Different shows may require different numbers of star columns, creating sparse and uneven rows
- C
A spreadsheet cannot store names in more than one column
- D
Separate columns prevent the database from storing numerical IDs
Correct answer
BDifferent shows may require different numbers of star columns, creating sparse and uneven rows
Explanation
A variable number of star columns produces a jagged design in which some rows have many unused or missing fields.
- A
- 37
Why is repeating a show's title across multiple rows inefficient?
- A
It wastes storage and creates opportunities for inconsistent copies of the same text
- B
It prevents the show from having more than one star
- C
It causes every repeated title to become a separate database table
- D
It makes all identifiers automatically invalid
Correct answer
AIt wastes storage and creates opportunities for inconsistent copies of the same text
Explanation
Repeated strings consume space and can become inconsistent if one copy is edited while others are not.
- A
- 38
What is the purpose of a primary key?
- A
It uniquely identifies each row or entity in a table
- B
It records the order in which rows were inserted
- C
It guarantees that every column contains text
- D
It stores the names of all tables related to the current table
Correct answer
AIt uniquely identifies each row or entity in a table
Explanation
A primary key, such as a show's unique ID, identifies one particular entity uniquely within its table.
- A
- 39
What is a foreign key?
- A
A key used only to encrypt data stored outside the database
- B
A duplicate primary key that is invalid in its original table
- C
A column containing values that refer to primary keys in another table
- D
A column that must contain a different data type from every other column
Correct answer
CA column containing values that refer to primary keys in another table
Explanation
A foreign key creates a relationship by storing identifiers that correspond to primary keys in another table.
- A
- 40
Why is an intermediary table such as
starsneeded for a many-to-many relationship?- A
It ensures that each show can have only one person
- B
It stores all show titles in one large text field
- C
It records multiple associations between shows and people without repeating complete entity descriptions
- D
It replaces every primary key with a random string
Correct answer
CIt records multiple associations between shows and people without repeating complete entity descriptions
Explanation
A show can have many people, and a person can appear in many shows. A linking table stores each show-person association using foreign keys.
- A
- 41
What relationship exists between the
showsandratingstables in the described IMDb design?- A
Each show must have many corresponding rating rows
- B
Each rating belongs to many unrelated shows simultaneously
- C
Shows and ratings have no shared identifying value
- D
Each show has one corresponding rating row
Correct answer
DEach show has one corresponding rating row
Explanation
The design describes a one-to-one relationship: each show has one row in the ratings table, linked by the show's ID.
- A
- 42
What relationship does the
genrestable represent for shows?- A
One genre can be associated with only one show
- B
Genres can be stored only as columns in the shows table
- C
One show can be associated with multiple genres
- D
Each show must have exactly one genre
Correct answer
COne show can be associated with multiple genres
Explanation
The genres table uses multiple rows with the same show ID to represent associations such as comedy, adventure, and family.
- A
- 43
What is the effect of joining tables with a one-to-many relationship?
- A
The original tables are permanently merged and all duplicate data is stored
- B
The result set may temporarily repeat the one-side data for each matching many-side row
- C
The query can return only the primary keys and no descriptive fields
- D
The database must delete all rows on the many side
Correct answer
BThe result set may temporarily repeat the one-side data for each matching many-side row
Explanation
For a show with several genres, a join can return the show's title once per genre. This repetition exists in the temporary result set, not necessarily in the stored tables.
- A
- 44
What is the main purpose of an SQL
JOIN?- A
To sort one table without examining any of its values
- B
To remove all foreign keys from a database
- C
To convert a table into a CSV file
- D
To combine related data from multiple tables using matching columns
Correct answer
DTo combine related data from multiple tables using matching columns
Explanation
A join combines rows from related tables, such as matching
shows.idwithratings.show_id. - A
- 45
Why are table-qualified column names such as
shows.iduseful in a join?- A
They are required whenever a column contains a number
- B
They force SQL to return only one row
- C
They convert the column into a foreign key automatically
- D
They make clear which table a column belongs to and avoid ambiguity
Correct answer
DThey make clear which table a column belongs to and avoid ambiguity
Explanation
Table qualification clarifies which column is intended, especially when multiple tables contain similarly named columns.
- A
- 46
Which SQL query correctly combines show titles with their ratings for ratings of at least 6.0?
- A
SELECT title, rating FROM shows WHERE shows.id JOIN ratings = ratings.show_id AND rating 6.0; - B
SELECT title, rating FROM shows JOIN ratings ON shows.id = ratings.show_id WHERE rating >= 6.0; - C
SELECT title, rating FROM ratings GROUP shows ON title WHERE rating <= 6.0; - D
SELECT title, rating FROM shows, ratings DELETE rating >= 6.0;
Correct answer
BSELECT title, rating FROM shows JOIN ratings ON shows.id = ratings.show_id WHERE rating >= 6.0;Explanation
The query selects the desired columns, joins the tables on their related identifiers, and filters ratings using
WHERE rating >= 6.0. - A
- 47
What is the main benefit of using SQLite in the described course context?
- A
It eliminates the need to learn any SQL syntax
- B
It is a programming language that replaces Python for every task
- C
It stores data only in human-readable spreadsheets
- D
It provides a lightweight implementation containing core SQL database functionality
Correct answer
DIt provides a lightweight implementation containing core SQL database functionality
Explanation
SQLite is a lightweight SQL implementation commonly used on computers and phones while still supporting core relational database operations.
- A
- 48
Which SQLite command displays the schema of a database or table?
- A
.columns - B
.design - C
.schema - D
.layout
Correct answer
C.schemaExplanation
The SQLite-specific
.schemacommand displays the SQL definitions used to create tables and their columns. - A
- 49
Which data type is most appropriate for a value such as a decimal rating?
- A
BLOB
- B
TEXT
- C
REAL
- D
INTEGER
Correct answer
CREAL
Explanation
A
REALrepresents a number that may contain a decimal point, such as a rating of 8.7. - A
- 50
What does the SQL data type
BLOBgenerally represent?- A
A text field that cannot contain spaces
- B
A binary large object containing data such as raw file bytes
- C
A relationship between two primary keys
- D
A column containing only whole-number counts
Correct answer
BA binary large object containing data such as raw file bytes
Explanation
BLOB stands for Binary Large Object and generally refers to binary data. The lecture noted that files are often better stored in a file system than directly in a database.
- A
- 51
What constraint prevents a column from accepting missing values?
- A
NO EMPTY - B
NOT NULL - C
UNIQUE ONLY - D
REQUIRED TEXT
Correct answer
BNOT NULLExplanation
NOT NULLrequires a value to be present in the column. - A
- 52
What does a
UNIQUEconstraint enforce?- A
The column must contain at least one null value
- B
Values in the constrained column cannot be duplicated
- C
Rows must be returned in alphabetical order
- D
Every value must be a floating-point number
Correct answer
BValues in the constrained column cannot be duplicated
Explanation
A
UNIQUEconstraint prevents duplicate values, such as duplicate email addresses in a user table. - A
- 53
What is the purpose of an index in a database?
- A
It provides a data structure that can make searches on selected columns faster
- B
It permanently sorts every table and prevents future updates
- C
It replaces the need for primary and foreign keys
- D
It compresses all text into a single database value
Correct answer
AIt provides a data structure that can make searches on selected columns faster
Explanation
An index is an auxiliary data structure, commonly a B-tree, that helps the database locate matching values more efficiently than scanning every row.
- A
- 54
Why can a B-tree index speed up a database search?
- A
It scans every row several times to guarantee accuracy
- B
It stores every possible query result in the user's program
- C
It converts all searches into constant-time operations regardless of the data
- D
Its short, broad structure reduces the number of steps needed to reach a value
Correct answer
DIts short, broad structure reduces the number of steps needed to reach a value
Explanation
A B-tree has many children per node, keeping its height relatively small and reducing the number of comparisons needed to find a value.
- A
- 55
What indexing behavior was described for primary and foreign keys in SQLite?
- A
Primary keys are indexed automatically, while foreign keys are not indexed by default
- B
Both types are always unindexed unless stored as text
- C
Foreign keys are indexed automatically, while primary keys cannot be indexed
- D
Both types are automatically indexed only after a
SELECTquery
Correct answer
APrimary keys are indexed automatically, while foreign keys are not indexed by default
Explanation
The lecture stated that SQLite automatically indexes primary keys, but foreign-key columns generally require indexes to be created explicitly.
- A
- 56
What is the main trade-off of creating database indexes?
- A
Indexes make searches slower but make database design simpler
- B
Indexes use additional space and can slow inserts, updates, and deletes
- C
Indexes prevent tables from being joined together
- D
Indexes reduce storage space and make every write instantaneous
Correct answer
BIndexes use additional space and can slow inserts, updates, and deletes
Explanation
Indexes improve read performance but require storage and maintenance whenever indexed data changes.
- A
- 57
Why might an index on a frequently searched title column improve a large website's performance?
- A
The index automatically creates a new copy of every website page
- B
The database can locate matching titles without linearly scanning the entire column
- C
The index changes all title values into primary keys
- D
The index prevents users from searching for titles that are not present
Correct answer
BThe database can locate matching titles without linearly scanning the entire column
Explanation
An index allows searches to use an efficient data structure rather than examining every title from top to bottom.
- A
- 58
Why can Python and SQL be used together in one application?
- A
SQL can query the database while Python handles interaction or application logic
- B
Python and SQL are interchangeable names for the same language
- C
Python automatically turns every SQL query into a spreadsheet formula
- D
SQL can create user interfaces but cannot read stored data
Correct answer
ASQL can query the database while Python handles interaction or application logic
Explanation
A program can use Python for input, output, and application behavior while sending SQL queries to retrieve or modify database data.
- A
- 59
Why are placeholders such as
?used when passing user input into SQL queries?- A
They allow the database library to handle user input safely rather than concatenating it into SQL text
- B
They make SQL queries execute without any database connection
- C
They convert every user input into a database table
- D
They force the database to ignore all user input
Correct answer
AThey allow the database library to handle user input safely rather than concatenating it into SQL text
Explanation
Parameterized queries separate SQL structure from user-provided values and allow the library to escape dangerous characters appropriately.
- A
- 60
What is a race condition in the likes-counter example?
- A
Concurrent operations read and update shared data in an order that can cause updates to be lost
- B
A query takes longer because an index contains too many values
- C
A database refuses to store two rows with the same primary key
- D
A user enters a password containing an invalid character
Correct answer
AConcurrent operations read and update shared data in an order that can cause updates to be lost
Explanation
If several servers read the same old like count before any writes finish, they may all write the same incremented value, losing some likes.
- A
- 61
If three users simultaneously read a like count of 1,000,000 and each writes back 1,000,001, what is the result?
- A
The database may record only one new like instead of three
- B
The database necessarily records exactly three new likes
- C
The database multiplies the count by three before storing it
- D
The database automatically records zero new likes
Correct answer
AThe database may record only one new like instead of three
Explanation
Because all three operations may use the same old value, each can overwrite the others with 1,000,001, losing two increments.
- A
- 62
What does it mean for a database transaction to be atomic?
- A
All operations in the transaction happen together, or none of them take effect
- B
Only numerical operations can occur inside the transaction
- C
Each operation is permanently stored before the next operation begins
- D
The transaction automatically creates a separate database for each user
Correct answer
AAll operations in the transaction happen together, or none of them take effect
Explanation
Atomicity prevents a multi-step operation from being interrupted halfway through, helping preserve consistency when concurrent requests occur.
- A
- 63
How can a transaction help prevent lost updates in the likes example?
- A
It causes the read-and-update sequence to execute without harmful interleaving
- B
It replaces the likes count with a randomly generated value
- C
It converts every like into a separate database table
- D
It permanently disables all other users from accessing the database
Correct answer
AIt causes the read-and-update sequence to execute without harmful interleaving
Explanation
Wrapping related operations in a transaction makes the sequence behave as a single atomic unit, reducing errors caused by concurrent requests.
- A
- 64
What is a SQL injection attack?
- A
An attack that sorts a database in the wrong order
- B
An attack that physically inserts a new database server into a network
- C
An attack that occurs only when a database contains numeric columns
- D
An attack in which malicious input changes the meaning of a dynamically constructed SQL query
Correct answer
DAn attack in which malicious input changes the meaning of a dynamically constructed SQL query
Explanation
SQL injection occurs when untrusted input is concatenated into SQL and is interpreted as part of the query rather than merely as data.
- A
- 65
In SQLite, what does
--signify when used in a SQL statement?- A
It forces the database to delete the current table
- B
It begins a comment, causing the remainder of the line to be ignored
- C
It marks the beginning of a password field
- D
It subtracts one value from another
Correct answer
BIt begins a comment, causing the remainder of the line to be ignored
Explanation
In SQLite, two hyphens begin a comment. In an injection attack, this can cause the rest of a query, such as a password check, to be ignored.
- A
- 66
Why is constructing a SQL query with a Python f-string unsafe when it includes user input?
- A
F-strings automatically delete every row returned by a query
- B
A user can insert quotes and SQL syntax that alter the intended query
- C
F-strings can contain only integers and therefore corrupt all text input
- D
SQL databases cannot execute queries containing Python strings
Correct answer
BA user can insert quotes and SQL syntax that alter the intended query
Explanation
Direct string interpolation allows user input to become executable SQL syntax. Parameterized placeholders should be used instead.
- A
- 67
How could a username containing a closing quote followed by
--bypass an unsafe password check?- A
The input causes SQL to compare the password numerically instead of as text
- B
The input changes the username into a primary key without querying the database
- C
The input automatically encrypts the password before comparison
- D
The quote can terminate the username string, and
--can comment out the password condition
Correct answer
DThe quote can terminate the username string, and
--can comment out the password conditionExplanation
In an improperly interpolated query, the injected quote closes the string literal and
--comments out the remaining password-checking expression. - A
- 68
Which practice best prevents the SQL injection vulnerability described in the lecture?
- A
Place user input directly inside an f-string surrounded by quotes
- B
Use parameterized queries with placeholders supplied through a database library
- C
Allow users to submit only values that look like numbers
- D
Remove all quotation marks from SQL string comparisons
Correct answer
BUse parameterized queries with placeholders supplied through a database library
Explanation
Parameterized queries let the database library distinguish data from SQL syntax and safely escape potentially dangerous input.
- A

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