🗄️

SQL MCQ

Test your SQL knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.

100 Questions 40 Beginner 40 Intermediate 20 Advanced

How This Practice Test Works

Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 40 beginner questions to confirm your fundamentals, work through the 40 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

1

What does SQL stand for?

A

Correct Answer

Structured Query Language

Explanation

SQL stands for Structured Query Language, used to manage and query relational databases.

2

Which SQL statement is used to retrieve data from a database?

B

Correct Answer

SELECT

Explanation

SELECT is the SQL statement used to query and retrieve data from one or more tables.

3

Which clause is used to filter rows based on a condition?

A

Correct Answer

WHERE

Explanation

WHERE filters rows before grouping based on a specified condition.

4

Which keyword is used to sort the result set of a query?

C

Correct Answer

ORDER BY

Explanation

ORDER BY sorts the result set by one or more columns, ascending (ASC, default) or descending (DESC).

5

Which SQL statement is used to add new rows to a table?

A

Correct Answer

INSERT INTO

Explanation

INSERT INTO table_name (columns) VALUES (values) adds new rows to a table.

6

Which statement modifies existing data in a table?

C

Correct Answer

UPDATE

Explanation

UPDATE table_name SET column = value WHERE condition modifies existing rows that match the condition.

7

Which statement removes rows from a table?

B

Correct Answer

DELETE

Explanation

DELETE FROM table_name WHERE condition removes rows matching the condition; DROP removes the entire table structure.

8

What is the purpose of a PRIMARY KEY constraint?

B

Correct Answer

To uniquely identify each row in a table and disallow NULL values

Explanation

A PRIMARY KEY uniquely identifies each record in a table; it must contain unique values and cannot contain NULLs.

9

What does the wildcard "%" represent in a LIKE pattern?

B

Correct Answer

Zero, one, or multiple characters

Explanation

In a LIKE pattern, "%" matches any sequence of zero or more characters, while "_" matches exactly one character.

10

Which keyword removes duplicate rows from a SELECT result?

B

Correct Answer

DISTINCT

Explanation

SELECT DISTINCT returns only unique combinations of the selected column values, removing duplicates.

11

What does NULL represent in SQL?

C

Correct Answer

An unknown or missing value

Explanation

NULL represents the absence of a value or an unknown value; it is not equal to 0 or an empty string.

12

How do you check if a column value is NULL in a WHERE clause?

B

Correct Answer

WHERE column IS NULL

Explanation

NULL cannot be compared with "=" because NULL is not a value; "IS NULL" (or "IS NOT NULL") is the correct way to test for it.

13

Which SQL command creates a new table?

B

Correct Answer

CREATE TABLE

Explanation

CREATE TABLE table_name (column definitions...) defines a new table and its columns.

14

What is the purpose of the LIMIT clause (or TOP in SQL Server)?

A

Correct Answer

To restrict the maximum number of rows returned by a query

Explanation

LIMIT n restricts the result set to at most n rows, commonly used for pagination or sampling.

15

Which aggregate function returns the total number of rows matching a query?

C

Correct Answer

COUNT()

Explanation

COUNT() returns the number of rows that match a specified condition, or COUNT(*) counts all rows.

16

What does the BETWEEN operator do?

A

Correct Answer

Checks if a value is within a specified range, inclusive of both endpoints

Explanation

BETWEEN x AND y selects values within the inclusive range from x to y.

17

Which clause groups rows that have the same values into summary rows?

B

Correct Answer

GROUP BY

Explanation

GROUP BY groups rows sharing the same value(s) in specified columns, typically used together with aggregate functions.

18

What is the purpose of the FOREIGN KEY constraint?

B

Correct Answer

To link a column to the primary key of another table, enforcing referential integrity

Explanation

A FOREIGN KEY establishes a relationship between two tables by referencing the primary key (or unique key) of another table.

19

Which logical operator returns true if both conditions are true?

C

Correct Answer

AND

Explanation

AND requires both conditions to be true for a row to be included in the result.

20

What does the "AS" keyword do in a SELECT statement?

A

Correct Answer

Creates an alias for a column or table

