Bird
Raised Fist0
Interview Prepdatabase-management-systemsmediumGoogleAmazonFlipkartCRED

Hash Index vs B+ Tree Index - Range Queries & Equality Lookups

Choose your preparation mode3 modes available
▶
Steps
setup

Initialize B+ Tree Structure

The B+ Tree is initialized with order 3 and keys inserted: 10, 20, 30, 40, 50, 60, 70. The tree structure is balanced with internal and leaf nodes.

💡 Setting up the tree structure is essential to visualize how keys are organized and how the tree guides searches.
Line:bptree = BPlusTree(order=3) bptree.insert(10) bptree.insert(20) ...
💡 The tree is balanced with internal nodes directing searches and leaf nodes containing keys in sorted order.
📊
Hash Index vs B+ Tree Index - Range Queries & Equality Lookups - Watch the Algorithm Execute, Step by Step
Watching this visualization helps you understand the structural advantages of B+ Trees for range queries compared to hash indexes, by seeing exactly how keys are located and how leaf nodes are scanned sequentially.
Step 1/10
·Active fill★Answer cell
search
3050
1020
leaf
3040
leaf
506070
leaf
Initial B+ Tree constructed with keys 10,20,30,40,50,60,70
searchKey: 25
3050
1020
leaf
3040
leaf
506070
leaf
At root, key 25 < 30, so descend to child node 2
searchKey: 25
3050
1020
leaf
3040
leaf
506070
leaf
Descended to leaf node 2 to locate key 25
searchKey: 25
3050
1020
leaf
3040
leaf
506070
leaf
Key 25 not found in leaf 2; start scanning after key 20
traverseKey: 25
3050
1020
leaf
3040
leaf
506070
leaf
Moved to leaf node 3 to start scanning keys >= 25
traverseKey: 30
3050
1020
leaf
3040
leaf
506070
leaf
Scanned keys 30 and 40 in leaf node 3, both within range
traverseKey: 40
3050
1020
leaf
3040
leaf
506070
leaf
Moved to leaf node 4 to continue scanning keys in range
traverseKey: 50
3050
1020
leaf
3040
leaf
506070
leaf
Scanned keys 50 and 60 in leaf node 4; stopped at key 70 outside range
traverse
3050
1020
leaf
3040
leaf
506070
leaf
Range scan complete; keys 30, 40, 50, 60 returned

Key Takeaways

✓ B+ Trees efficiently support range queries by linking leaf nodes for sequential scans.

This is hard to see from code alone because the linkage and sequential scanning are structural properties best understood visually.

✓ Internal nodes guide searches by directing to the correct child based on key comparisons.

Visualizing the active path clarifies how the tree narrows down the search space step-by-step.

✓ Range scans stop early when keys exceed the upper bound, avoiding unnecessary reads.

Seeing the scan stop at the right key helps understand the efficiency of B+ Tree range queries.

Practice

(1/5)
1. You have a SQL query with multiple clauses: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, and LIMIT. To correctly process the query and produce the expected result, which approach best models the order in which these clauses are logically executed by the database engine?
easy
A. Execute clauses in the written order from top to bottom as they appear in the query.
B. Execute clauses in the logical order: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT.
C. Execute all filtering clauses first (WHERE and HAVING), then grouping, then selection, ignoring FROM order.
D. Execute SELECT first to identify columns, then FROM to get tables, then apply filters and limits.

Solution

  1. Step 1: Understand SQL logical execution order

    SQL does not execute clauses in the written order. Instead, it first identifies data sources (FROM), then filters rows (WHERE), groups rows (GROUP BY), filters groups (HAVING), selects columns (SELECT), orders results (ORDER BY), and finally limits output rows (LIMIT).
  2. Step 2: Match problem description to logical execution order

    The logical order ensures correct filtering and grouping before selection and ordering, which matches Execute clauses in the logical order: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT exactly.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Logical execution order matches database engine processing [OK]
Hint: SQL executes clauses logically, not in written order [OK]
Common Mistakes:
  • Assuming SQL executes clauses top-to-bottom as written
2. Consider the following Python code simulating SQL query execution order using linked nodes. What is the exact output when executing the query plan starting from the FROM clause node?
class QueryPlanNode:
    def __init__(self, name):
        self.name = name
        self.next = None
    def set_next(self, node):
        self.next = node
    def execute(self):
        print(f"Executing {self.name} clause")
        if self.next:
            self.next.execute()

from_clause = QueryPlanNode('FROM')
where_clause = QueryPlanNode('WHERE')
group_by_clause = QueryPlanNode('GROUP BY')
having_clause = QueryPlanNode('HAVING')
select_clause = QueryPlanNode('SELECT')
order_by_clause = QueryPlanNode('ORDER BY')
limit_clause = QueryPlanNode('LIMIT')

