
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































D191: Advanced Data Management Prep with Detailed Rationales Course Code: D Course Name: Advanced Data Management Topic: SQL Programming Query Optimization Indexing Trigger Execution Practice Academic Year: 2026/
In database schema design, when applying a foreign key constraint with an ON DELETE CASCADE clause between the orders and order_items tables, what happens to child records when a parent record is deleted? A. The deletion is blocked and throws a foreign key violation error. B. The foreign key column in order_items is automatically updated to NULL. C. All corresponding child rows in order_items are automatically deleted. D. A background cron job is scheduled to purge matching rows in order_items. CORRECT ANSWER: C RATIONALE: The ON DELETE CASCADE referential integrity action specifies that when a row in the parent table (orders) is deleted, PostgreSQL automatically removes all referenced child rows in the child table (order_items). Option A describes the default RESTRICT or NO ACTION behavior. Option B describes ON DELETE SET NULL. Option D is incorrect because CASCADE automates this process natively inside the database transaction without requiring background jobs or external scripting.
When performing query performance tuning in PostgreSQL, evaluating an execution plan generated by EXPLAIN ANALYZE provides critical feedback. Which metric is exclusively provided by EXPLAIN ANALYZE that is missing from a standard EXPLAIN query?
A. Estimated cost range for startup and total plan completion. B. Estimated total number of output rows. C. Actual execution time in milliseconds and actual row counts. D. Tree structure of join operators and scan types. CORRECT ANSWER: C RATIONALE: Standard EXPLAIN shows the query planner's estimates (cost, rows, width) based on database statistics without executing the query. EXPLAIN ANALYZE actually executes the query, capturing real-world metrics including actual execution time in milliseconds and actual row counts per node. Option A, B, and D are present in standard EXPLAIN.
A database administrator needs to optimize frequent range queries on a date column (order_date) in a table containing 10 million rows. Which type of indexing strategy utilizes a balanced tree structure suited for B-Tree index comparison operators like <, <=, =, >=, and >? A. Hash Index B. B-Tree Index C. GIN (Generalized Inverted Index) D. BRIN (Block Range Index) CORRECT ANSWER: B RATIONALE: The B-Tree Index is the default index type in PostgreSQL and is self-balancing. It keeps data sorted, making it ideal for range queries (<, <=, =, >=, >), pattern matching with prefix matches, and sorting operations (ORDER BY). Option A (Hash) only supports equality (=). Option C (GIN) is designed for composite/multivalue items like JSONB or array types. Option D (BRIN) is best for very large, naturally ordered tables where data pages map to min/max values, but B-Tree is the standard robust balanced tree structure for general range queries.
In PostgreSQL PL/pgSQL development, a database developer creates an AFTER INSERT OR UPDATE trigger on the inventory table. Inside the trigger function, which
During query optimization, the database query engine evaluates join algorithms. Which join mechanism, known as a Hash Join , builds an in-memory hash table on the smaller relation and scans the larger relation to find matches? A. Nested Loop Join B. Hash Join C. Merge Join D. Bitmap Index Scan CORRECT ANSWER: B RATIONALE: A Hash Join loads all matching rows from the smaller table (the build phase) into an in-memory hash table using a hash key, then reads the larger table (the probe phase) to check for matching keys. Option A (Nested Loop) iterates over every row of the outer table and searches the inner table. Option C (Merge Join) requires both inputs to be sorted on the join key beforehand. Option D is an index scanning strategy, not a join algorithm.
In SQL transaction processing, which ACID property ensures that once a database transaction is committed, its modifications persist permanently even in the event of a system power failure? A. Atomicity B. Consistency C. Isolation D. Durability CORRECT ANSWER: D RATIONALE: Durability guarantees that once a transaction commits, its changes are written to non-volatile storage (such as write-ahead logs / WAL) and survive any subsequent crash or power loss. Atomicity ensures all-or-nothing execution. Consistency ensures data meets all schema rules and constraints. Isolation prevents concurrent transactions from interfering with each other.
When designing an analytics data mart, a database architect creates a Materialized View to store the precomputed results of an expensive multi-table join. What statement must be executed to refresh the underlying data in a Materialized View? A. UPDATE VIEW summary_sales; B. REFRESH MATERIALIZED VIEW summary_sales; C. ALTER VIEW summary_sales REBUILD; D. REINDEX VIEW summary_sales; CORRECT ANSWER: B RATIONALE: Materialized views persist query results physically on disk. Because the underlying data changes over time, executing REFRESH MATERIALIZED VIEW summary_sales; is required to re-run the view's query and update the stored dataset. UPDATE VIEW and ALTER VIEW REBUILD are invalid SQL syntax for updating materialized datasets.
To assign a unique sequential integer to rows within a partition without gaps or duplicates, which SQL window function should be utilized? A. RANK() B. DENSE_RANK() C. ROW_NUMBER() D. NTILE() CORRECT ANSWER: C RATIONALE: ROW_NUMBER() assigns a unique, sequential integer to each row within a partition, regardless of tied values. RANK() leaves gaps in ranking numbers when ties occur. DENSE_RANK() does not leave gaps upon ties, but tied rows receive identical rank numbers. NTILE() divides rows into a specified number of ranked buckets.
RATIONALE: The GRANT statement is a core DCL command used to grant specific access privileges (such as SELECT, INSERT, UPDATE) to database users or roles. REVOKE removes permissions. COMMIT is a Transaction Control Language (TCL) command. ASSIGN is not a standard SQL DCL command.
When evaluating query performance, a developer notices that a query filters on LOWER(email) = '[email protected]'. Why does a standard B-Tree index on email fail to speed up this query, requiring an expression index? A. Standard B-Tree indexes cannot index character string columns. B. Function calls on indexed columns prevent standard index lookup matching. C. Lowercase functions force the planner into a Hash Join. D. Expression indexes are required for all WHERE clauses in PostgreSQL. CORRECT ANSWER: B RATIONALE: Applying a function like LOWER() to a column transforms the key values dynamically; the standard index stores raw column values, so the optimizer cannot match transformed search criteria and falls back to a full table scan. Creating an expression index on CREATE INDEX idx_email_lower ON users (LOWER(email)) stores pre-computed lowercase values, enabling index lookup.
Which PostgreSQL PL/pgSQL control structure allows a developer to iterate over the rows returned by a query dynamic record set? A. LOOP ... EXIT B. FOR record_var IN query LOOP ... END LOOP;
C. WHILE EXISTS(query) LOOP ... END LOOP; D. IF FETCH NEXT THEN ... END IF; CORRECT ANSWER: B RATIONALE: The syntax FOR record_var IN query LOOP ... END LOOP; automatically opens an implicit cursor, iterates through every row of the target query, assigns each row to record_var, and cleans up upon completion.
Refer to the visual query execution pipeline flow above. At which stage does the engine transform an Abstract Syntax Tree into the most cost-effective execution plan using database statistics? A. Query Parser B. Query Optimizer / Planner C. Query Rewriter D. Execution Engine CORRECT ANSWER: B RATIONALE: The Query Optimizer / Planner takes the parsed and rewritten syntax tree, analyzes schema statistics (like table size, histogram distribution, and index existence), estimates execution costs (CPU/IO), and outputs the optimal execution plan for the Execution Engine.
What type of PostgreSQL index is explicitly optimized for indexing multi-valued data structures, such as full-text search vectors and JSONB documents? A. B-Tree Index B. GIN (Generalized Inverted Index) C. Hash Index D. Clustered Index CORRECT ANSWER: B
When analyzing database performance using EXPLAIN ANALYZE, what does a Seq Scan operator indicate? A. The engine is traversing a B-Tree index to locate matching records. B. The engine is sequentially reading all disk blocks of a table from start to end. C. The engine is performing a temporary sorting operation in RAM. D. The engine is fetching rows from an external foreign data wrapper. CORRECT ANSWER: B RATIONALE: A Seq Scan (Sequential Scan) reads every block of the table sequentially from beginning to end. While efficient for small tables or queries fetching a large percentage of total rows, it can cause severe IO bottlenecks on large tables requiring targeted lookups.
Which PostgreSQL procedure keyword allows a PL/pgSQL function or procedure to execute operations under a nested autonomous transaction context using explicit block boundaries? A. BEGIN TRANSACTION B. EXCEPTION C. DECLARE AUTONOMOUS D. SAVEPOINT CORRECT ANSWER: B RATIONALE: In PL/pgSQL, adding an EXCEPTION block to a function or procedure creates a subtransaction wrapper. If an error occurs within the block, changes inside that block are rolled back while surrounding execution context can recover. Standard transaction boundary statements like COMMIT or SAVEPOINT manage explicit transactional control points.
To combine the results of two SELECT queries into a single result set while automatically eliminating duplicate rows , which set operator must be used? A. UNION ALL B. UNION C. INTERSECT ALL D. EXCEPT CORRECT ANSWER: B RATIONALE: The UNION set operator merges the outputs of two queries and performs an implicit deduplication step. Conversely, UNION ALL retains all rows including duplicate records.
A database table logs accumulates millions of rows monthly. What partitioning method creates child tables based on explicit value ranges, such as date ranges? A. Hash Partitioning B. List Partitioning C. Range Partitioning D. Round-Robin Partitioning CORRECT ANSWER: C RATIONALE: Range Partitioning assigns table rows to child partitions defined by continuous, non-overlapping key ranges (e.g., FOR VALUES FROM ('2026- 01 - 01') TO ('2026- 02 - 01')), optimizing query pruning for date-based analytical filters.
What is the primary operational difference between a stored procedure and a user- defined function (UDF) in PostgreSQL? A. Functions can commit transactions, whereas procedures cannot. B. Procedures can perform transaction control (COMMIT/ROLLBACK), whereas functions cannot.
RATIONALE: LAG() provides access to data from a preceding row at a given physical offset within the window partition, facilitating period-over-period delta calculations. LEAD() looks ahead to subsequent rows.
When executing an UPDATE statement in PostgreSQL, how does the engine's Multi- Version Concurrency Control (MVCC) handle the target row under the hood? A. It overwrites the disk memory blocks of the old row directly in place. B. It soft-deletes the original tuple and inserts a new tuple with updated values. C. It moves the updated row to a temporary system rollback segment. D. It places an exclusive schema lock on the entire database table. CORRECT ANSWER: B RATIONALE: Under MVCC , PostgreSQL treats an update as a two-step operation: the existing tuple is marked as dead (setting its header expiration transaction ID xmax), and a new version (tuple) with updated column values is inserted into the table page. Dead tuples are later cleaned up by the VACUUM process.
What database maintenance process reclaims physical disk space occupied by dead tuples generated by MVCC UPDATE and DELETE operations? A. REINDEX B. VACUUM C. TRUNCATE D. ANALYZE CORRECT ANSWER: B RATIONALE: The VACUUM command removes dead tuples from table pages and marks space available for future row insertions. VACUUM FULL physically compacts tables to yield free space back to the operating system file system.
In PostgreSQL, what event timing must be declared when building a trigger designed to modify input values before they are validated and saved to disk? A. AFTER B. BEFORE C. INSTEAD OF D. DEFERRED CORRECT ANSWER: B RATIONALE: A BEFORE trigger fires before the database attempts to validate constraints and execute the requested operation. Inside a BEFORE row trigger, modifying fields on the NEW record alters the data that gets physically written.
Which PostgreSQL view type allows defining INSTEAD OF triggers to enable direct DML modifications on non-updatable complex views? A. Materialized Views B. Standard Views C. System Views D. Temporary Views CORRECT ANSWER: B RATIONALE: Standard Views support INSTEAD OF triggers for INSERT, UPDATE, and DELETE events. When DML is issued against the view, the trigger intercepts the command and executes custom logic on the underlying physical base tables.
When optimizing complex relational schemas, what type of dependency occurs when a non-key column determines another non-key column, violating 3NF? A. Partial Dependency B. Transitive Dependency
D. Disables table-level locking completely to eliminate deadlocks. CORRECT ANSWER: C RATIONALE: SERIALIZABLE is the strictest transaction isolation level. It prevents dirty reads, non-repeatable reads, phantom reads, and serialization anomalies, ensuring concurrent transaction outcomes match a purely sequential execution order.
In SQL aggregation, what clause must be used instead of WHERE to filter query output based on aggregate function results? A. ORDER BY B. GROUP BY C. HAVING D. QUALIFY CORRECT ANSWER: C RATIONALE: The HAVING clause filters grouped records after aggregate values are calculated by GROUP BY. The WHERE clause filters individual predicate rows before aggregation occurs.
In query optimization, what occurs during a Bitmap Heap Scan in a PostgreSQL execution plan? A. The engine scans all physical table heap pages sequentially without indexes. B. The engine uses a bitmap created by an index scan to retrieve matching physical table blocks. C. The engine creates a temporary B-Tree index on disk to sort non-indexed columns. D. The engine checks transaction log entries to verify committed tuple status. CORRECT ANSWER: B RATIONALE: A Bitmap Heap Scan reads data pages identified by a prior Bitmap Index Scan. The index scan constructs an in-memory bit array of table physical block
locations containing matching tuples; the heap scan then visits those target blocks efficiently in physical disk order.
Which feature allows creating an index on a specific subset of rows defined by a WHERE predicate , saving index maintenance costs and memory space? A. Covered Index B. Expression Index C. Partial Index D. Composite Index CORRECT ANSWER: C RATIONALE: A Partial Index includes only rows that satisfy a specified conditional clause (e.g., CREATE INDEX idx_active ON users (id) WHERE status = 'ACTIVE';). This reduces index storage size and maintenance overhead during non-matching row updates.
What SQL clause is used to handle situations where an INSERT statement violates a primary key or unique constraint by executing an alternative action like updating the existing row in PostgreSQL? A. ON CONFLICT DO UPDATE B. ON CONFLICT DO UPDATE / DO NOTHING C. MERGE INTO ... MATCHED D. EXCEPT ON DUPLICATE CORRECT ANSWER: B RATIONALE: PostgreSQL supports upsert operations using ON CONFLICT (conflict_target) DO UPDATE (or DO NOTHING). It intercepts unique constraint collisions during insertion and smoothly updates or ignores target records without failing the transaction.
A. Nested Loop Join B. Hash Join C. Merge Join D. Index Scan Join CORRECT ANSWER: C RATIONALE: A Merge Join is extremely fast when input datasets are already sorted on the join key. It reads both inputs simultaneously in linear scan fashion, matching rows without requiring in-memory hashing or nested iterations.
Which clause is added to a PostgreSQL CREATE INDEX command to include additional non-key payload columns for index-only scans without adding them to the index search tree? A. WITH B. INCLUDE C. COVERING D. ATTACH CORRECT ANSWER: B RATIONALE: The INCLUDE clause (e.g., CREATE INDEX idx_test ON table(col1) INCLUDE (col2);) stores extra payload columns in the leaf pages of an index. This allows index-only scans for queries fetching col1 and col2, without expanding the index B-Tree search keys.
When developing ETL workflows, what type of database schema design places a central fact table surrounded by unnormalized dimension tables connected directly via foreign keys? A. Snowflake Schema B. Star Schema C. Normalized 3NF Schema
D. Entity-Attribute-Value (EAV) Schema CORRECT ANSWER: B RATIONALE: A Star Schema features a central numeric fact table surrounded by denormalized dimension tables directly linked via foreign keys, optimizing analytical OLAP query aggregation performance.
In OLAP systems, what distinguishes a Snowflake Schema from a Star Schema? A. Fact tables are fully denormalized into single flat files. B. Dimension tables are normalized into multiple sub-dimension tables. C. Dimensions link directly to outer views without key constraints. D. It relies entirely on unstructured JSON storage. CORRECT ANSWER: B RATIONALE: In a Snowflake Schema , dimension tables are normalized into multiple related sub-dimension tables (e.g., separating product into subcategory and category), reducing redundancy at the cost of additional join operations.
What system catalog view in PostgreSQL can be queried to inspect execution statistics and column data distribution details used by the Query Planner? A. pg_tables B. pg_stats C. pg_indexes D. pg_locks CORRECT ANSWER: B RATIONALE: The pg_stats catalog view exposes detailed data distribution statistics (such as null fractions, average field widths, distinct values, and most common values) collected by ANALYZE, which the planner uses to estimate query costs.