Explanation

AS assigns a temporary alias name to a column or table, often used to make output more readable.

21

Which data type is typically used to store whole numbers?

B

Correct Answer

INT

Explanation

INT (or INTEGER) is the standard SQL data type for storing whole numbers.

22

Which data type is best for storing variable-length text with a maximum size, e.g. names?

B

Correct Answer

VARCHAR

Explanation

VARCHAR(n) stores variable-length character strings up to a maximum length n, more space-efficient than fixed-length CHAR for varying text.

23

What does the IN operator do in a WHERE clause?

A

Correct Answer

Checks if a value matches any value in a specified list or subquery

Explanation

IN (value1, value2, ...) returns true if the column value matches any of the listed values, equivalent to multiple OR conditions.

24

What is a "view" in SQL?

B

Correct Answer

A virtual table based on the result of a stored SELECT query

Explanation

A view is a saved query that behaves like a virtual table, presenting data from one or more underlying tables without storing the data itself.

25

Which command grants or removes a column's default value, structure, or constraints on an existing table?

C

Correct Answer

ALTER TABLE

Explanation

ALTER TABLE is used to add, modify, or drop columns and constraints on an existing table.

26

What is the result of "5 = NULL" in SQL?

C

Correct Answer

NULL (unknown)

Explanation

Any comparison with NULL using "=" yields NULL (unknown), not TRUE or FALSE, because NULL represents an unknown value.

27

Which clause is used to filter groups after a GROUP BY, based on an aggregate condition?

B

Correct Answer

HAVING

Explanation

HAVING filters groups after aggregation, whereas WHERE filters individual rows before grouping.

28

What does "ORDER BY column DESC" do?

A

Correct Answer

Sorts the results in descending order based on the column

Explanation

DESC sorts results from highest to lowest (or Z to A for text); ASC (the default) sorts ascending.

29

Which function returns the current date and/or time in most SQL databases?

B

Correct Answer

NOW() or CURRENT_TIMESTAMP

Explanation

NOW() (MySQL) or CURRENT_TIMESTAMP (standard SQL) return the current date and time.

30

What does "SELECT * FROM table" do?

B

Correct Answer

Selects all columns of all rows from the table

Explanation

The "*" wildcard in SELECT means "all columns", returning every column for every matching row.

31

Which constraint ensures a column cannot contain NULL values?

B

Correct Answer

NOT NULL

Explanation

The NOT NULL constraint requires that a column always have a value, rejecting any insert or update that would leave it empty.

32

What does "DROP TABLE table_name" do?

B

Correct Answer

Permanently deletes the table and all its data and structure

Explanation

DROP TABLE completely removes the table definition along with all data, indexes, and constraints associated with it.

33

What does the AVG() function do?

A

Correct Answer

Returns the average (mean) value of a numeric column

Explanation

AVG() computes the arithmetic mean of the values in the specified numeric column, ignoring NULLs.

34

What is the purpose of the UNIQUE constraint?

A

Correct Answer

Ensures all values in a column are different from each other

Explanation

UNIQUE ensures that all values in a column (or combination of columns) are distinct across the table, though unlike PRIMARY KEY, multiple NULLs may be allowed depending on the database.

35

How do you add a new column to an existing table?

A

Correct Answer

ALTER TABLE table_name ADD COLUMN column_name datatype

Explanation

ALTER TABLE ... ADD COLUMN adds a new column with the specified data type to an existing table.

36

Which operator negates a condition, e.g. "WHERE NOT (age > 18)"?

A

Correct Answer

NOT

Explanation

NOT reverses the result of a boolean condition, so rows where the condition is true are excluded and vice versa.

37

What does "COUNT(DISTINCT column)" return?

B

Correct Answer

The number of unique, non-NULL values in that column

Explanation

COUNT(DISTINCT column) counts only distinct non-NULL values, removing duplicates before counting.

38

What is the difference between CHAR and VARCHAR data types?

B

Correct Answer

CHAR is fixed-length (padded with spaces), while VARCHAR is variable-length, storing only the actual characters used

Explanation