from_clause.set_next(where_clause)
where_clause.set_next(group_by_clause)
group_by_clause.set_next(having_clause)
having_clause.set_next(select_clause)
select_clause.set_next(order_by_clause)
order_by_clause.set_next(limit_clause)

from_clause.execute()
easy
A. Executing FROM clause Executing WHERE clause Executing GROUP BY clause Executing HAVING clause Executing SELECT clause Executing ORDER BY clause Executing LIMIT clause
B. Executing SELECT clause Executing FROM clause Executing WHERE clause Executing GROUP BY clause Executing HAVING clause Executing ORDER BY clause Executing LIMIT clause
C. Executing FROM clause Executing SELECT clause Executing WHERE clause Executing GROUP BY clause Executing HAVING clause Executing ORDER BY clause Executing LIMIT clause
D. Executing FROM clause Executing WHERE clause Executing HAVING clause Executing GROUP BY clause Executing SELECT clause Executing ORDER BY clause Executing LIMIT clause

Solution

  1. Step 1: Trace execution starting from FROM node

    The execute() method prints the current node's clause name, then recursively calls execute() on the next node if it exists. The chain is FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT.
  2. Step 2: Confirm output order matches linked nodes

    Each clause prints in the linked order, so output lines are exactly the clauses in the chain order.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Output matches linked list traversal order [OK]
Hint: Linked nodes print clauses in linked order [OK]
Common Mistakes:
  • Confusing printed order with written SQL order
3. Which of the following statements about the Atomicity property of ACID is INCORRECT?
medium
A. Atomicity guarantees that either all operations of a transaction are applied or none are.
B. Atomicity ensures that once a transaction starts, it cannot be interrupted by other transactions.
C. Atomicity helps prevent partial updates that could leave the database in an inconsistent state.
D. Atomicity is typically implemented using mechanisms like write-ahead logging and rollback.

Solution

  1. Step 1: Recall Atomicity meaning

    Atomicity means all-or-nothing execution of a transaction.
  2. Step 2: Analyze each option

    A is correct; C is correct as partial updates violate atomicity; D is correct as logging and rollback implement atomicity.
  3. B is incorrect because Atomicity does not prevent interruption by other transactions; that is Isolation's role.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Atomicity is about completeness, not concurrency control.
Hint: Atomicity = all-or-nothing, not about concurrency
Common Mistakes:
  • Confusing Atomicity with Isolation
  • Assuming Atomicity controls transaction scheduling
4. Which of the following statements about cost estimation in query optimization is TRUE regarding its limitations?
medium
A. Cost estimation always accurately predicts query execution time because it uses precise statistics
B. Cost estimation is unnecessary if the query uses indexes
C. Cost estimation ignores CPU costs and focuses only on I/O costs
D. Cost estimation can be inaccurate due to outdated statistics or assumptions about data distribution

Solution

  1. Step 1: Understand cost estimation limitations

    Cost estimation relies on statistics that may be stale or incomplete, leading to inaccuracies.
  2. Step 2: Analyze each option

    Cost estimation always accurately predicts query execution time because it uses precise statistics: Cost estimation is heuristic, not always precise.
    Cost estimation can be inaccurate due to outdated statistics or assumptions about data distribution: Correct--statistics can be outdated or assumptions invalid.
    Cost estimation ignores CPU costs and focuses only on I/O costs: Cost models consider CPU, I/O, and sometimes network.
    Cost estimation is unnecessary if the query uses indexes: Index usage reduces cost but estimation is still needed.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Cost estimation is an approximation influenced by statistics quality.
Hint: Cost estimation is only as good as the statistics and assumptions it uses.
Common Mistakes:
  • Believing cost estimation is perfectly accurate
  • Thinking cost models ignore CPU costs
  • Assuming indexes remove the need for cost estimation
5. Identify the bug in the following Python code that attempts to find customers with orders using a JOIN simulation:
medium
A. Line 3: The return statement should remove duplicates explicitly with DISTINCT.
B. Line 2: The list comprehension incorrectly filters customers by order IDs instead of customer IDs.
C. Line 1: Using a list instead of a set for order_customer_ids causes duplicates and slower lookups.
D. Line 1: The variable name order_customer_ids is misleading and should be order_ids.

Solution

  1. Step 1: Analyze data structure used for order_customer_ids

    Using a list causes O(m) lookup per customer, leading to O(n*m) time and duplicates.
  2. Step 2: Identify impact on performance and correctness

    Using a set enables O(1) lookups and avoids duplicates, improving performance and correctness.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Replacing list with set fixes performance and duplicate issues [OK]
Hint: Sets provide O(1) membership checks, lists do not [OK]
Common Mistakes:
  • Using list instead of set for membership
  • Confusing customer_id with order_id
  • Assuming duplicates are handled automatically
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard