SQL Fundamentals
- 114Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What is SQL, and what is it used for?
114 questions
- 1
What is SQL, and what is it used for?
Model answer
SQL, or Structured Query Language, is used to communicate with databases and retrieve, create, update, and delete data.
Explanation
SQL is a common query language supported by databases such as SQLite, PostgreSQL, and MySQL.
- 2
Why is SQL important for web developers regardless of which programming language they use?
Model answer
Most web applications store and retrieve data from databases, so developers commonly use SQL alongside languages such as JavaScript, Python, Go, or TypeScript.
Explanation
The programming language handles application logic, while SQL communicates with the database layer.
- 3
What is a database?
Model answer
A database is software that makes it easier to store and manage large amounts of data in a computer's file system.
Explanation
A database can be viewed as a more powerful and automated alternative to spreadsheets.
- 4
How does working with SQL differ from manually managing data in a spreadsheet?
Model answer
SQL allows developers to write code that automates database operations instead of manually moving data through pointing, clicking, and dragging.
Explanation
SQL automates creates, reads, updates, and deletes.
- 5
What do the four CRUD operations stand for?
Model answer
CRUD stands for create, read, update, and delete.
Explanation
These operations represent the basic ways applications manage stored data.
- 6
Which SQL operation corresponds to a read operation?
Model answer
A
SELECTstatement performs a read operation by retrieving data from a database.Explanation
A
SELECTquery returns a result set rather than changing stored data. - 7
What is a result set?
Model answer
A result set is the table-like collection of rows and columns returned by a SQL query.
Explanation
Unlike ordinary console output, a query commonly returns structured tabular data.
- 8
Why are SQL statements usually terminated with a semicolon?
Model answer
A semicolon marks the end of a SQL statement.
Explanation
It separates one SQL command from the next.
- 9
Are SQL keywords case-sensitive?
Model answer
SQL keywords are generally case-insensitive, although uppercase keywords are a common convention for readability.
Explanation
For example,
SELECTandselectgenerally perform the same operation. - 10
What is the difference between a field and a column in SQL terminology?
Model answer
They are often used interchangeably, but column is the more precise database term; a field commonly refers to an attribute in a programming-language object.
Explanation
A database column may become an object field when a row is represented in application code.
- 11
What does
SELECT * FROM users;return?Model answer
It returns every column and every row from the
userstable.Explanation
The asterisk is a wildcard representing all columns.
- 12
How do you select only one column from a table?
Model answer
Specify the column after
SELECT, such asSELECT id FROM users;.Explanation
The query returns the values in the selected column rather than the entire table.
- 13
How do you select multiple columns from a table?
Model answer
List the column names after
SELECTand separate them with commas, such asSELECT id, name FROM users;.Explanation
Only the listed columns appear in the result set.
- 14
What does a
WHEREclause do?Model answer
A
WHEREclause filters rows so that only records satisfying a condition are returned or modified.Explanation
For example,
WHERE is_admin = trueselects only administrator records. - 15
Which comparison operator is used for equality in SQL?
Model answer
SQL uses a single equals sign,
=, to test equality.Explanation
Unlike some programming languages, SQL does not use
==for equality tests. - 16
How are
ANDandORused in SQL conditions?Model answer
ANDrequires both conditions to be true, whileORrequires at least one condition to be true.Explanation
Parentheses can be used to control the order in which combined conditions are evaluated.
- 17
What does the
INoperator do?Model answer
The
INoperator tests whether a value matches any value in a specified list or result set.Explanation
It is a concise alternative to combining multiple equality conditions with
OR. - 18
How does the
BETWEENoperator work?Model answer
BETWEENselects values within an inclusive lower and upper boundary.Explanation
For example,
age BETWEEN 13 AND 18includes ages from 13 through 18. - 19
How do the
%and_wildcards differ withLIKE?Model answer
The
%wildcard matches zero or more characters, while_matches exactly one character.Explanation
These wildcards allow partial and pattern-based text matching.
- 20
How would you find names that start with the letters
Al?Model answer
Use a pattern such as
WHERE name LIKE 'Al%'.Explanation
The percent sign allows any sequence of characters after
Al. - 21
How would you find names that start with
Aland contain exactly five characters?Model answer
Use
WHERE name LIKE 'Al___'.Explanation
The two literal letters are followed by three underscore wildcards.
- 22
What does the
LIMITclause do?Model answer
It restricts the maximum number of rows returned by a query.
Explanation
It helps prevent unnecessarily retrieving a very large result set.
- 23
Why might a query with
LIMIT 5return fewer than five rows?Model answer
It returns at most five rows, so it can return fewer if fewer than five rows match the query.
Explanation
LIMITcaps the result; it does not create additional rows. - 24
What does
ORDER BYdo?Model answer
ORDER BYsorts query results according to one or more columns.Explanation
Sorting is ascending by default unless
DESCis specified. - 25
How do ascending and descending order differ?
Model answer
Ascending order goes from lower values to higher values, while descending order goes from higher values to lower values.
Explanation
Use
ASCfor ascending order andDESCfor descending order. - 26
In what order should
ORDER BYandLIMITcommonly be written when requesting the top results?Model answer
Sort the rows with
ORDER BYfirst and then restrict the sorted result withLIMIT.Explanation
This ensures that the limit selects the highest- or lowest-ranked rows rather than an arbitrary subset.
- 27
What does
DISTINCTdo?Model answer
DISTINCTremoves duplicate values from the selected result.Explanation
For example,
SELECT DISTINCT country_code FROM usersreturns each country code once. - 28
What is the difference between
NULLand an empty string?Model answer
NULLrepresents the absence of a value, whereas an empty string is a text value with length zero.Explanation
They represent different database states and should not be treated as equivalent.
- 29
How do you test for missing values in SQL?
Model answer
Use
IS NULLto find missing values andIS NOT NULLto find values that are present.Explanation
Equality comparisons such as
= NULLdo not correctly test for nullness. - 30
What are common SQLite data types?
Model answer
SQLite commonly uses
NULL, integer, real, text, and blob values.Explanation
Integers represent whole numbers, reals represent fractional numbers, text stores strings, and blobs store binary data.
- 31
How does SQLite represent Boolean values when they are returned?
Model answer
SQLite represents false and true as the integers 0 and 1, respectively.
Explanation
SQLite accepts Boolean keywords but stores and returns them as integer values.
- 32
How does SQLite's type system differ from PostgreSQL's?
Model answer
SQLite uses loose type enforcement and may allow values of different types in a column, while PostgreSQL applies stricter type checking.
Explanation
SQLite may allow an integer in a column declared as text, whereas PostgreSQL would generally reject it.
- 33
What is a
VARCHARtype used for in databases that support it?Model answer
VARCHARstores text with a specified maximum length.Explanation
A known length limit can allow database storage and performance optimizations.
- 34
Why are monetary values commonly stored as integers?
Model answer
Money is often stored as an integer in the smallest currency unit, such as cents, to avoid floating-point rounding errors.
Explanation
For example, five dollars and sixty-seven cents can be stored as 567 cents.
- 35
What is a database schema?
Model answer
A database schema describes how data is organized, including its tables, columns, names, data types, and relationships.
Explanation
The schema defines the shape of the database rather than the particular records currently stored.
- 36
What does a
CREATE TABLEstatement define?Model answer
It defines a table's name and its columns, data types, and optional constraints.
Explanation
Columns are listed inside parentheses following the table name.
- 37
What is the purpose of a primary key?
Model answer
A primary key uniquely identifies each row and does not allow null or duplicate values.
Explanation
A table normally has one primary key, often an integer
idcolumn. - 38
Why is a dedicated
idcolumn generally preferred over using an email address as a primary key?Model answer
A dedicated identifier remains stable even if business rules later change, such as allowing duplicate or changed email addresses.
Explanation
Using mutable business data as an identifier can make future changes difficult throughout the application.
- 39
What does a
UNIQUEconstraint enforce?Model answer
A
UNIQUEconstraint prevents duplicate non-null values in a column or combination of columns.Explanation
Unlike a primary key, a table may have multiple unique constraints and unique columns may generally allow nulls.
- 40
What does a
NOT NULLconstraint enforce?Model answer
It requires every inserted row to contain a value for the constrained column.
Explanation
It prevents missing values in fields that the schema considers mandatory.
- 41
What is a foreign key?
Model answer
A foreign key is a column whose values reference a primary key in another table.
Explanation
Foreign keys create relationships between tables.
- 42
What does a foreign key constraint protect against?
Model answer
It prevents a row from referencing a record that does not exist in the related table.
Explanation
This preserves referential integrity between related records.
- 43
What does
ALTER TABLEallow a developer to do?Model answer
It allows an existing table to be changed, including renaming tables or columns and adding or dropping columns.
Explanation
The latter part of the statement specifies the particular alteration.
- 44
What is a database migration?
Model answer
A database migration is an incremental change to a database schema, such as adding a column or table.
Explanation
Migrations allow a production database to evolve alongside application code.
- 45
Why are migrations that add a table or column generally safer than migrations that remove one?
Model answer
Existing application code usually ignores newly added resources, while removing a resource can break code that still depends on it.
Explanation
Adding unused schema elements normally does not invalidate existing queries.
- 46
What is the safe order for removing a column or table?
Model answer
First update and deploy the application so it stops using the resource, then remove the resource from the database.
Explanation
This prevents active code from querying a column or table that no longer exists.
- 47
Why are renaming migrations especially difficult?
Model answer
Old application code expects the old name while new code expects the new name, creating a period in which the database and code can disagree.
Explanation
Renaming may require coordinated deployment, copying, aliasing, or planned downtime.
- 48
What is an up migration?
Model answer
An up migration moves the database schema forward to a newer version.
Explanation
Up migrations are applied incrementally in chronological order.
- 49
What is a down migration?
Model answer
A down migration reverses an associated up migration so the schema can be rolled back.
Explanation
Down migrations are mainly a recovery mechanism when a change causes problems.
- 50
Why should developers be especially careful when changing persisted database data?
Model answer
Data changes can be harder to reverse than code changes, and restoring old code does not necessarily restore altered or deleted data.
Explanation
Persisted production data may require backups or recovery procedures.
- 51
What is a relational database?
Model answer
A relational database stores data in tables and supports relationships between records in different tables.
Explanation
Keys allow entities such as users, transactions, posts, and comments to reference one another.
- 52
What is a non-relational database?
Model answer
A non-relational database does not generally support the same complex table-based relationships as a relational database.
Explanation
Many non-relational systems store nested or document-like data instead of normalized tables.
- 53
What is a one-to-one relationship?
Model answer
A one-to-one relationship means each record in one entity corresponds to at most one record in another entity.
Explanation
A one-to-one relationship can often be represented as an additional column on the same table.
- 54
How is a one-to-many relationship commonly modeled?
Model answer
The table on the many side contains a foreign key referencing the table on the one side.
Explanation
For example, many tweets can contain a
user_idthat references one user. - 55
How is a many-to-many relationship commonly modeled?
Model answer
It is modeled with a joining table containing foreign keys for both related entities.
Explanation
A user-groups joining table can associate many users with many groups.
- 56
What is the purpose of a joining table?
Model answer
A joining table stores relationships between entities, usually using only the identifiers of the related records.
Explanation
It avoids forcing a many-to-many relationship into a single foreign-key column.
- 57
Why should a joining table often use a unique constraint across its two foreign keys?
Model answer
The constraint prevents the same relationship between two entities from being stored more than once.
Explanation
For example, the same user should not be associated with the same group in duplicate rows.
- 58
What is data normalization intended to achieve?
Model answer
Normalization reduces data redundancy and improves data integrity by organizing information so it is not unnecessarily duplicated.
Explanation
Less duplication reduces the chance that one copy will be updated while another remains stale.
- 59
What are the two rules of first normal form described in the material?
Model answer
Every row must have a unique primary key, and tables cannot be nested inside other tables.
Explanation
A dedicated unique identifier prevents completely duplicate rows.
- 60
What additional dependency rule defines second normal form?
Model answer
Every non-key column must depend on the entire primary key, not merely part of a composite primary key.
Explanation
Moving a column that depends on only part of a composite key into another table reduces redundancy.
- 61
What additional dependency rule defines third normal form?
Model answer
Non-key columns must depend only on the primary key and not on other non-key columns.
Explanation
A value that can be calculated from another non-key value is often redundant and should not be stored separately.
- 62
What problem does Boyce-Codd normal form address?
Model answer
It addresses cases with multiple candidate keys where a key column depends on a non-key column.
Explanation
It adds a stricter dependency rule beyond third normal form.
- 63
Why is storing a user's birthday generally better than storing their current age?
Model answer
A birthday remains correct over time, while a stored age becomes outdated unless it is repeatedly updated.
Explanation
The current age can be calculated from the raw birthday whenever needed.
- 64
What is data redundancy?
Model answer
Data redundancy is the unnecessary storage of the same information in multiple locations.
Explanation
For example, storing a user's address in two tables can cause the copies to become inconsistent.
- 65
What is the difference between normalized and denormalized data design?
Model answer
Normalization minimizes duplication, while denormalization intentionally duplicates or precomputes data to improve query performance.
Explanation
Denormalization can speed up frequent queries but creates additional consistency risks.
- 66
What is an ORM?
Model answer
An object-relational mapper is a library that maps objects or structs in application code to rows and tables in a database.
Explanation
An ORM can generate SQL for common operations such as creating, updating, and deleting records.
- 67
What is a major advantage of using an ORM?
Model answer
An ORM makes application code less verbose by replacing many repeated raw SQL statements with library methods.
Explanation
For example, a create method can generate an
INSERTstatement from an object. - 68
What is a major trade-off of using an ORM?
Model answer
An ORM improves simplicity but can reduce direct control over SQL and may generate inefficient queries.
Explanation
Production systems often use an ORM for routine operations while retaining raw SQL as an escape hatch.
- 69
How does data typically flow through a web application?
Model answer
The front end communicates with the backend through HTTP, and the backend communicates with the database using SQL.
Explanation
The backend converts incoming HTTP requests into database operations and converts results into HTTP responses.
- 70
Which HTTP methods commonly correspond to CRUD operations?
Model answer
POST commonly maps to create, GET to read, PUT to update, and DELETE to delete.
Explanation
This is a common convention for CRUD-style web servers.
- 71
What happens when a new user submits a registration form?
Model answer
The front end sends the data to the backend in an HTTP request, and the backend converts it into a SQL operation such as an
INSERT.Explanation
The database normally communicates with the backend rather than directly with the front end.
- 72
Why should dynamic SQL values not be inserted using ordinary string concatenation?
Model answer
String concatenation can allow SQL injection, in which user input changes the intended SQL command.
Explanation
Database libraries provide parameterized queries or safe interpolation to prevent this vulnerability.
- 73
What is SQL injection?
Model answer
SQL injection is an attack in which malicious input is interpreted as part of a SQL statement and changes what the query executes.
Explanation
An attacker might terminate an intended statement and add commands such as dropping a table.
- 74
How should SQL injection be prevented?
Model answer
Use a trusted database library's parameterized-query or safe-interpolation features instead of manually concatenating user input into SQL.
Explanation
The library sanitizes values so they are treated as data rather than SQL code.
- 75
What does an
INSERTstatement do?Model answer
An
INSERTstatement adds one or more new rows to a table.Explanation
The listed column values must correspond to the listed columns.
- 76
What is the purpose of
AUTOINCREMENTor automatic integer IDs?Model answer
Automatic IDs assign a new identifier without requiring application code to determine the next available number.
Explanation
SQLite can automatically increment an integer primary-key ID under the described conditions.
- 77
What is a UUID, and why might it be used as an identifier?
Model answer
A UUID is a very large randomly generated identifier whose enormous number of possible values makes collisions extremely unlikely.
Explanation
UUIDs allow records to receive identifiers without first reading the database for the next integer.
- 78
What does an
UPDATEstatement do?Model answer
An
UPDATEstatement changes one or more column values in existing rows.Explanation
A
WHEREclause should normally identify exactly which rows should be changed. - 79
Why should an update query use a precise
WHEREcondition?Model answer
Without a precise condition, the update may modify multiple unintended rows.
Explanation
Using a stable primary key is often safer than filtering by a non-unique name.
- 80
What does a
DELETEstatement do?Model answer
A
DELETEstatement removes rows from a table.Explanation
A delete without a
WHEREclause can remove every row in the table. - 81
What safety practice is recommended before deleting production data?
Model answer
Run the intended condition as a
SELECTfirst to verify exactly which rows would be deleted, then convert it toDELETE.Explanation
This helps catch an incorrect or overly broad
WHEREclause. - 82
What is a soft delete?
Model answer
A soft delete marks a record as deleted, often with a timestamp, instead of physically removing it.
Explanation
Application queries then exclude records marked as deleted.
- 83
What are two disadvantages of soft deletes?
Model answer
They add filtering complexity and may conflict with privacy requirements because supposedly deleted data remains stored.
Explanation
Keeping many deleted rows can also increase table size and reduce query performance.
- 84
What is the purpose of database backups?
Model answer
Backups allow a production database to be restored after catastrophic deletion, corruption, or application errors.
Explanation
A backup preserves a recoverable copy separate from the live database.
- 85
How do periodic database snapshots work?
Model answer
An automated process copies the production database at intervals, such as hourly or daily, and stores the copies separately.
Explanation
Restoring a snapshot may lose changes made after the snapshot was taken.
- 86
What is an append-only log backup strategy?
Model answer
It records every database change in a log that is only appended to, allowing the sequence of changes to be replayed.
Explanation
This provides more fine-grained recovery than occasional snapshots but is more complex.
- 87
What is an SQL alias?
Model answer
An alias temporarily gives a table or column a different name within a query.
Explanation
The
ASkeyword can make queries and returned column names shorter or clearer. - 88
What does the
IIFfunction do in SQLite?Model answer
IIFreturns one value when a condition is true and another value when it is false.Explanation
It can create computed result columns such as an audit status.
- 89
What is an aggregate function?
Model answer
An aggregate function combines values from multiple rows into a summarized result.
Explanation
Examples include
COUNT,SUM,MIN,MAX, andAVG. - 90
What does
COUNT(*)return?Model answer
It returns the number of rows in the selected result set.
Explanation
It is useful when the number of matching records matters more than their individual contents.
- 91
What does the
SUMfunction return?Model answer
It returns the total of the numeric values in a specified column.
Explanation
Summing transaction amounts can calculate a user's balance when the data model requires it.
- 92
What do
MINandMAXreturn?Model answer
MINreturns the smallest value, whileMAXreturns the largest value in a set.Explanation
They can be used to find values such as the youngest age or largest transaction.
- 93
What does the
AVGfunction do with null values?Model answer
AVGignores null values when calculating the average.Explanation
Only values that are present contribute to the average.
- 94
What does
GROUP BYdo?Model answer
GROUP BYdivides rows into groups so aggregate functions can produce one result for each group.Explanation
For example, grouping by
user_idallows a separate transaction total for every user. - 95
What is the difference between
WHEREandHAVING?Model answer
WHEREfilters individual rows before grouping, whileHAVINGfilters grouped results after aggregation.Explanation
Use
HAVINGwhen the condition depends on an aggregate such asCOUNTorSUM. - 96
What does the
ROUNDfunction do?Model answer
ROUNDreduces a numeric value to a specified number of decimal places; without a precision argument, SQLite rounds to a whole number.Explanation
It is often used to make aggregate results easier to display.
- 97
What is a subquery?
Model answer
A subquery is a query nested inside another query whose result is used by the outer query.
Explanation
A subquery can, for example, find a user's ID by name while the outer query retrieves that user's transactions.
- 98
Does a subquery create a permanent table?
Model answer
No. A subquery produces a temporary result only while the statement is executing.
Explanation
Its result is not automatically stored as a new database table.
- 99
What is an inner join?
Model answer
An inner join returns rows whose join condition matches in both tables.
Explanation
A plain
JOINusually means an inner join. - 100
What does the
ONclause specify in a join?Model answer
The
ONclause specifies the condition used to match rows from the joined tables.Explanation
A common condition matches a foreign key in one table with a primary key in another.
- 101
Why are table-qualified column names useful in joins?
Model answer
They identify which table a column belongs to when multiple tables contain columns with the same name.
Explanation
For example,
users.nameandcountries.namedistinguish two differentnamecolumns. - 102
What does a left join return?
Model answer
A left join returns every row from the left table and matching rows from the right table, using nulls when no match exists.
Explanation
It is useful when records without related data must still appear.
- 103
Why is a right join often unnecessary?
Model answer
A right join can usually be replaced by swapping the table order and using a left join.
Explanation
The two forms can express the same relationship while left joins are more widely supported and easier to reason about.
- 104
What does a full join return?
Model answer
A full join returns all rows from both tables, whether or not matching rows exist in the other table.
Explanation
Unmatched columns are represented with null values.
- 105
Can a join return more rows than either individual table?
Model answer
Yes. If one row matches multiple rows in the other table, the join can produce multiple result rows for that original row.
Explanation
Grouping and aggregation can combine related rows when one result row per entity is desired.
- 106
What is an SQL index?
Model answer
An index is an in-memory database structure that helps queries locate matching rows efficiently.
Explanation
Indexes commonly use tree-based structures to avoid scanning every row.
- 107
What is the typical lookup complexity of a binary-tree index?
Model answer
A binary-tree index provides a lookup that is approximately O(logn) rather than O(n).
Explanation
The database can search a sorted structure instead of checking every row sequentially.
- 108
Why are primary-key columns commonly indexed automatically?
Model answer
Primary keys are frequently used to locate individual rows, so indexing them makes those lookups efficient while enforcing uniqueness.
Explanation
An ID lookup is a common database operation.
- 109
When should a developer add an index to a non-primary-key column?
Model answer
Add one when frequent lookups on that column become slow or are expected to become a performance bottleneck.
Explanation
For example, frequent searches by email may justify an index on the email column.
- 110
Why should developers avoid indexing every column?
Model answer
Indexes consume memory and make writes slower because each insert or update must also maintain the indexes.
Explanation
Indexes improve reads but have storage and write-performance costs.
- 111
What is a multi-column index?
Model answer
A multi-column index indexes a combination of columns for queries that commonly filter on those columns together.
Explanation
The order of columns matters because the index is sorted by the first column, then the next.
- 112
Why does the order of columns in a multi-column index matter?
Model answer
Queries using the index's first column can benefit substantially, while queries using only later columns may receive little or no benefit.
Explanation
The first column determines the primary ordering of the indexed structure.
- 113
Why might a database be denormalized?
Model answer
A database may be denormalized to speed up expensive or frequently executed queries by storing duplicated or precomputed data.
Explanation
Denormalization trades simpler and faster reads for additional consistency risks.
- 114
Why should developers generally normalize before considering denormalization?
Model answer
A normalized design is easier to keep accurate and avoids unnecessary duplication; denormalization should be added only when performance needs justify it.
Explanation
Correctness and maintainability should usually be established before optimizing for speed.

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