CHAR(n) always occupies n characters of storage (padding shorter strings with spaces), while VARCHAR(n) stores only the actual string length up to n.

39

Which keyword combines the result sets of two SELECT statements, removing duplicate rows?

A

Correct Answer

UNION

Explanation

UNION combines the results of two or more SELECT statements into a single result set, removing duplicate rows by default (UNION ALL keeps duplicates).

40

What is the result of "NULL OR TRUE" in SQL's three-valued logic?

C

Correct Answer

TRUE

Explanation

In three-valued logic, "NULL OR TRUE" is TRUE because the result is true regardless of the unknown operand; only "NULL OR FALSE" and "NULL AND TRUE" yield NULL.

1

What is the difference between an INNER JOIN and a LEFT JOIN?

B

Correct Answer

INNER JOIN returns only rows with matches in both tables, while LEFT JOIN returns all rows from the left table plus matched rows from the right (with NULLs where there is no match)

Explanation

INNER JOIN excludes rows without a match in both tables, whereas LEFT (OUTER) JOIN preserves all rows from the left table, filling unmatched right-side columns with NULL.

2

What is a subquery (nested query)?

B

Correct Answer

A query nested inside another query, often used in WHERE, FROM, or SELECT clauses to compute intermediate results

Explanation

A subquery is a SELECT statement embedded within another SQL statement, used to filter, compute, or supply values for the outer query.

3

What does a self-join allow you to do?

A

Correct Answer

Join a table with itself, often using aliases, to compare rows within the same table

Explanation

A self-join treats the same table as two separate instances (via aliases) to compare or relate rows to other rows in the same table, e.g. finding employees and their managers.

4

What is the purpose of an INDEX on a column?

B

Correct Answer

To speed up data retrieval operations on that column at the cost of additional storage and slower writes

Explanation

An index creates an auxiliary data structure (often a B-tree) that allows the database to find rows matching a condition much faster, but adds overhead to INSERT/UPDATE/DELETE operations.

5

What is the difference between UNION and UNION ALL?

B

Correct Answer

UNION removes duplicate rows from the combined result, while UNION ALL keeps all rows including duplicates, making it generally faster

Explanation

UNION performs an implicit DISTINCT on the combined results (requiring a sort/dedup step), whereas UNION ALL simply concatenates results without removing duplicates.

6

What does a transaction with "COMMIT" and "ROLLBACK" provide?

B

Correct Answer

A way to group multiple statements so they either all succeed (COMMIT) or all be undone (ROLLBACK), ensuring atomicity

Explanation

Transactions allow a sequence of operations to be treated as a single atomic unit: COMMIT makes all changes permanent, while ROLLBACK reverts all changes made since the transaction began.

7

What does the ACID acronym stand for in the context of database transactions?

A

Correct Answer

Atomicity, Consistency, Isolation, Durability

Explanation

ACID properties (Atomicity, Consistency, Isolation, Durability) guarantee reliable processing of database transactions.

8

What is the purpose of "GROUP BY" combined with "HAVING COUNT(*) > 1"?

B

Correct Answer

To find groups (sets of rows sharing the same grouped value) that have more than one row, often used to identify duplicates

Explanation

After grouping, HAVING COUNT(*) > 1 filters to only those groups that contain more than one row, a common pattern for detecting duplicate entries.

9

What is a "composite key"?

B

Correct Answer

A primary key consisting of two or more columns whose combined values uniquely identify a row

Explanation

A composite key combines multiple columns to form a unique identifier when no single column is sufficient to guarantee uniqueness.

10

What does "CASE WHEN condition THEN result ELSE other_result END" provide in a SELECT statement?

B

Correct Answer

Conditional logic within a query, returning different values per row based on specified conditions, similar to if/else

Explanation

The CASE expression allows row-level conditional logic directly in SQL queries, evaluating conditions in order and returning the corresponding result.

11

What is database normalization?

B

Correct Answer

The process of organizing tables and columns to minimize redundancy and dependency, typically by dividing data into related tables

Explanation

Normalization applies a series of rules (normal forms) to reduce data duplication and improve data integrity by structuring tables around well-defined relationships.

