1Which of the following is a common flow control statement used to execute a block of code conditionally based on whether a condition is true?
flow control statements
Easy
A.IF...THEN...ELSE
B.DECLARE
C.FETCH
D.LOOP
Correct Answer: IF...THEN...ELSE
Explanation:
The IF...THEN...ELSE construct is a fundamental flow control statement that allows for the conditional execution of code. It checks a condition and runs a specific block of code if it's true, and an optional alternative block if it's false.
Incorrect! Try again.
2What is the primary characteristic of a database function?
functions
Easy
A.It cannot accept any parameters.
B.It must return a value.
C.It is used to automatically start a transaction.
D.It must modify data in at least one table.
Correct Answer: It must return a value.
Explanation:
A user-defined function is a reusable block of code that performs a specific task and is required to return a value (either a single scalar value or a table). This distinguishes it from a stored procedure, which does not have to return a value.
Incorrect! Try again.
3A pre-compiled collection of SQL statements stored in the database and executed as a single unit is known as a ____.
stored procedures
Easy
A.Stored Procedure
B.Cursor
C.View
D.Trigger
Correct Answer: Stored Procedure
Explanation:
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again. They are stored on the database server and can improve performance and reduce network traffic.
Incorrect! Try again.
4What is the main purpose of a database cursor?
cursors
Easy
A.To delete an entire table at once.
B.To create a temporary copy of the database.
C.To define user permissions.
D.To process the results of a query one row at a time.
Correct Answer: To process the results of a query one row at a time.
Explanation:
A cursor is a control structure that enables traversal over the records in a database. It acts as a pointer to a specific row within a result set, allowing you to process each row individually.
Incorrect! Try again.
5A special type of stored procedure that is executed automatically in response to a data modification event (like INSERT, UPDATE, or DELETE) is called a:
triggers
Easy
A.Trigger
B.Function
C.Cursor
D.Schedule
Correct Answer: Trigger
Explanation:
A trigger is a database object that is automatically executed ('fired') when a specific event occurs on a table or view. They are often used to maintain data integrity or enforce business rules.
Incorrect! Try again.
6In database programming languages like PL/SQL, what block is used to catch and handle errors that occur during the execution of code?
exception handling
Easy
A.The COMMIT block
B.The DECLARE block
C.The TRIGGER block
D.The EXCEPTION block
Correct Answer: The EXCEPTION block
Explanation:
The EXCEPTION block is specifically designed to catch and handle runtime errors. When an error occurs in the executable section (BEGIN...END), control is transferred to the EXCEPTION block to run error-handling code.
Incorrect! Try again.
7What is a transaction in a database?
transaction system concepts
Easy
A.A connection between a client and the server.
B.A logical unit of work composed of one or more SQL statements.
C.A backup of a single table.
D.A single SELECT statement.
Correct Answer: A logical unit of work composed of one or more SQL statements.
Explanation:
A transaction is a sequence of operations performed as a single logical unit of work. The entire sequence must either complete successfully or be fully rolled back to maintain database consistency.
Incorrect! Try again.
8In the ACID properties of a transaction, what does the 'A' stand for?
desirable properties of transactions
Easy
A.Authentication
B.Accuracy
C.Atomicity
D.Availability
Correct Answer: Atomicity
Explanation:
Atomicity ensures that a transaction is treated as an 'atomic' or indivisible unit. It either executes completely, or not at all. There is no partial execution.
Incorrect! Try again.
9In concurrency control, what does a 'schedule' represent?
schedules
Easy
A.A timeline for database maintenance.
B.A list of database users.
C.The order in which operations from concurrent transactions are executed.
D.A plan for adding new features to the DBMS.
Correct Answer: The order in which operations from concurrent transactions are executed.
Explanation:
A schedule (or history) is a sequence of operations from a set of concurrent transactions. It specifies the chronological order in which these operations are executed by the DBMS.
Incorrect! Try again.
10A schedule in which transactions are executed one after another, without any interleaving of operations, is known as a ____ schedule.
serializability of schedules
Easy
A.Cascading
B.Serial
C.Recoverable
D.Concurrent
Correct Answer: Serial
Explanation:
A serial schedule executes transactions sequentially, one at a time. This guarantees consistency but offers no concurrency. It is used as a benchmark to verify the correctness of concurrent schedules.
Incorrect! Try again.
11What is the primary goal of concurrency control in a DBMS?
concurrency control
Easy
A.To create more tables.
B.To manage simultaneous operations without causing data inconsistencies.
C.To perform regular backups of the database.
D.To speed up the network connection.
Correct Answer: To manage simultaneous operations without causing data inconsistencies.
Explanation:
Concurrency control is the process of managing simultaneous access to the database by multiple users or transactions to ensure that the data remains consistent and the integrity of the data is maintained.
Incorrect! Try again.
12Which SQL command is used to undo all the changes made by a transaction that has not yet been saved?
recoverability
Easy
A.UPDATE
B.SAVE
C.COMMIT
D.ROLLBACK
Correct Answer: ROLLBACK
Explanation:
The ROLLBACK command is used to discard all changes made during the current transaction, restoring the database to the state it was in before the transaction began.
Incorrect! Try again.
13Which ACID property ensures that once a transaction is committed, its effects are permanent, even if the system crashes afterward?
desirable properties of transactions
Easy
A.Durability
B.Isolation
C.Consistency
D.Atomicity
Correct Answer: Durability
Explanation:
Durability guarantees that the results of a committed transaction are permanently stored in the system. The changes must persist even in the case of a system failure.
Incorrect! Try again.
14Which SQL command is used to make all the changes in a transaction permanent?
transaction system concepts
Easy
A.BEGIN
B.ROLLBACK
C.COMMIT
D.SAVEPOINT
Correct Answer: COMMIT
Explanation:
The COMMIT command signals the successful completion of a transaction and instructs the DBMS to make all of its modifications permanent.
Incorrect! Try again.
15Which of the following is a key advantage of using stored procedures?
stored procedures
Easy
A.They can only be used for SELECT queries.
B.They increase the complexity of the client application code.
C.They can reduce network traffic between clients and the server.
D.They are stored on the client machine.
Correct Answer: They can reduce network traffic between clients and the server.
Explanation:
By executing code directly on the server, stored procedures eliminate the need to send individual SQL statements over the network, which can significantly reduce traffic and improve performance.
Incorrect! Try again.
16In a SQL query, where can a user-defined function that returns a single value typically be used?
functions
Easy
A.Only in a COMMIT statement
B.Only in a TRIGGER
C.In place of a column name in the SELECT list or in a WHERE clause
D.Only in the FROM clause
Correct Answer: In place of a column name in the SELECT list or in a WHERE clause
Explanation:
Scalar functions (which return a single value) are very flexible and can be used in expressions within a SQL statement, such as in the list of columns to be selected or as part of a condition in the WHERE clause.
Incorrect! Try again.
17After declaring and opening a cursor, which command is used to retrieve the next row from the result set?
cursors
Easy
A.NEXT
B.MOVE
C.GET
D.FETCH
Correct Answer: FETCH
Explanation:
The FETCH statement is used to retrieve a specific row from the result set pointed to by the cursor. Typically, it is used in a loop to iterate through all the rows.
Incorrect! Try again.
18A trigger can be configured to fire ____ or ____ a DML operation.
triggers
Easy
A.ONLY, NEVER
B.START, END
C.WITH, WITHOUT
D.BEFORE, AFTER
Correct Answer: BEFORE, AFTER
Explanation:
Triggers can be set to execute either immediately before the triggering event (like an INSERT) occurs or immediately after it has completed, allowing for different kinds of validation and logging.
Incorrect! Try again.
19The strategy of preventing other transactions from accessing a data item while a transaction is using it is known as:
concurrency control
Easy
A.Indexing
B.Locking
C.Normalization
D.Partitioning
Correct Answer: Locking
Explanation:
Locking is a fundamental mechanism for concurrency control. A transaction acquires a lock on a data item before accessing it, which can prevent other transactions from performing conflicting operations.
Incorrect! Try again.
20What is the purpose of a database log (or journal) in a transaction system?
recoverability
Easy
A.To keep a record of all changes made to the database for recovery purposes.
B.To store a backup copy of all tables.
C.To record user login and logout times.
D.To list all stored procedures and functions.
Correct Answer: To keep a record of all changes made to the database for recovery purposes.
Explanation:
The database log is a critical component for ensuring durability and recoverability. It records information about all transactions and their changes, allowing the system to undo failed transactions (ROLLBACK) or redo committed transactions after a crash.
Incorrect! Try again.
21An Audit table needs to log the old and new values of a product's price whenever the Products table is updated. The trigger should only execute its logging logic for rows where the price has actually changed. Which of the following is the most appropriate trigger implementation?
triggers
Medium
A.A BEFORE INSERT trigger on Products that compares the new price to a default value.
B.An AFTER UPDATE trigger on Products that checks IF NEW.price <> OLD.price for each row.
C.A STATEMENT level trigger that cannot access NEW and OLD values.
D.An AFTER UPDATE trigger on Products that logs all updated rows, regardless of which column changed.
Correct Answer: An AFTER UPDATE trigger on Products that checks IF NEW.price <> OLD.price for each row.
Explanation:
This scenario requires row-level processing to compare the state of a column before and after the update. An AFTER UPDATE FOR EACH ROW trigger is ideal. Inside the trigger, the NEW and OLD pseudo-records allow for comparing the updated price value with its original value, ensuring the logging action only occurs when necessary.
Incorrect! Try again.
22Consider the schedule S: R2(A); R1(B); W2(B); W1(A); C2; C1;. What can be concluded about its serializability?
serializability of schedules
Medium
A.It is conflict-serializable and equivalent to the serial schedule T1; T2.
B.It is conflict-serializable and equivalent to the serial schedule T2; T1.
C.It is not conflict-serializable.
D.It is a serial schedule.
Correct Answer: It is not conflict-serializable.
Explanation:
To check for conflict serializability, we draw a precedence graph. The conflicting operations are:
R1(B) and W2(B) -> This is a read-write conflict, creating an edge T1 -> T2.
R2(A) and W1(A) -> This is a read-write conflict, creating an edge T2 -> T1.
Since the precedence graph contains a cycle (T1 -> T2 -> T1), the schedule S is not conflict-serializable.
Incorrect! Try again.
23A transaction is following the Two-Phase Locking (2PL) protocol. It has acquired several shared and exclusive locks and has just issued its first UNLOCK command on a data item. What is the transaction allowed to do next according to the 2PL protocol?
concurrency control
Medium
A.It can acquire new shared locks but not exclusive locks.
B.It can continue to acquire and release locks freely until it commits.
C.It can only release existing locks but cannot acquire any new locks.
D.It can acquire new exclusive locks but not shared locks.
Correct Answer: It can only release existing locks but cannot acquire any new locks.
Explanation:
The Two-Phase Locking (2PL) protocol consists of a 'growing phase' and a 'shrinking phase'. During the growing phase, a transaction can acquire locks but cannot release any. Once the transaction releases its first lock, it enters the 'shrinking phase'. In this phase, it can only release locks and is not permitted to acquire any new ones. This rule ensures serializability.
Incorrect! Try again.
24A transaction transfers $100 from Account A to Account B. The operation involves two steps: debiting A, then crediting B. The system guarantees that if a power failure occurs after the debit but before the credit, the debit operation will be rolled back upon restart. Which ACID property does this guarantee primarily uphold?
desirable properties of transactions
Medium
A.Atomicity
B.Isolation
C.Durability
D.Consistency
Correct Answer: Atomicity
Explanation:
Atomicity ensures that all operations within a transaction are completed as a single, indivisible unit. Either all operations succeed, or none of them do. In this case, by rolling back the partial work (the debit), the system upholds atomicity, preventing the database from being in an inconsistent state where money is lost.
Incorrect! Try again.
25Which of the following scenarios is the best use case for a stored procedure over a user-defined function?
stored procedures
Medium
A.Calculating a complex mathematical value based on input parameters to be used in the WHERE clause of a SELECT statement.
B.Encapsulating a multi-step business process involving several INSERT, UPDATE, and DELETE statements that modifies the state of the database.
C.Returning a single, computed value (e.g., an employee's total sales) to be included as a column in a SELECT query.
D.Formatting a date value into a specific string format for display in a query result set.
Correct Answer: Encapsulating a multi-step business process involving several INSERT, UPDATE, and DELETE statements that modifies the state of the database.
Explanation:
Stored procedures are designed to execute a series of SQL statements, including DML (Data Manipulation Language) and DDL (Data Definition Language) operations. They excel at encapsulating complex business logic that modifies the database. Functions, especially those used within SELECT statements, are generally expected to be side-effect-free (not modify data) and return a single value or a table.
Incorrect! Try again.
26A developer writes a procedure using a cursor to iterate through all employees in a department and give a 10% raise to those with a salary below $50,000. What is the primary reason for using a cursor in this scenario?
cursors
Medium
A.To guarantee that the query will be executed faster than a set-based UPDATE.
B.To store the entire result set of the SELECT query in memory before processing.
C.To execute a single UPDATE statement that affects multiple rows more efficiently.
D.To process the result set on a row-by-row basis, allowing for conditional logic for each employee.
Correct Answer: To process the result set on a a row-by-row basis, allowing for conditional logic for each employee.
Explanation:
Cursors provide a mechanism to retrieve a result set from a query and process it one row at a time. This is necessary when complex, conditional logic needs to be applied to each individual row, which cannot be easily expressed in a single, set-based SQL statement. While a simple conditional update could be done with a WHERE clause, a cursor is chosen when the logic per row is more intricate.
Incorrect! Try again.
27Consider the schedule S: W1(A); R2(A); W1(B); C1; R2(C); C2;. Which property best describes this schedule?
recoverability
Medium
A.It is a strict schedule.
B.It is not recoverable.
C.It is recoverable, but not cascadeless.
D.It is cascadeless.
Correct Answer: It is recoverable, but not cascadeless.
Explanation:
In this schedule, T2 reads data item A which was written by T1 (W1(A); R2(A)).
Recoverability: A schedule is recoverable if a transaction Tj that reads from Ti commits only after Ti commits. Here, T2 reads from T1, and T2 commits (C2) after T1 commits (C1). So, the schedule is recoverable.
Cascadeless: A schedule is cascadeless if a transaction Tj is only allowed to read an item X after the transaction Ti that last wrote X has committed. Here, T2 reads A (R2(A)) before T1 commits (C1). This violates the condition for being cascadeless. If T1 were to abort, T2 would have to be rolled back, causing a cascade.
Incorrect! Try again.
28Analyze the following pseudo-code block:
sql
DECLARE v_count INT := 0;
BEGIN
SELECT COUNT(*) INTO v_count FROM employees WHERE department_id = 999; -- Assume dept 999 does not exist
v_count := v_count + 1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_count := -1;
WHEN OTHERS THEN
v_count := -99;
END;
-- What is the final value of v_count?
exception handling
Medium
A.1
B.-1
C.0
D.-99
Correct Answer: -1
Explanation:
In many SQL procedural languages (like PL/SQL), a SELECT ... INTO statement that finds no rows raises a NO_DATA_FOUND exception. The code execution immediately jumps to the EXCEPTION block. The line v_count := v_count + 1; is never reached. The WHEN NO_DATA_FOUND handler is matched, which sets v_count to -1. The WHEN OTHERS block is not executed as a more specific handler was found.
Incorrect! Try again.
29A database system runs two transactions concurrently. It ensures that the operations of one transaction are not visible to the other until the first one commits. From the perspective of the second transaction, the first transaction either has not happened at all, or it has completed fully. This behavior describes which ACID property?
desirable properties of transactions
Medium
A.Atomicity
B.Isolation
C.Consistency
D.Durability
Correct Answer: Isolation
Explanation:
Isolation is the property that ensures concurrent transactions do not interfere with each other's execution. It makes transactions appear as if they are running serially, one after another, even though they are executing concurrently. This prevents issues like dirty reads, non-repeatable reads, and phantom reads.
Incorrect! Try again.
30Examine the following SQL procedural logic:
sql
DECLARE counter INT := 1;
DECLARE result INT := 0;
WHILE counter <= 5 LOOP
IF counter MOD 2 = 0 THEN
result := result + counter;
END IF;
counter := counter + 1;
END LOOP;
-- What is the final value of 'result'?
flow control statements
Medium
A.15
B.5
C.9
D.6
Correct Answer: 6
Explanation:
The loop iterates with counter from 1 to 5. The IF statement checks if the counter is even (counter MOD 2 = 0).
When counter is 1, 3, 5 (odd), the condition is false.
When counter is 2, result becomes 0 + 2 = 2.
When counter is 4, result becomes 2 + 4 = 6.
The loop terminates when counter becomes 6. The final value of result is 6.
Incorrect! Try again.
31A developer needs a reusable piece of code that accepts an employee ID and returns the number of years they have been with the company. This value needs to be used directly within a SELECT statement to show employee details and their tenure. Why is a user-defined function (UDF) the most appropriate choice?
functions
Medium
A.Because functions can return a single scalar value that can be used in the column list of a SELECT statement.
B.Because functions can modify tables, which is needed to calculate tenure.
C.Because functions are the only way to perform calculations in a database.
D.Because functions are pre-compiled and always faster than stored procedures.
Correct Answer: Because functions can return a single scalar value that can be used in the column list of a SELECT statement.
Explanation:
User-defined functions are designed to encapsulate calculations and return values (either scalar or table-valued) that can be seamlessly integrated into SQL queries, such as in the SELECT list or WHERE clause. A stored procedure cannot be called in this manner. The primary advantage here is the function's ability to be used as part of a declarative SQL statement.
Incorrect! Try again.
32In a system using a timestamp-ordering protocol for concurrency control, two transactions T1 and T2 have timestamps TS(T1) = 20 and TS(T2) = 25. Suppose T2 issues a read(Q) operation, and later T1 issues a write(Q) operation. What will be the system's response to T1's write request?
concurrency control
Medium
A.Allow the write operation but roll back T2.
B.Reject the write operation and roll back T1.
C.Block T1 until T2 commits.
D.Allow the write operation to proceed normally.
Correct Answer: Reject the write operation and roll back T1.
Explanation:
The basic timestamp-ordering protocol aims to maintain a serializable order equivalent to the timestamp order. T1 has an older timestamp than T2. When T1 tries to write Q, the protocol checks the read-timestamp of Q, which is TS(T2) = 25. Since TS(T1) < read_TS(Q) (i.e., 20 < 25), it means an older transaction (T1) is trying to change a value that has already been read by a younger transaction (T2). This violates the serial order, so T1's write is rejected, and T1 is aborted.
Incorrect! Try again.
33A schedule is considered view-serializable if it is view-equivalent to some serial schedule. Which of the following conditions is NOT required for two schedules, S and S', to be view-equivalent?
serializability of schedules
Medium
A.For each data item Q, if transaction Ti reads the initial value of Q in S, it must also read the initial value of Q in S'.
B.For each data item Q, if Ti reads a value of Q written by Tj in S, it must also read the value of Q written by Tj in S'.
C.For each data item Q, the transaction that performs the final write on Q must be the same in both S and S'.
D.For every data item, the order of conflicting operations (read-write, write-read, write-write) must be the same in both S and S'.
Correct Answer: For every data item, the order of conflicting operations (read-write, write-read, write-write) must be the same in both S and S'.
Explanation:
This condition describes conflict-serializability, which is a stricter condition than view-serializability. View-equivalence is defined by three conditions: (1) Initial Reads, (2) Reads-From relationships, and (3) Final Writes. While a conflict-serializable schedule is always view-serializable, a view-serializable schedule is not necessarily conflict-serializable (e.g., in cases involving 'blind writes').
Incorrect! Try again.
34In a transaction processing system, what is the primary role of the 'log buffer'?
transaction system concepts
Medium
A.To temporarily store log records in main memory before they are written to stable storage.
B.To hold the 'before' images of data for rollback purposes only.
C.To permanently store all committed transaction data.
D.To cache frequently accessed data blocks from the disk to speed up queries.
Correct Answer: To temporarily store log records in main memory before they are written to stable storage.
Explanation:
Writing directly to stable storage (like a hard disk) for every log record is inefficient. The log buffer is an area in main memory where log records are temporarily collected. They are then written to the physical log on disk in batches, which is much more efficient. This process must still adhere to the write-ahead logging (WAL) protocol, ensuring logs are on stable storage before data is written.
Incorrect! Try again.
35Given the following schedule S: R1(A); R2(A); W2(B); C2; W1(B); C1;. What is the relationship between transaction T1's write to B and transaction T2's write to B?
schedules
Medium
A.There is no conflict because they commit in a different order.
B.It is a 'write-write' conflict.
C.It is a 'dirty read' because T1 reads uncommitted data from T2.
D.It is a 'lost update' because T2's update is overwritten by T1.
Correct Answer: It is a 'write-write' conflict.
Explanation:
A conflict occurs between two transactions if they access the same data item and at least one of the operations is a write. In this schedule, T2 writes to B (W2(B)) and T1 also writes to B (W1(B)). This is a classic write-write conflict. The term 'lost update' specifically refers to a scenario where one transaction's update is overwritten by another, which is a consequence of this unsynchronized write-write conflict.
Incorrect! Try again.
36A table Inventory has a quantity column. A developer needs to prevent this quantity from ever being updated to a negative value. Any attempt to do so should raise an error and fail the UPDATE statement. Which type of trigger is most suitable for this validation rule?
triggers
Medium
A.An AFTER UPDATE trigger that reverts the change if NEW.quantity is negative.
B.An INSTEAD OF UPDATE trigger on the table itself.
C.A BEFORE INSERT trigger to handle initial stock values.
D.A BEFORE UPDATE trigger that checks the NEW.quantity value.
Correct Answer: A BEFORE UPDATE trigger that checks the NEW.quantity value.
Explanation:
A BEFORE UPDATE trigger executes before the actual data modification occurs. This allows it to inspect the proposed new value (NEW.quantity) and, if the validation fails (the value is negative), it can raise an error to prevent the UPDATE operation from ever happening. Using an AFTER UPDATE trigger would be less efficient as it would allow the invalid update to occur and then require another operation to undo it.
Incorrect! Try again.
37Which of the following properties ensures that a system will not have to deal with cascading aborts?
recoverability
Medium
A.Atomic transactions
B.Serializable schedules
C.Cascadeless schedules
D.Recoverable schedules
Correct Answer: Cascadeless schedules
Explanation:
By definition, a cascadeless schedule is one where a transaction Tj is only allowed to read a data item X after the transaction Ti that last wrote to X has committed. This prevents Tj from reading 'dirty' (uncommitted) data from Ti. Therefore, if Ti aborts, Tj does not need to be rolled back, thus avoiding a cascading abort.
Incorrect! Try again.
38In a database system, a deadlock has occurred between four transactions, T1, T2, T3, and T4. The wait-for graph is T1 -> T2 -> T3 -> T4 -> T1. To break this deadlock, the system's deadlock detection algorithm decides to abort a transaction. Which transaction would be the most likely candidate for abortion based on common heuristics?
concurrency control
Medium
A.The transaction that is at the beginning of the cycle (T1).
B.A transaction chosen completely at random from the cycle.
C.The transaction that holds the most exclusive locks.
D.The transaction that has performed the least amount of work or is the 'youngest'.
Correct Answer: The transaction that has performed the least amount of work or is the 'youngest'.
Explanation:
When breaking a deadlock, database systems use heuristics to choose a 'victim' transaction to abort. The goal is to minimize the cost of the rollback. Common factors include how long the transaction has been running, how much CPU/IO it has consumed, how many data items it has updated, and how many locks it holds. Aborting a young transaction that has done little work is typically the most efficient choice.
Incorrect! Try again.
39What is a primary advantage of using stored procedures in a client-server database application regarding network traffic?
stored procedures
Medium
A.They increase network traffic because the procedure's source code is sent to the server for every execution.
B.They reduce network traffic by allowing the client to send a single call to execute multiple SQL statements on the server.
C.They have no impact on network traffic compared to executing individual SQL statements.
D.They encrypt all data sent over the network, which is their primary purpose.
Correct Answer: They reduce network traffic by allowing the client to send a single call to execute multiple SQL statements on the server.
Explanation:
Without stored procedures, a client application might need to send multiple individual SQL commands to the server to complete a single business transaction. This creates significant network latency. By encapsulating these commands into a single stored procedure, the client only needs to make one network round-trip: a call to execute the procedure with its parameters. The server then executes all the SQL internally, drastically reducing network traffic.
Incorrect! Try again.
40A developer needs to write a query that categorizes employees into 'Junior', 'Mid-level', and 'Senior' based on their years_of_service. Which SQL construct is most suitable for implementing this conditional logic directly within a SELECT statement?
flow control statements
Medium
A.A CASE statement
B.An IF-THEN-ELSE block
C.A WHILE loop
D.A GOTO statement
Correct Answer: A CASE statement
Explanation:
The CASE statement is the standard SQL construct for handling if/then/else logic within a query. It allows you to define conditions and return a corresponding value when a condition is met. For example: SELECT employee_name, CASE WHEN years_of_service > 10 THEN 'Senior' WHEN years_of_service > 4 THEN 'Mid-level' ELSE 'Junior' END AS experience_level FROM employees;. Other constructs like loops and IF blocks are part of procedural extensions (like PL/SQL or T-SQL) and cannot be used directly within a standard SELECT statement in this way.
Incorrect! Try again.
41Consider a table Employees with an AFTER UPDATE trigger that logs changes to an AuditLog table. Another table Departments has an AFTER UPDATE trigger that, when a department's budget is changed, updates the max_salary for all employees in that department via a stored procedure. What is the most likely outcome if a transaction updates a department's budget, causing the second trigger to fire and update multiple rows in Employees, which in turn fires the first trigger for each updated employee?
triggers
Hard
A.The transaction will likely succeed, with the Employees trigger firing for each row updated by the Departments trigger, creating multiple audit entries as expected.
B.The system will enter a deadlock state as the triggers on Employees and Departments attempt to acquire locks on each other's tables in a conflicting order.
C.The transaction will succeed, but the audit log will be inconsistent because triggers cannot see changes made by other triggers within the same statement.
D.The transaction will fail due to a "mutating table" error because the triggers create a circular dependency.
Correct Answer: The transaction will likely succeed, with the Employees trigger firing for each row updated by the Departments trigger, creating multiple audit entries as expected.
Explanation:
This scenario describes a valid cascading trigger. The Departments trigger fires once due to the initial update. This trigger's action is a DML statement that modifies multiple rows in the Employees table. The AFTER UPDATE trigger on Employees will then fire once for each row affected by that DML statement, correctly generating multiple audit log entries. This is a standard and supported behavior in most SQL databases. A "mutating table" error (common in Oracle) would typically occur if a row-level trigger on a table tried to query or modify the same table. Deadlock is possible in complex concurrent systems but is not the most direct or likely outcome of this specific trigger logic.
Incorrect! Try again.
42Consider the schedule S: . Which of the following statements accurately describes schedule S?
serializability of schedules
Hard
A.S is conflict serializable but not view serializable.
B.S is both conflict and view serializable.
C.S is view serializable but not conflict serializable.
D.S is neither conflict serializable nor view serializable.
Correct Answer: S is view serializable but not conflict serializable.
Explanation:
To check for conflict serializability, we build a precedence graph based on conflicting operations (R-W, W-R, W-W). The schedule contains the conflict , which implies an edge . It also contains the conflict , implying an edge . The resulting cycle means S is not conflict serializable.
To check for view serializability, we check if S is view-equivalent to any serial schedule. An equivalent schedule must satisfy three conditions: same initial reads, same updated reads, and same final writes.
Initial Read: reads the initial value of A.
Updated Reads: There are none.
Final Write: performs the final write on A.
Let's test the serial schedule .
In , reads the initial A. (Matches S)
There are no updated reads. (Matches S)
In , performs the final write. (Matches S)
Since S is view-equivalent to the serial schedule , it is view serializable. This is a classic example where a blind write () breaks conflict serializability but preserves view serializability.
Incorrect! Try again.
43A database system uses Multi-Version Concurrency Control (MVCC) and implements the REPEATABLE READ isolation level. A long-running transaction starts and reads a set of rows from the Products table where category = 'Electronics'. While is still running, another transaction commits after inserting a new row into Products with category = 'Electronics'. Afterwards, re-executes the exact sameSELECT query. What will observe?
concurrency control
Hard
A.The phantom row phenomenon; will see the new row inserted by .
B. will not see the new row, and no error will occur.
C. will block until no other transactions are modifying rows that could potentially match its query predicate.
D. will fail with a serialization error because its view of the data has been invalidated by 's commit.
Correct Answer: will not see the new row, and no error will occur.
Explanation:
In an MVCC system, REPEATABLE READ is typically implemented using snapshot isolation. When transaction begins, it is given a transaction ID which determines its view of the database—it can only see versions of data committed before its snapshot was taken. Because inserted and committed its new row after started, the new row is not part of 's snapshot. When re-executes its query, it reads from the exact same snapshot, so it will not see the new row. This effectively prevents phantom reads in this common MVCC implementation, even though the SQL standard for REPEATABLE READ allows them. The transaction does not fail or block; it simply operates on its consistent, isolated view of the data.
Incorrect! Try again.
44Analyze the schedule S: . How would you classify this schedule based on the properties of recoverability, cascadelessness, and strictness?
recoverability
Hard
A.It is a strict schedule (and therefore also cascadeless and recoverable).
B.It is recoverable, but neither cascadeless nor strict.
C.It is recoverable and cascadeless, but not strict.
D.It is cascadeless, but not recoverable.
Correct Answer: It is a strict schedule (and therefore also cascadeless and recoverable).
Explanation:
Let's analyze the properties in order of strictness:
Strict: A schedule is strict if no data item is read or written by a transaction until the last transaction that wrote to it has committed or aborted. In S, writes to A and then commits. Only after commits does read A and later write to A. Both the read and the write by happen after has committed. Therefore, the schedule is strict.
Cascadeless: A schedule is cascadeless if reads are only performed on data written by committed transactions (i.e., no dirty reads). Since the schedule is strict, it is by definition also cascadeless. reads A after commits, so no dirty read occurs.
Recoverable: A schedule is recoverable if transactions commit only after all transactions from which they read have committed. Since the schedule is cascadeless, it is also recoverable.
Because the schedule meets the conditions for being strict, it also meets the less-stringent requirements for being cascadeless and recoverable.
Incorrect! Try again.
45A stored procedure sp_process_order is defined with EXECUTE AS CALLER (or SQL SECURITY INVOKER). An administrative user with high privileges executes a script that grants EXECUTE permission on this procedure to a low-privilege user, web_user. The procedure contains a statement to UPDATE the Invoices table. The web_user has SELECT permission on Invoices but not UPDATE. What happens when web_user executes sp_process_order?
stored procedures
Hard
A.The procedure fails during compilation/resolution because the system detects that the caller, web_user, lacks the required UPDATE permission before execution begins.
B.The procedure executes successfully, as the grant of EXECUTE permission implicitly confers the necessary underlying table permissions for the duration of the procedure's execution.
C.The procedure executes successfully because permissions are checked against the procedure's owner (the administrator), not the caller.
D.The procedure fails due to a permissions error on the UPDATE statement, because the procedure runs with the permissions of the web_user.
Correct Answer: The procedure fails due to a permissions error on the UPDATE statement, because the procedure runs with the permissions of the web_user.
Explanation:
The security context clause EXECUTE AS CALLER (in SQL Server) or SQL SECURITY INVOKER (in standard SQL) is critical. This clause specifies that the procedure must execute using the privilege set of the user who calls it, not the user who defined or owns it. In this case, web_user is the caller. Although web_user has permission to execute the procedure itself, the statements inside the procedure are subject to web_user's permissions. Since web_user lacks UPDATE permission on the Invoices table, the UPDATE statement will fail with a permission-denied error at runtime. If the procedure had been defined with EXECUTE AS OWNER or SQL SECURITY DEFINER, the permissions of the definer would be used, and the operation would likely succeed.
Incorrect! Try again.
46You declare a KEYSET-driven cursor on a query that selects 100 employees based on their salary. After opening the cursor, but before you have fetched all 100 rows, another transaction performs two actions and commits: (1) it UPDATEs the salary of an employee who is already in your cursor's keyset, changing a non-key column, and (2) it DELETEs a different employee who was also in your cursor's keyset. What is the behavior of the cursor when you try to fetch these two affected rows?
cursors
Hard
A.The updated row will reflect the new salary value, and the deleted row will simply be skipped by the cursor without any status change.
B.Both the updated and deleted rows will be visible in the cursor as they were when the cursor was opened, showing a static snapshot.
C.The entire cursor will be invalidated and raise an error upon the next FETCH operation due to the external modifications.
D.The updated row will reflect the new salary value, but an attempt to fetch the deleted row will return a status indicating the row is missing.
Correct Answer: The updated row will reflect the new salary value, but an attempt to fetch the deleted row will return a status indicating the row is missing.
Explanation:
KEYSET-driven cursors work by creating a static set of unique keys for all rows that match the initial query. This 'keyset' is fixed for the life of the cursor.
For Updates: When you fetch a row, the database uses the stored key to look up the latest data values in the base tables. Therefore, updates to non-key columns of rows within the keyset are visible to the cursor. The fetch will return the new salary.
For Deletes: When you attempt to fetch a row whose key is in the keyset but has been deleted from the base table, the database lookup fails. The system reports this failure, typically by setting a status variable (like @@FETCH_STATUS = -2 in T-SQL) to indicate that the row is missing.
This behavior is a hybrid of STATIC (which wouldn't see the update) and DYNAMIC (which might also see new rows).
Incorrect! Try again.
47Consider a stored procedure in a PL/SQL-like language with a transaction.
sql
BEGIN -- Transaction starts
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
BEGIN
-- Inner block with exception handler
UPDATE accounts SET balance = balance + 100 WHERE id = 999; -- Fails, account 999 does not exist
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO error_log (message) VALUES ('Account not found');
END;
UPDATE products SET stock = stock - 1 WHERE id = 5;
COMMIT;
Assuming account id = 999 does not exist and the UPDATE (or a SELECT ... INTO in PL/SQL that would cause this error) fails, raising a NO_DATA_FOUND exception, what is the final state of the database after the procedure completes?
exception handling
Hard
A.The entire transaction is rolled back. No changes are committed, and nothing is logged.
B.The first UPDATE on accounts is rolled back, the error is logged, and the UPDATE on products is committed.
C.The procedure execution stops after the exception is handled, so the UPDATE on products is never executed, but the first UPDATE and the log entry are committed.
D.The first UPDATE on accounts and the UPDATE on products are both committed, and the error is logged. The failed UPDATE is ignored.
Correct Answer: The first UPDATE on accounts and the UPDATE on products are both committed, and the error is logged. The failed UPDATE is ignored.
Explanation:
The key concept here is that a handled exception does not automatically abort the entire transaction. The EXCEPTION block within the inner BEGIN...END scope catches the NO_DATA_FOUND error.
The execution of the failing UPDATE is halted.
Control is transferred to the EXCEPTION block, which successfully inserts a message into error_log.
Since the exception is now considered 'handled', the program flow continues normally after the inner block's END; statement.
The UPDATE on the products table is executed.
The final COMMIT statement is reached, which makes all successful modifications within the transaction's scope permanent: the first accounts update, the error_log insert, and the products update.
Incorrect! Try again.
48A database uses a strict two-phase locking (Strict 2PL) protocol. Transaction acquires a shared lock on data item A, reads it, then requests an exclusive lock on data item B. Concurrently, transaction holds an exclusive lock on B, writes to it, and then requests a shared lock on A. What situation has occurred, and what is the typical resolution mechanism?
concurrency control
Hard
A.Inconsistent analysis; this scenario is prevented by the ordered locking phase of the 2PL protocol.
B.Starvation; one transaction will never be granted the lock it needs due to a continuous stream of other transactions.
C.Livelock; the system will continuously abort and restart one of the transactions.
D.Deadlock; the system will resolve it by aborting one of the transactions based on a victim selection algorithm.
Correct Answer: Deadlock; the system will resolve it by aborting one of the transactions based on a victim selection algorithm.
Explanation:
This is a textbook deadlock scenario. We have a circular wait condition:
holds a lock on A and is waiting for a lock on B.
holds a lock on B and is waiting for a lock on A.
This creates a cycle in the waits-for graph (), which is the definition of a deadlock. Neither transaction can proceed. Strict 2PL ensures serializability and recoverability if transactions complete, but it does not prevent deadlocks. Database systems that use locking must employ a deadlock management strategy. The most common is deadlock detection (periodically checking the waits-for graph for cycles) and resolution, which involves choosing a 'victim' transaction (e.g., based on age, log space used, or priority) to abort and roll back. This releases its locks, breaking the cycle and allowing the other transaction to proceed.
Incorrect! Try again.
49In the context of distributed databases, the CAP theorem states a system can only provide two of Consistency, Availability, and Partition Tolerance. If a banking system must guarantee that a funds transfer between two accounts, residing on different network partitions, never results in money being created or destroyed even during a network failure, which two properties of the CAP theorem is it prioritizing, and what ACID property is this most closely related to?
desirable properties of transactions
Hard
A.Prioritizing Partition Tolerance and a relaxed form of Consistency; most related to Atomicity.
B.Prioritizing Consistency and Availability (CA); most related to Isolation.
C.Prioritizing Availability and Partition Tolerance (AP); most related to Durability.
D.Prioritizing Consistency and Partition Tolerance (CP); most related to Consistency and Atomicity.
Correct Answer: Prioritizing Consistency and Partition Tolerance (CP); most related to Consistency and Atomicity.
Explanation:
A network failure is a partition ('P'). The requirement that money is never created or destroyed is a strict consistency ('C') guarantee. To ensure this guarantee in the face of a partition, the system must sacrifice availability ('A'). For example, it might return an error or block the transfer operation until the partition is resolved, rather than proceeding and risking an inconsistent state. This makes it a CP (Consistency/Partition Tolerance) system. This strict transactional guarantee maps directly to the ACID properties of Atomicity (the transfer must happen completely or not at all) and Consistency (the database invariant that the total sum of money is preserved is never violated).
Incorrect! Try again.
50You have a view v_employee_dept that joins Employees and Departments tables. You define an INSTEAD OF INSERT trigger on this view. The trigger's logic correctly separates the new data and inserts it into the base Employees and Departments tables. The Employees table has a NOT NULL constraint on the department_id column, which is a foreign key to Departments. What happens if a user tries to INSERT a row into the view for a new employee in a new department, and the trigger's code inserts into the Employees table before inserting into the Departments table?
triggers
Hard
A.The insert into Employees is temporarily held in a pending state until the Departments insert is complete, at which point both are committed.
B.The trigger fails and the entire operation is rolled back due to a foreign key constraint violation.
C.The INSTEAD OF trigger bypasses base table constraints, so the insert succeeds, but leaves the data in an inconsistent state.
D.The insert succeeds because constraint checking is deferred until the end of the trigger's execution.
Correct Answer: The trigger fails and the entire operation is rolled back due to a foreign key constraint violation.
Explanation:
INSTEAD OF triggers replace the action on the view with their own code, but they do not bypass the integrity constraints (like foreign keys, checks, not null) of the underlying base tables. When the trigger code attempts to execute INSERT into the Employees table first, the database engine will immediately check the constraints on Employees. Since the new department_id does not yet exist in the Departments table, the foreign key constraint will be violated. This violation causes the INSERT statement to fail, which in turn halts the trigger and rolls back the entire operation.
Incorrect! Try again.
51A user-defined function get_stock_level(product_id) queries an Inventory table to return the current stock for a product. You then create a computed column in the Products table defined as stock AS get_stock_level(product_id). Why will a database system (like SQL Server) prevent you from creating an index on this computed column, even if it is marked as PERSISTED, unless another specific option is used during the function's creation?
functions
Hard
A.The function returns a numeric data type, which cannot be indexed when it is part of a computed column.
B.An index cannot be created on any computed column that references another table, regardless of how it is done.
C.The function is not schema-bound, meaning the underlying Inventory table could be altered in a way that invalidates the function's logic.
D.Functions that perform data access are considered non-deterministic by default, and indexes can only be created on deterministic outputs.
Correct Answer: The function is not schema-bound, meaning the underlying Inventory table could be altered in a way that invalidates the function's logic.
Explanation:
For a database to build and trust an index on a computed column that uses a function, it needs a guarantee that the function will always return the same output for the same input, and that the function's underlying dependencies will not change. This guarantee is provided by creating the function with the SCHEMABINDING option. Schema binding locks the referenced objects (like the Inventory table) from being dropped or modified in ways that would affect the function's signature or behavior. Without SCHEMABINDING, the database cannot ensure the integrity of the persisted index values over time, and therefore prohibits the creation of the index. While non-determinism (option A) is a related concern, SCHEMABINDING is the direct and mandatory requirement for indexing functions that access user data.
Incorrect! Try again.
52In a T-SQL stored procedure, you have a WHILE loop processing rows. Inside the loop, a BEGIN TRY...BEGIN CATCH block handles potential errors for a DML operation. After the TRY...CATCH block, you check @@ROWCOUNT to decide if the loop should terminate.
sql
WHILE (1=1)
BEGIN
BEGIN TRY
-- Attempt a DML operation that might fail or affect 0 rows
UPDATE Top100Customers SET processed = 1 WHERE processed = 0;
END TRY
BEGIN CATCH
-- Log error, but allow loop to continue
INSERT INTO dbo.ErrorLog (msg) VALUES (ERROR_MESSAGE());
END CATCH
-- Check if the UPDATE did anything
IF @@ROWCOUNT = 0
BREAK; -- Exit loop
END
What is the critical flaw in this loop's termination logic?
flow control statements
Hard
A.The BREAK statement inside the IF is out of scope and will cause a syntax error.
B.A deadlock will occur if the ErrorLog table is frequently locked by other processes.
C.The WHILE (1=1) loop will never terminate because @@ROWCOUNT is always reset to 1 by the BEGIN TRY statement.
D.If an error occurs, @@ROWCOUNT will reflect the row count of the INSERT into ErrorLog, not the UPDATE, leading to incorrect behavior.
Correct Answer: If an error occurs, @@ROWCOUNT will reflect the row count of the INSERT into ErrorLog, not the UPDATE, leading to incorrect behavior.
Explanation:
The @@ROWCOUNT variable in T-SQL is volatile; it is reset by almost every statement, including control-of-flow statements in some cases. If the UPDATE in the TRY block fails, control jumps to the CATCH block. The INSERT into ErrorLog is executed. This INSERT statement will set @@ROWCOUNT to 1 (the number of rows inserted into the log). The code then continues to the IF @@ROWCOUNT = 0 check. Since @@ROWCOUNT is now 1, the condition is false, and the loop will not BREAK. It will continue to run, attempting the same failing UPDATE indefinitely, creating an infinite loop that fills the error log. The correct approach is to save the value of @@ROWCOUNT into a local variable immediately after the DML statement inside the TRY block.
Incorrect! Try again.
53Analyze schedule S: . Which statement correctly describes the serializability of this schedule?
serializability of schedules
Hard
A.The schedule is not view serializable and not conflict serializable.
B.The schedule is view serializable but not conflict serializable.
C.The schedule is conflict serializable.
D.The schedule is recoverable but not view serializable.
Correct Answer: The schedule is not view serializable and not conflict serializable.
Explanation:
Conflict Serializability: We build a precedence graph. The first conflicts with and , which creates a dependency . Later, the operations of (specifically ) conflict with the second , which creates a dependency . The existence of the cycle means the schedule is not conflict serializable.
View Serializability: We check if it is view-equivalent to any serial schedule ( or ).
In S, reads the value of A written by the first operation of . Therefore, any equivalent serial schedule must have appear before .
In S, the final write on data item A is performed by the second operation of . Therefore, any equivalent serial schedule must have as the last transaction.
These two conditions are contradictory: must be before , but it must also be after . It is impossible to construct a serial schedule that is view-equivalent to S. Therefore, the schedule is not view serializable.
Incorrect! Try again.
54Consider the schedule S: . Transaction performs a 'blind write'. Which property does this schedule primarily violate, and what is the potential consequence?
recoverability
Hard
A.It violates the cascadeless property, leading to a potential for cascading aborts.
B.It is not a recoverable schedule because a committed transaction () has read data from an aborted transaction.
C.It is not a recoverable schedule, which can lead to the effects of an aborted transaction being incorrectly persisted.
D.It violates the strict property, requiring complex recovery logic for before-images.
Correct Answer: It is not a recoverable schedule, which can lead to the effects of an aborted transaction being incorrectly persisted.
Explanation:
This schedule is unrecoverable. Here's why: writes to A. Then overwrites that value. Then aborts. When aborts, the recovery manager must roll back its changes by restoring the before-image of A (the value A had before wrote to it). However, has already overwritten A and subsequently committed. If the system restores the before-image for , it will wipe out the committed update from , thus violating the durability of . This makes a correct rollback of impossible without violating the commit of . This is a classic unrecoverable situation. Option D is incorrect because no transaction reads from the aborted transaction; the conflict is a Write-Write conflict.
Incorrect! Try again.
55In a database system using Timestamp Ordering (TO) protocol, transaction with timestamp issues a read(A). Later, transaction with timestamp issues a write(A). Finally, transaction with issues a read(A). Let the initial Read-Timestamp and Write-Timestamp of A be and . What is the outcome for the three transactions?
concurrency control
Hard
A.All three transactions succeed.
B. succeeds, but is aborted for violating the read timestamp of A, and is subsequently also aborted.
C. succeeds, but and are aborted.
D. and succeed, but is aborted because its timestamp is smaller than the Write-Timestamp of A.
Correct Answer: and succeed, but is aborted because its timestamp is smaller than the Write-Timestamp of A.
Explanation:
We trace the operations and timestamps on data item A:
issues read(A): . The basic TO rule for read is check if . Since , the read is permitted. The system updates .
issues write(A): . The basic TO rule for write is check if and . Since and , the write is permitted. The system updates .
issues read(A): . The system checks if . The condition is false. This means , an 'older' transaction, is trying to read a data item that has already been overwritten by a 'younger' transaction (). To prevent producing a non-serializable schedule, the protocol requires that be aborted and rolled back.
Incorrect! Try again.
56A transaction enters the ACTIVE state, performs several reads and writes, and then issues a COMMIT command. The system successfully writes the commit record to the transaction log on stable storage, but before it can flush all the modified data blocks from its buffer cache to disk, a system crash occurs. After the system restarts, what is the state of this transaction and how will the recovery manager handle it?
transaction system concepts
Hard
A.The transaction is in a PARTIALLY COMMITTED state, and the system must UNDO its changes to ensure atomicity.
B.The transaction is considered ACTIVE and will be rolled back because the end-of-transaction marker was not found in the data files.
C.The transaction is considered ABORTED, because the data was not physically written to disk, and it will be UNDONE.
D.The transaction is considered COMMITTED, and its changes will be REDONE from the log to ensure durability.
Correct Answer: The transaction is considered COMMITTED, and its changes will be REDONE from the log to ensure durability.
Explanation:
The critical event that moves a transaction to the COMMITTED state is the successful writing of its 'commit' record to the stable log. This is the point of no return. The principle of write-ahead logging (WAL) ensures this log record is written before the commit is acknowledged. When the system restarts, the recovery process (like ARIES) will scan the log. It will find the COMMIT record for this transaction, classifying it as a 'winner'. During the REDO phase of recovery, the manager will replay the log records for this transaction, reapplying all its changes to the data on disk to ensure they are present. This guarantees the Durability property of ACID, even if the buffer cache was not flushed before the crash.
Incorrect! Try again.
57A stored procedure sp_A calls another stored procedure sp_B. sp_A starts a transaction, calls sp_B, does more work, and then commits. sp_B also contains BEGIN TRANSACTION and COMMIT statements. In a system like SQL Server, what is the effect of the COMMIT TRANSACTION statement inside the nested procedure sp_B?
sql
-- Procedure B
CREATE PROCEDURE sp_B AS
BEGIN
BEGIN TRANSACTION;
UPDATE T2 SET col = 2;
COMMIT TRANSACTION; -- What does this do?
END;
-- Procedure A
CREATE PROCEDURE sp_A AS
BEGIN
BEGIN TRANSACTION;
EXEC sp_B;
UPDATE T1 SET col = 1;
COMMIT TRANSACTION;
END;
stored procedures
Hard
A.It only decrements an internal transaction counter (@@TRANCOUNT); the actual commit happens only at the end of sp_A.
B.It causes a runtime error because nested COMMIT statements are not permitted.
C.It commits the update to T2 immediately, making it a separate, autonomous transaction.
D.It releases locks acquired by sp_B but does not make the changes to T2 durable.
Correct Answer: It only decrements an internal transaction counter (@@TRANCOUNT); the actual commit happens only at the end of sp_A.
Explanation:
In SQL Server's default model, transactions can be nested, but they are not truly independent. The system maintains a transaction counter, @@TRANCOUNT. The first BEGIN TRANSACTION (in sp_A) starts the real transaction and increments @@TRANCOUNT from 0 to 1. The nested BEGIN TRANSACTION in sp_B simply increments it to 2. Conversely, the COMMIT TRANSACTION in sp_B only decrements @@TRANCOUNT from 2 back to 1. It does not perform a physical commit. The transaction is only physically committed to the database when the outermost COMMIT is executed (in sp_A), which decrements @@TRANCOUNT from 1 to 0. Therefore, all work done in sp_A and sp_B is part of a single atomic transaction.
Incorrect! Try again.
58Analyze the following schedule and identify all the classic concurrency problems it exhibits:
(Result is 500)
(Result is 600)
schedules
Hard
A.Dirty Read and Phantom Read.
B.Non-Repeatable Read only.
C.Phantom Read only.
D.Phantom Read and Non-Repeatable Read.
Correct Answer: Phantom Read only.
Explanation:
Let's analyze the types of concurrency problems:
Dirty Read: A transaction reads data written by another transaction that has not yet committed. only re-reads after has committed. No dirty read occurs.
Non-Repeatable Read: A transaction re-reads the same set of rows and finds that some rows have been updated or deleted. This schedule does not modify or delete any existing rows that has already seen.
Phantom Read: A transaction re-executes a query with a search condition (a WHERE clause) and finds that additional rows now satisfy the condition because another transaction has inserted them. This is exactly what happens here. 's first query reads a set of rows matching category='A'. inserts a new row that also matches this condition. When runs the exact same query again, a new 'phantom' row appears, changing the result of the aggregate function. This is the definition of a phantom read.
Incorrect! Try again.
59In a system where query performance is critical, a developer uses a scalar user-defined function (UDF) in the WHERE clause of a query that runs against a table with millions of rows. For example: SELECT * FROM Orders WHERE dbo.IsHighValue(order_total) = 1;. Even though dbo.IsHighValue contains simple logic and an index exists on the order_total column, the query performs very poorly. What is the most likely reason for this performance degradation?
functions
Hard
A.The use of a scalar UDF in the WHERE clause makes the predicate non-SARGable, preventing the query optimizer from using an index seek.
B.The UDF cannot be parallelized, forcing the entire multi-million row query to run on a single processor core.
C.The UDF causes the transaction isolation level to be implicitly escalated to SERIALIZABLE, leading to increased locking and blocking.
D.The function introduces excessive CPU overhead for each row, which outweighs the benefit of the index.
Correct Answer: The use of a scalar UDF in the WHERE clause makes the predicate non-SARGable, preventing the query optimizer from using an index seek.
Explanation:
This is a major performance anti-pattern in many RDBMSs. The query optimizer treats a scalar UDF as a 'black box'. It cannot determine its cost or how it affects the data. This prevents the optimizer from using column statistics to estimate how many rows will be returned and, most importantly, it makes the WHERE clause predicate non-SARGable (not a Search ARGument). A non-SARGable predicate cannot be satisfied with an efficient index seek operation. Instead, the optimizer is forced to generate a plan that performs a full table (or index) scan, retrieving every single row and executing the function on each one to see if it matches. This row-by-row execution is vastly less efficient than a targeted index seek, leading to extremely poor performance on large tables.
Incorrect! Try again.
60Which of the following statements most accurately describes the fundamental relationship between conflict serializability and view serializability?
serializability of schedules
Hard
A.The set of conflict serializable schedules is a proper subset of the set of view serializable schedules.
B.The sets of conflict serializable and view serializable schedules are disjoint.
C.The set of view serializable schedules is a proper subset of the set of conflict serializable schedules.
D.The sets of conflict serializable and view serializable schedules are identical.
Correct Answer: The set of conflict serializable schedules is a proper subset of the set of view serializable schedules.
Explanation:
Conflict serializability is a stricter, more conservative condition than view serializability. Every schedule that is conflict serializable is, by definition, also view serializable. This is because being conflict-equivalent to a serial schedule implies that all reads, writes, and their dependencies are ordered in the same way, which satisfies the conditions for view-equivalence. However, the reverse is not true. There are schedules that are view serializable but not conflict serializable. These schedules typically involve 'blind writes' (a write to a data item without first reading it), which can create a cycle in the conflict precedence graph (making it not conflict serializable) while still being equivalent to a serial schedule from the perspective of what each transaction reads and what the final state is. Therefore, the set of all conflict serializable schedules is a proper (i.e., non-equal) subset of the larger set of all view serializable schedules.