SQL and Database Fundamentals
- 90Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
Why is SQL important in modern digital systems, and what kinds of tasks does it support?
90 questions
- 1
Why is SQL important in modern digital systems, and what kinds of tasks does it support?
Model answer
SQL is the standard language for communicating with relational databases. It supports retrieving, managing, and analyzing data used by applications and business systems.
Explanation
Everyday services such as online banking, shopping, and package tracking rely on databases, and SQL lets applications and users work with their data.
- 2
How can businesses use SQL to turn raw data into useful information?
Model answer
They can use SQL to ask questions about sales, customers, inventory, and trends, then retrieve results that support business decisions.
Explanation
For example, a retailer can identify popular products, valuable customers, seasonal sales patterns, or possible fraud.
- 3
What does the
SELECTclause specify, and what does theFROMclause specify?Model answer
SELECTspecifies which columns to return, whileFROMidentifies the table from which to retrieve them.Explanation
These clauses form the basic structure of a query that retrieves data.
- 4
What does the asterisk in
SELECT *mean, and why should it usually be avoided in production queries?Model answer
The asterisk requests every column. In production, it can make the database retrieve unnecessary data, increasing input/output work and memory use and potentially slowing the query.
Explanation
Selecting only needed columns is more efficient and makes the query's purpose clearer.
- 5
How does a
WHEREclause affect a query's results?Model answer
It filters individual rows, returning only those for which the specified condition is true.
Explanation
For example, filtering on a product category can return only the rows for that category.
- 6
What kinds of comparisons can SQL operators in a
WHEREclause make?Model answer
Comparison operators can test equality, inequality, and relative size, including less-than and greater-than relationships. They can be used with numeric values, dates, and text.
Explanation
A comparison can, for example, select products above a price threshold or dates within a chosen range.
- 7
How does the
LIKEoperator work with the%wildcard?Model answer
LIKEmatches text patterns, and%represents any sequence of characters, including no characters.Explanation
A pattern such as
LIKE 'men%'matches text beginning with “men.” - 8
How can a query filter records to a date range without relying on a date-extraction function?
Model answer
Compare the date column directly with the range's start and end dates in the
WHEREclause.Explanation
Direct comparisons can filter dates from a chosen period and can allow an index on the date column to be used.
- 9
How do
ANDandORdiffer in aWHEREclause?Model answer
ANDrequires every joined condition to be true, whileORrequires at least one condition to be true.Explanation
ANDnarrows results to rows satisfying all conditions;ORcan include rows satisfying either condition. - 10
What is SQL's precedence rule when
ANDandORare combined, and how can parentheses change the logic?Model answer
ANDis evaluated beforeOR. Parentheses explicitly group conditions and can make the intended logic clear or change how conditions are evaluated.Explanation
Without parentheses, a condition combining categories with a brand filter may apply the brand requirement only to the final
ANDcondition. - 11
What does the
NOToperator do, and what should you consider when combining it with other logical operators?Model answer
NOTreverses a condition's truth value. Use parentheses when combining it withANDorORto make the intended logic explicit.Explanation
Grouping logical conditions helps prevent unexpected filtering results.
- 12
What does
DISTINCTdo in a query?Model answer
DISTINCTremoves duplicate results, leaving only unique values or combinations of selected values.Explanation
A manufacturer that appears in many matching sales records can appear only once in a distinct manufacturer list.
- 13
When
DISTINCTis applied to multiple selected columns, what counts as a duplicate?Model answer
A result is duplicated only when the entire combination of selected column values repeats.
Explanation
For instance, the same manufacturer paired with two different colors produces two distinct combinations.
- 14
How does
ORDER BYarrange query results, and what are its default and descending behaviors?Model answer
ORDER BYsorts results by one or more columns. The default is ascending;DESCrequests descending order.Explanation
Ascending order runs from A to Z, smallest to largest, or earliest to latest; descending reverses those sequences.
- 15
How does sorting by multiple columns work, and does
ORDER BYchange which rows a query returns?Model answer
Columns are applied in sequence: the first sorts the results, and later columns sort within earlier-column groups. Sorting changes the presentation order, not which rows are returned.
Explanation
For example, sorting by color and then descending price groups colors and orders prices within each group.
- 16
What does
GROUP BYdo to rows in a query?Model answer
GROUP BYcollects rows that share values in one or more columns so calculations can be performed separately for each group.Explanation
Grouping sales by category allows a separate total to be calculated for each category.
- 17
What does each of the aggregate functions
COUNT,SUM,AVG,MIN, andMAXcalculate?Model answer
COUNTcounts rows,SUMadds numeric values,AVGcalculates their average, andMINandMAXreturn the smallest and largest values.Explanation
These functions summarize data within a group or across a selected set of rows.
- 18
How could a retailer calculate total revenue for each product category?
Model answer
Group sales by category and sum the product of each sale's price and quantity for each group.
Explanation
The category column defines the groups, and the aggregate calculation produces a revenue total for each one.
- 19
What is the purpose of giving a calculated aggregate an alias with
AS?Model answer
An alias assigns a readable name to the calculated result in the query output.
Explanation
Naming a summed value “total revenue” makes the result easier to interpret.
- 20
How does
HAVINGdiffer fromWHERE?Model answer
WHEREfilters individual rows before grouping, whileHAVINGfilters groups afterGROUP BYand aggregation.Explanation
Use
HAVINGto keep only groups meeting an aggregate threshold, such as categories whose revenue exceeds a specified amount. - 21
Why can't
WHEREbe used to filter a result based on an aggregate such as a group total?Model answer
WHEREruns before groups and their aggregates are created, so the aggregate result is not yet available to filter.Explanation
HAVINGapplies after grouping and is designed to filter using aggregate results. - 22
Why is storing customer, product, manufacturer, and sale details in one large table problematic?
Model answer
It duplicates information, wastes storage, and can cause errors or inconsistent values when repeated details need to be updated.
Explanation
If a customer's address is repeated for many purchases, changing it requires updating every copy correctly.
- 23
What is normalization, and what is its main purpose?
Model answer
Normalization organizes data into multiple related tables, each focused on a particular entity, to minimize repetition and improve consistency.
Explanation
Customer, product, manufacturer, and sale information can be stored separately rather than repeated in one large table.
- 24
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
A customer ID can distinguish one customer record from every other customer record.
- 25
What is a foreign key, and how does it connect tables?
Model answer
A foreign key is a column in one table whose values refer to primary key values in another table.
Explanation
A sale can store a customer ID that points to the customer's full record without repeating the customer's name and address.
- 26
How do primary and foreign keys help reduce redundancy while preserving relationships between records?
Model answer
Details are stored once in their main table, while related tables store key values that refer to those details.
Explanation
A sale can refer to a product by product ID rather than repeating the product description.
- 27
What is an inner join, and which rows does it return?
Model answer
An inner join combines rows from related tables and returns only rows with matching values in both tables.
Explanation
A product with no matching sale is excluded from an inner join between product and sale.
- 28
What information does an
ONclause provide in a join?Model answer
It specifies the condition that relates the tables, commonly matching a foreign key in one table to a primary key in another.
Explanation
The condition tells the database which rows from the joined tables belong together.
- 29
Why should a query joining tables usually list needed columns explicitly instead of selecting all columns?
Model answer
Explicit column selection avoids retrieving unnecessary data, makes the query clearer, and prevents confusion when tables have columns with the same name.
Explanation
A broad selection from multiple tables can return many unwanted or ambiguously named columns.
- 30
How can a query retrieve information linked across three or more related tables?
Model answer
Chain joins by matching the related keys between each successive pair of tables.
Explanation
A query can connect sales to products and products to manufacturers to retrieve information from all three.
- 31
What are table aliases, and why are they useful in multi-table queries?
Model answer
Aliases are temporary short names for tables within a query. They reduce repeated table names and make references in complex joins more concise and readable.
Explanation
A short alias can replace a long table name when qualifying selected columns and join conditions.
- 32
How could a query find products made by Texas manufacturers and sold to customers in California?
Model answer
Join the sale, customer, product, and manufacturer tables through their related keys, then filter customers by California and manufacturers by Texas.
Explanation
The joins connect the transaction to both the customer and the product's manufacturer, allowing conditions from both tables to be applied.
- 33
How does a left join differ from an inner join?
Model answer
A left join keeps every row from the left table and adds matching right-table data where available; an inner join keeps only matching rows.
Explanation
Rows without a right-table match remain in a left join, with
NULLvalues for the right-table columns. - 34
How do right joins and full joins handle unmatched rows?
Model answer
A right join keeps all rows from the right table, while a full join keeps all rows from both tables; unmatched columns are filled with
NULL.Explanation
These outer joins retain nonmatching records that an inner join would exclude.
- 35
How could a retailer list every product and show a sale date only when the product has been sold?
Model answer
Use a left join from the product table to the sale table.
Explanation
This preserves every product; products without a matching sale have
NULLin the sale-date columns. - 36
What is a Cartesian product in the context of a join, and why can it be dangerous?
Model answer
It combines every row from one table with every row from another, potentially creating an enormous result that consumes excessive memory and processing resources.
Explanation
It can result from omitting a join condition or using the wrong columns in that condition.
- 37
Why is an explicit join condition generally preferable to a natural join?
Model answer
An explicit condition clearly states which columns connect the tables. A natural join guesses from matching column names and can produce surprises if names change.
Explanation
Explicit joins make the intended relationship visible in the query.
- 38
What does the
INSERTstatement do, and what is its basic structure?Model answer
INSERTadds new rows to a table, typically by naming the target table and columns, then supplying corresponding values.Explanation
Listing columns alongside the values makes their correspondence clear.
- 39
Why is it best practice to list target columns explicitly in an
INSERTstatement?Model answer
It clarifies which values go into which columns and makes the statement more resilient if the table later gains another column.
Explanation
Relying on a table's default column order can cause an insert to break when the structure changes.
- 40
What happens to columns omitted from an
INSERTstatement?Model answer
They receive their defined default values if available; otherwise, they typically receive
NULL.Explanation
The outcome depends on the column's definition in the table.
- 41
What does
NULLrepresent, and how is it different from zero or an empty string?Model answer
NULLrepresents a missing, unknown, or inapplicable value; it is not the same as zero or an empty string.Explanation
It indicates the absence of a known or applicable value rather than a particular numeric or text value.
- 42
How can data from one table be inserted into another table?
Model answer
Use an
INSERT INTO ... SELECTstatement to select rows from a source table and insert them into the target table.Explanation
A filter on the
SELECTcan limit which source rows are copied, such as when archiving older sales. - 43
How do primary-key and foreign-key constraints protect data during insertion?
Model answer
They reject inserts that reuse an existing primary-key value or refer to a foreign-key value that does not exist in the referenced table.
Explanation
These checks preserve uniqueness and valid relationships between records.
- 44
What does an
UPDATEstatement do, and how does itsWHEREclause affect the change?Model answer
UPDATEchanges values in existing rows, and itsWHEREclause specifies which rows are changed.Explanation
Without a
WHEREclause, the update applies to every row in the table. - 45
What is the danger of running an
UPDATEwithout aWHEREclause?Model answer
The update changes the specified columns in every row, which can cause widespread data corruption.
Explanation
For example, updating a product price without a filter could assign the same price to every product.
- 46
What safety check should be performed before an
UPDATE?Model answer
Run a
SELECTusing the exact sameWHEREcondition to preview the rows and values that will be affected.Explanation
Checking the target records before changing them can reveal an incorrect filter or unexpected row count.
- 47
Can the syntax for updating data across multiple related tables vary between database systems?
Model answer
Yes. Database systems may support different forms of multi-table updates, so the specific system's syntax should be checked.
Explanation
Some systems allow an update with a join, while others may require a different structure or separate statements.
- 48
What does
DELETEremove, and what is the risk of omitting itsWHEREclause?Model answer
DELETEremoves rows from a table. Without aWHEREclause, it removes every row while leaving the table structure in place.Explanation
A missing filter can empty a table unintentionally.
- 49
What should you do before running a
DELETEstatement?Model answer
Run a
SELECTwith the sameWHEREcondition to verify which rows would be deleted.Explanation
This preview helps confirm the deletion targets before data is removed.
- 50
Why may deleted data be difficult to recover?
Model answer
It is typically gone unless a backup exists or the deletion is within a transaction that can be rolled back.
Explanation
A deletion should therefore be treated as potentially permanent.
- 51
What are the common ways a foreign-key constraint can govern deletion of a referenced parent record?
Model answer
It can restrict the deletion, cascade the deletion to child records, or set the child foreign key to
NULLor a default value.Explanation
The configured behavior determines what happens to records that refer to the parent.
- 52
How do
RESTRICTandCASCADEdiffer when deleting a parent record?Model answer
RESTRICTprevents deletion while dependent child records exist;CASCADEautomatically deletes those child records too.Explanation
Cascade can remove large amounts of related data, so its consequences must be understood before deleting.
- 53
What is a soft delete, and why might an organization use one?
Model answer
A soft delete marks a record inactive or records a deletion date instead of physically removing it. This preserves data for reporting or auditing while normal views can filter it out.
Explanation
It can be a safer approach when historical information needs to remain available.
- 54
How does
DROP TABLEdiffer fromDELETE?Model answer
DELETEremoves rows but leaves the table structure;DROP TABLEremoves the table, its structure, indexes, and its data.Explanation
Dropping a table is a more extensive and potentially permanent structural change.
- 55
What precautions should be taken before dropping a table?
Model answer
Make a reliable backup, check dependencies, test in a non-production environment, and consider using
DROP TABLE IF EXISTSin scripts.Explanation
These steps reduce the risk of losing needed data or disrupting other database objects.
- 56
If one table has a foreign key referencing another, which table should generally be dropped first?
Model answer
Drop the referencing child table before the referenced parent table.
Explanation
The parent may not be droppable while another table still depends on it.
- 57
Why is understanding a database's dependency structure important before structural changes?
Model answer
Other tables, views, or stored procedures may rely on the object being changed, and those dependencies can cause errors or unexpected effects.
Explanation
Checking dependencies helps identify the effects and required order of structural changes.
- 58
What is the recommended priority order when developing SQL queries?
Model answer
Prioritize correctness first, readability second, and optimization third.
Explanation
A fast query that returns incorrect information is useless or potentially harmful; optimization should follow a correct, understandable query.
- 59
Why should query optimization generally not be attempted before correctness and readability are established?
Model answer
Premature optimization can create unnecessary complexity without addressing the actual performance bottleneck.
Explanation
The query should first be accurate and understandable, then optimized if its performance warrants it.
- 60
How can comments make SQL easier to maintain?
Model answer
Comments can explain why complex logic, filters, or joins were chosen, helping later readers understand the query's intent.
Explanation
Explaining the reason behind a decision can be more useful than merely restating what the SQL already says.
- 61
What formatting practices can improve SQL readability?
Model answer
Use consistent capitalization and formatting, put selected columns and conditions on separate lines, and indent logically.
Explanation
Consistent layout makes the structure of a query easier to scan and maintain.
- 62
Why should explicit join syntax be preferred over putting join conditions in the
WHEREclause?Model answer
Explicit join syntax separates table-joining logic from row-filtering logic, making the query clearer.
Explanation
That separation makes the purpose of each condition easier to understand.
- 63
What is the conceptual processing order for
FROMand joins,WHERE,GROUP BY,HAVING,SELECT,UNION, andORDER BY?Model answer
The conceptual order is
FROMand joins,WHERE,GROUP BY,HAVING,SELECT,UNIONif used, thenORDER BY.Explanation
The database optimizer may change the actual execution strategy, but this order helps explain query logic.
- 64
Why is it usually beneficial to filter unwanted rows as early as possible?
Model answer
Early filtering reduces the number of rows that later, more costly operations such as grouping and sorting must process.
Explanation
WHEREfilters individual rows beforeGROUP BY, so it can reduce the input to aggregation. - 65
What is an index, and how can it speed up data retrieval?
Model answer
An index is a separate data structure containing ordered values and pointers to table rows, allowing the database to locate matching rows without scanning the entire table.
Explanation
It works like a book index that directs readers to relevant pages.
- 66
What is a full table scan, and when might a database perform one?
Model answer
A full table scan reads every row to find matches; it may be needed when no usable index supports the search.
Explanation
Scanning a large table can be slower than using an index to locate relevant rows.
- 67
Why can creating too many indexes harm database performance?
Model answer
Indexes can speed up reads but slow inserts, updates, and deletes because the database must also maintain affected indexes.
Explanation
Each additional relevant index adds work when data changes.
- 68
Which columns are generally good candidates for indexes, and which may be poor candidates?
Model answer
Frequently searched or joined columns, and sometimes columns used for sorting, are candidates. Rarely searched or frequently updated columns may be poor choices if the read benefit does not justify the write cost.
Explanation
Indexing should balance faster retrieval against the overhead of maintaining indexes.
- 69
What does it mean for a
WHEREcondition to be sargable?Model answer
A sargable condition is written so the database can use an index to satisfy the search.
Explanation
The term refers to whether a condition can serve as an index-usable search argument.
- 70
Why can applying a function directly to an indexed column in a
WHEREclause prevent efficient index use?Model answer
The database may have to apply the function to every row's column value before testing the condition, preventing an effective index lookup.
Explanation
Filtering on an extracted year from a date can require processing each date value.
- 71
How can a date query that selects records from one year be written to preserve possible index use?
Model answer
Compare the unmodified date column directly against the year's start and end boundaries.
Explanation
A direct range condition leaves the indexed column available for an index lookup.
- 72
How can the position of a wildcard in a
LIKEpattern affect index use?Model answer
A leading wildcard often prevents index use, while a pattern with the wildcard only at the end can often use an index.
Explanation
A prefix pattern can be searched more directly than a pattern that can begin with any characters.
- 73
When should an exact-match comparison be preferred over
LIKE?Model answer
Prefer an exact-match comparison when an exact match is what the query requires.
Explanation
Using
LIKEunnecessarily can be less suitable than expressing a direct equality condition. - 74
Why might
EXISTSbe faster thanINwhen checking a large subquery result?Model answer
EXISTSchecks whether any matching row is present and can stop once it finds one, whileINmay need to process the subquery's result.Explanation
The performance difference can depend on the query and database system.
- 75
What are several ways to make join operations more efficient?
Model answer
Join only necessary tables, filter rows before joining when possible, and use an inner join when nonmatching rows are not needed.
Explanation
These choices can reduce the rows and extra work involved in the join.
- 76
Why can an inner join be faster than an outer join?
Model answer
An inner join does not need the additional work of retaining unmatched rows and generating
NULLvalues for them.Explanation
When nonmatching records are not required, an inner join may avoid that extra processing.
- 77
Why can a join be preferable to a correlated subquery or repeated per-row queries?
Model answer
A join can let the database retrieve related data in one operation rather than repeatedly running a subquery or issuing a separate query for each item.
Explanation
This can reduce repeated work and application-to-database round trips, including the N-plus-one query problem.
- 78
How do
UNIONandUNION ALLdiffer, and when isUNION ALLpreferable?Model answer
UNIONremoves duplicate rows, whileUNION ALLretains them. UseUNION ALLwhen duplicates are acceptable or cannot occur, because it avoids the work of removing duplicates.Explanation
Duplicate removal can require extra processing, such as sorting.
- 79
What information can an execution plan provide when diagnosing a slow query?
Model answer
It can show the tables and access order, index use or table scans, join algorithms, row counts, and estimated or actual costs or times.
Explanation
Tools such as
EXPLAINor execution-plan displays help identify where a query is spending time or processing excessive rows. - 80
What is a common table expression, and how can it help with a complex query?
Model answer
A CTE is a named temporary result set defined for one query. It can divide a long query into readable, modular steps.
Explanation
CTEs can make a multi-step query easier to follow than deeply nested subqueries.
- 81
What is denormalization, and why might a read-heavy application use it?
Model answer
Denormalization intentionally adds controlled redundancy to reduce expensive joins and speed up reads.
Explanation
It trades some write efficiency and normalization for faster retrieval, such as storing a customer's state on an order for reporting.
- 82
What is table partitioning, and how can it help with very large tables?
Model answer
Partitioning divides a large table into smaller physical sections based on a criterion such as date. Queries limited to particular sections may scan less data.
Explanation
A query for recent records may need to access only the relevant date partitions rather than the entire table.
- 83
What is the fundamental rule for testing SQL that can change or destroy data?
Model answer
Never test it on a production database; use a separate development, staging, or test environment.
Explanation
A non-production environment prevents experiments from damaging live data.
- 84
What are the usual stages of a reliable database integration test?
Model answer
Create the schema, load specific test data, run the code, verify the resulting state, and clean up so the next test starts fresh.
Explanation
A known starting state and explicit verification make test results more reliable.
- 85
How can a transaction make manual testing of an update or delete safer?
Model answer
Begin a transaction, run and inspect the change, then commit it if correct or roll it back if it is not.
Explanation
A rollback undoes changes made since the transaction began, allowing inspection without making the changes permanent.
- 86
What other isolated database environments may be used for testing?
Model answer
Teams can use isolated database instances, such as ones run in Docker containers, or in-memory databases such as SQLite for fast unit tests.
Explanation
These approaches provide controlled environments separate from production.
- 87
How does correcting a factual data error differ ethically from manipulating historical data?
Model answer
Correcting a clear error supports data accuracy, while changing historical records to improve appearances or hide complaints manipulates the record and undermines trust.
Explanation
Ethical data management aims to preserve the truth rather than make past results look better.
- 88
What controls should govern direct changes to production data?
Model answer
Such changes should be rare and supported by strong justification and appropriate approvals.
Explanation
Controls help ensure that production modifications are necessary and accountable.
- 89
What information should an audit trail record about a significant data change?
Model answer
It should record who made the change, what changed, when it changed, and why it changed.
Explanation
Details can include the account, affected table and column, record key, old and new values, timestamp, and a reason or linked support ticket.
- 90
How do audit trails support data integrity, accountability, and ethical data management?
Model answer
They create a traceable history that lets organizations verify who changed data, what was changed, when, and why.
Explanation
A correction remains visible as a logged change instead of being hidden, supporting audits and trust in the data.

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