12

What is the difference between "DELETE", "TRUNCATE", and "DROP" for removing data from a table?

B

Correct Answer

DELETE removes rows (optionally with WHERE) and can be rolled back; TRUNCATE quickly removes all rows resetting identity counters with minimal logging; DROP removes the entire table structure

Explanation

DELETE is a row-by-row, logged operation supporting WHERE and rollback; TRUNCATE deallocates all data pages at once (faster, minimally logged) and resets auto-increment; DROP deletes the table definition entirely.

13

What does a window function with "OVER (PARTITION BY column)" do, e.g. "SUM(amount) OVER (PARTITION BY dept)"?

B

Correct Answer

It computes the aggregate (e.g. sum) across rows within each partition (group) while still returning a row for each individual record, unlike GROUP BY which collapses rows

Explanation

Window functions compute values across a set of related rows (the "window" or partition) without collapsing the result into one row per group, preserving the original row-level granularity.

14

What is the purpose of the "EXISTS" operator in a subquery?

B

Correct Answer

Returns TRUE if the subquery returns at least one row, often used for efficient existence checks

Explanation

EXISTS evaluates to true as soon as the subquery produces any row, often allowing the database to short-circuit and avoid scanning all rows, useful for correlated existence checks.

15

What is a "CTE" (Common Table Expression), defined with WITH?

B

Correct Answer

A named temporary result set defined within a query using WITH, which can be referenced like a table within that query, improving readability and enabling recursion

Explanation

A CTE, defined with "WITH name AS (SELECT ...)", creates a temporary named result set scoped to the enclosing query, useful for breaking complex queries into readable steps or writing recursive queries.

16

What does the "ON DELETE CASCADE" option on a foreign key do?

B

Correct Answer

Automatically deletes rows in the child table when the referenced row in the parent table is deleted

Explanation

ON DELETE CASCADE propagates deletions: removing a parent row automatically removes any child rows that reference it via the foreign key.

17

What is the difference between a clustered index and a non-clustered index?

B

Correct Answer

A clustered index determines the physical storage order of table rows (only one per table), while a non-clustered index is a separate structure that points back to the table data (multiple allowed)

Explanation

A clustered index defines the actual physical order of data rows in storage (a table can have only one), while non-clustered indexes maintain a separate sorted structure with pointers/references to the actual rows.

18

What does "GROUP BY" require regarding columns in the SELECT list (in standard SQL)?

B

Correct Answer

Every selected column must either be part of the GROUP BY clause or wrapped in an aggregate function

Explanation

In standard SQL, non-aggregated columns in the SELECT clause must appear in the GROUP BY clause; otherwise their value would be ambiguous across multiple rows in the same group.

19

What does "RIGHT JOIN" return that differs from "LEFT JOIN"?

B

Correct Answer

RIGHT JOIN returns all rows from the right table plus matching rows from the left, filling unmatched left-side columns with NULL — the mirror image of LEFT JOIN

Explanation

RIGHT JOIN preserves all rows from the right-hand table (with NULLs for non-matching left-side columns), the opposite orientation of a LEFT JOIN.

20

What is the effect of "SELECT ... FOR UPDATE" in a transaction?

B

Correct Answer

It locks the selected rows so other transactions cannot modify (and in some databases, read) them until the current transaction completes

Explanation

FOR UPDATE places a row-level lock on the selected rows, preventing concurrent transactions from modifying them until the lock is released, useful for preventing race conditions.

21

What does the "COALESCE(a, b, c)" function return?

B

Correct Answer

The first non-NULL value among a, b, and c

Explanation

COALESCE evaluates its arguments in order and returns the first one that is not NULL, often used to supply default values.

22

What is the difference between "WHERE" and "ON" clauses when used with JOINs?

B

Correct Answer

ON specifies the join condition that determines how rows from the two tables are matched, while WHERE filters the joined result afterward — this distinction matters especially for OUTER JOINs

Explanation

For OUTER JOINs, placing a condition in ON affects which rows are matched (and thus which produce NULLs), while the same condition in WHERE filters out rows after the join, potentially changing results.

23

What does "DENSE_RANK()" return differently from "RANK()" in a window function?

B

Correct Answer

RANK() leaves gaps in ranking numbers after ties (e.g. 1,2,2,4), while DENSE_RANK() assigns consecutive ranking numbers without gaps after ties (e.g. 1,2,2,3)

Explanation

Both assign the same rank to tied rows, but RANK() skips subsequent rank numbers proportional to the number of ties, while DENSE_RANK() continues with the next consecutive integer.

24

What is the purpose of "EXPLAIN" (or "EXPLAIN PLAN") before a query?

B

Correct Answer

It shows the execution plan the database engine would use to run the query, such as which indexes are used, helping with performance tuning

Explanation

EXPLAIN reveals how the database planner intends to execute a query (table scans vs index usage, join order, estimated costs), guiding optimization efforts.

25

What does a "self-referencing foreign key" typically model, e.g. an "employees" table with a "manager_id" column referencing "employees.id"?

B

Correct Answer

A hierarchical relationship within a single table, such as employees reporting to other employees

Explanation

A self-referencing foreign key allows rows in a table to reference other rows in the same table, commonly used to represent tree/hierarchy structures like org charts.

26

What does "INSERT INTO table (cols) SELECT cols FROM other_table" accomplish?

B

Correct Answer

It inserts rows into "table" using the results of a SELECT query from "other_table", copying data between tables

Explanation

INSERT ... SELECT populates a table directly from the result set of another query, useful for bulk copying or transforming data between tables.

27

What does "ANY" / "SOME" do when used with a comparison operator and a subquery, e.g. "WHERE salary > ANY (subquery)"?

B

Correct Answer

It returns true if salary is greater than at least one value returned by the subquery

Explanation

"> ANY (subquery)" is true if the comparison holds for at least one row returned by the subquery; "> ALL (subquery)" requires it to hold for every row.

28

What is the purpose of "GENERATED ALWAYS AS IDENTITY" (or AUTO_INCREMENT in MySQL)?

A

Correct Answer

To automatically generate a unique, sequential value for a column, commonly used for primary keys

Explanation

Identity/auto-increment columns automatically assign an incrementing numeric value on each insert, commonly used to generate surrogate primary keys.

29

What does the "CROSS JOIN" produce?

B

Correct Answer

The Cartesian product of two tables — every row from the first table combined with every row from the second

Explanation

CROSS JOIN returns all possible combinations of rows from the joined tables (rows_A × rows_B), with no join condition restricting the pairing.

30

What does "SELECT TOP 10 PERCENT * FROM table ORDER BY score DESC" (SQL Server syntax) accomplish?

B

Correct Answer

Returns the top 10% of rows (by row count) from the table, ordered by score descending

Explanation

TOP n PERCENT returns approximately that percentage of the total row count, here the highest-scoring 10% after sorting.

31

What is a "materialized view" and how does it differ from a regular view?

B

Correct Answer

A materialized view physically stores (caches) the query result on disk and must be refreshed periodically, while a regular view is computed on-the-fly each time it is queried

Explanation

Materialized views trade storage and freshness (requiring REFRESH) for faster read performance, since the result set is precomputed and stored rather than recalculated on each query.

32

What does the "LEAD()" / "LAG()" window functions do?

B

Correct Answer

They access the value of a column in a subsequent (LEAD) or preceding (LAG) row within the result set, relative to the current row

Explanation

LAG() and LEAD() let you reference values from other rows (previous or next, respectively, based on the specified ordering) without using a self-join.

33

What is the purpose of "CHECK" constraints?

B

Correct Answer

To enforce that values in a column satisfy a specific boolean condition before being accepted

Explanation

A CHECK constraint defines a condition that every row must satisfy, e.g. "CHECK (age >= 0)", rejecting inserts/updates that violate it.

34

What does "FULL OUTER JOIN" return?

B

Correct Answer

All rows from both tables, with NULLs filled in for non-matching columns on either side

Explanation

FULL OUTER JOIN combines LEFT and RIGHT JOIN behavior, returning all rows from both tables and filling unmatched columns with NULL.

35

What does "ROUND(123.456, 2)" return?

B

Correct Answer

123.46

Explanation

ROUND(value, decimals) rounds the number to the specified number of decimal places, here rounding 123.456 to 123.46.

36

What is the purpose of the "STRING_AGG" / "GROUP_CONCAT" function?

B

Correct Answer

To concatenate values from multiple rows within a group into a single delimited string

Explanation

STRING_AGG (PostgreSQL/SQL Server) or GROUP_CONCAT (MySQL) aggregates values from multiple rows into one string separated by a specified delimiter.

37

What does adding "WITH CHECK OPTION" to a view definition enforce?

B

Correct Answer

It ensures that any INSERT or UPDATE performed through the view must satisfy the view's WHERE condition, rejecting rows that would not appear in the view

Explanation

WITH CHECK OPTION prevents modifications through an updatable view from creating rows that fall outside the view's defining WHERE clause.

38

What is the effect of using a transaction with "SAVEPOINT"?

B

Correct Answer

It creates a named point within a transaction to which you can later roll back, without undoing the entire transaction

Explanation

SAVEPOINT marks an intermediate point in a transaction; ROLLBACK TO SAVEPOINT undoes only the changes made after that point, while keeping earlier changes within the transaction intact.

39

What does "CAST(column AS DECIMAL(10,2))" do?

B

Correct Answer

Converts the column's value to a decimal number with up to 10 total digits and 2 after the decimal point

Explanation

CAST converts a value to a specified data type; DECIMAL(10,2) defines fixed-point precision with 10 total significant digits and 2 after the decimal point.

40

What does the "OFFSET" clause do when combined with LIMIT, e.g. "LIMIT 10 OFFSET 20"?

B

Correct Answer

Skips the first 20 rows, then returns the next 10 rows, commonly used for pagination

Explanation

OFFSET skips a specified number of rows before starting to return rows, and LIMIT caps how many are returned — together implementing pagination (e.g. page 3 of 10 results per page).

1

What is the difference between the four standard transaction isolation levels (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE)?

B

Correct Answer

They progressively reduce concurrency anomalies (dirty reads, non-repeatable reads, phantom reads) at the cost of reduced concurrency, with SERIALIZABLE providing the strongest guarantees and READ UNCOMMITTED the weakest

Explanation

Each isolation level addresses progressively more concurrency anomalies: READ UNCOMMITTED allows dirty reads, READ COMMITTED prevents them but allows non-repeatable reads, REPEATABLE READ prevents those but allows phantoms, and SERIALIZABLE prevents all three at the cost of throughput.

2

What is a "deadlock" in a database, and how do most database systems handle it?

B

Correct Answer

A deadlock occurs when two or more transactions each hold locks the others need, forming a cycle of dependencies; most databases detect this and abort (roll back) one of the transactions to break the cycle

Explanation

A deadlock is a circular wait condition between transactions holding conflicting locks; database engines typically run a deadlock detector that picks a "victim" transaction to roll back, allowing the others to proceed.

3

What is the purpose of "query plan caching" and how can parameterized queries affect it?

B

Correct Answer

The database caches the execution plan for a query so repeated executions can reuse it, avoiding recompilation — though a plan optimized for one parameter set ("parameter sniffing") can be suboptimal for others

Explanation

Plan caching avoids the cost of re-parsing and re-optimizing identical query shapes, but "parameter sniffing" issues can arise when a plan compiled for atypical parameter values is reused for very different data distributions.

4

How does a recursive CTE (Common Table Expression) work, e.g. for traversing a hierarchy?

B

Correct Answer

It consists of an "anchor" member (base case) UNIONed with a "recursive" member that references the CTE itself, repeatedly executing until the recursive member returns no new rows

Explanation

A recursive CTE defines a base case and a recursive case combined with UNION (or UNION ALL); the database repeatedly evaluates the recursive part against the previous iteration's results until no new rows are produced, commonly used for hierarchical/tree data.

5

What is the difference between "covering index" and a regular index?

B

Correct Answer

A covering index includes all the columns needed to satisfy a query (in the index itself), allowing the database to answer the query without accessing the underlying table data ("index-only scan")

Explanation

When an index contains every column referenced by a query (via key columns and/or included columns), the database can satisfy the query entirely from the index, avoiding extra lookups to the table ("covering" the query).

6

What problem does "MVCC" (Multi-Version Concurrency Control), used by databases like PostgreSQL and MySQL InnoDB, solve?

B

Correct Answer

It allows readers to see a consistent snapshot of data without blocking writers (and vice versa) by maintaining multiple versions of rows, avoiding many lock contention issues

Explanation

MVCC keeps multiple row versions so that read operations can proceed against a consistent snapshot while writes create new versions, reducing the need for read locks and improving concurrency.

7

What does "SARGable" mean in the context of a WHERE clause predicate, and why does it matter for performance?

B

Correct Answer

A SARGable (Search ARGument-able) predicate is written in a form the optimizer can use with an index seek (e.g. "column = value"), whereas wrapping a column in a function (e.g. "YEAR(date_col) = 2024") often prevents index usage, forcing a full scan

Explanation

For an index to be used efficiently, the predicate generally must leave the indexed column unmodified on one side of the comparison; applying functions to the column (non-SARGable predicates) typically forces a full scan since the index is stored on the raw column values.

8

What is the purpose of "PARTITIONING" a large table (e.g. by date range)?

B

Correct Answer

It splits a large table into smaller physical pieces based on a partitioning key, allowing the database to scan only relevant partitions ("partition pruning") and easing maintenance tasks like archiving old data

Explanation

Table partitioning divides data into segments (e.g. by month), so queries filtering on the partition key can skip irrelevant partitions entirely, and maintenance operations (like dropping old data) can operate on whole partitions efficiently.

9

What is the "N+1 query problem" often encountered in application code using an ORM, and how does SQL help avoid it?

B

Correct Answer

It occurs when an application executes one query to fetch a list of N records, then executes N additional queries to fetch related data for each record individually — fixable by using a JOIN or a single batched query with IN/WHERE

Explanation

The N+1 problem causes excessive round trips to the database; rewriting the access pattern to use a JOIN or a single query with "WHERE id IN (...)" retrieves all needed data in one or few queries instead of N+1.

10

What is the difference between a "hash join", "merge join" (sort-merge join), and "nested loop join" as physical join strategies?

B

Correct Answer

They are different algorithms the optimizer may pick to execute the same logical join — nested loop suits small/indexed inputs, hash join builds an in-memory hash table for large unsorted inputs, and merge join exploits pre-sorted inputs

Explanation

These are physical implementation strategies the query optimizer chooses based on data size, sorting, and indexes available: nested loop suits small/indexed cases, hash join handles large unsorted datasets by hashing one side, and merge join is efficient when both inputs are already sorted on the join key.

11

What is "write-ahead logging" (WAL) and why is it important for durability?

B

Correct Answer

WAL requires that changes be recorded in a sequential log before being applied to the actual data files, so that after a crash the database can replay the log to recover committed transactions and undo uncommitted ones

Explanation

By writing changes to a durable log before modifying data pages, the database guarantees that committed transactions can be recovered (replayed from the log) even if a crash occurs before the data pages themselves were flushed to disk.

12

What is the difference between "optimistic locking" and "pessimistic locking" concurrency control strategies?

B

Correct Answer

Pessimistic locking acquires locks upfront to block other transactions, while optimistic locking allows concurrent access and checks for conflicts (e.g. via a version column) only at commit time, failing if one is detected

Explanation

Pessimistic locking trades concurrency for safety by locking resources before use; optimistic locking assumes conflicts are rare, allowing concurrent reads/writes but validating (often via a version/timestamp column) before committing, rejecting the transaction if the data changed underneath it.

13

What is a "lateral join" (or CROSS APPLY in SQL Server) used for?

B

Correct Answer

It allows a subquery on the right side of the join to reference columns from the left side's current row, enabling per-row correlated computations such as "top N per group"

Explanation

Unlike a normal join where both sides are evaluated independently, a LATERAL (or CROSS/OUTER APPLY) join lets the right-hand subquery reference columns from the left-hand row, enabling row-by-row correlated subqueries like fetching the top N related records per row.

14

What does "denormalization" trade off, and when might it be appropriate?

B

Correct Answer

Denormalization intentionally duplicates data across tables to reduce joins needed for reads, trading increased storage and more complex writes (to keep redundant data consistent) for faster reads — useful in read-heavy analytics

Explanation

Denormalization is a deliberate performance trade-off: duplicating or pre-aggregating data avoids costly joins on read-heavy paths at the cost of update complexity and storage, common in data warehouses and reporting systems.

15

What is a "phantom read" anomaly, and which isolation level is required to fully prevent it according to the SQL standard?

B

Correct Answer

A phantom read happens when a transaction re-runs a range query and finds new matching rows inserted by another transaction; the SQL standard requires SERIALIZABLE to fully prevent it (some databases prevent it at REPEATABLE READ too)

Explanation

Phantom reads involve new rows appearing in a repeated range query due to concurrent inserts; the ANSI SQL standard places full prevention at the SERIALIZABLE level, though implementations like PostgreSQL's snapshot-based REPEATABLE READ also prevent it via different mechanisms.

16

What is the purpose of "UPSERT" (e.g. "INSERT ... ON CONFLICT DO UPDATE" in PostgreSQL or "ON DUPLICATE KEY UPDATE" in MySQL)?

B

Correct Answer

It atomically inserts a new row, or updates the existing row if a conflicting unique/primary key already exists, avoiding race conditions from separate SELECT-then-INSERT/UPDATE logic

Explanation

UPSERT combines insert-or-update logic into a single atomic statement, avoiding the race condition where a separate "check if exists, then insert or update" sequence could fail under concurrent access.

17

What does "query plan parameter sniffing" mean in the context of stored procedures, and what issue can it cause?

B

Correct Answer

The optimizer generates and caches an execution plan based on the parameter values from the first execution; if later calls use very different values with different data distributions, the cached plan may be suboptimal for them

Explanation

Because the optimizer "sniffs" the first parameter values to build a plan it then caches and reuses, a plan well-suited for one parameter value (e.g. a very selective filter) may perform poorly for another (e.g. a filter matching most rows), a classic performance pitfall in parameterized stored procedures.

18

What is the difference between a "scalar subquery" and a "correlated subquery"?

B

Correct Answer

A scalar subquery returns a single value and can be evaluated independently of the outer query, while a correlated subquery references columns from the outer query and is conceptually re-evaluated for each row of the outer query

Explanation

A scalar subquery is self-contained and returns one value usable as an expression; a correlated subquery depends on the current row of the outer query (referencing its columns), conceptually executing once per outer row, though optimizers often rewrite these into joins for efficiency.

19

What does "GROUPING SETS", "CUBE", and "ROLLUP" extend GROUP BY to do?

B

Correct Answer

They allow computing multiple levels of aggregation in a single query — GROUPING SETS specifies arbitrary combinations of grouping columns, ROLLUP produces hierarchical subtotals, and CUBE produces all possible combinations (a full cross-tabulation)

Explanation

These GROUP BY extensions generate multiple grouping levels in one pass: ROLLUP produces hierarchical subtotals (e.g. by day, then by month, then grand total), CUBE produces every combination of the specified columns, and GROUPING SETS lets you specify exactly which combinations you want.

20

What is the practical significance of the difference between "NOT IN (subquery)" and "NOT EXISTS (correlated subquery)" when the subquery can return NULL values?

B

Correct Answer

If the NOT IN subquery returns any NULL, the entire comparison can evaluate to NULL (excluding all rows) due to three-valued logic, whereas NOT EXISTS is unaffected by NULLs, making it generally safer here

Explanation

Due to SQL's three-valued logic, "x NOT IN (1, NULL)" evaluates to NULL (not TRUE) for any x, causing the row to be excluded unexpectedly; NOT EXISTS avoids this pitfall since it only checks for row existence, not value equality against potentially-NULL values.