πŸŽ“ Velnov

πŸ—„οΈ SQL Β· Topic 19 of 20

Views, Indexes & Transactions β€” SQL Questions with Answers

30 practice questions on Views, Indexes & Transactions, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.

0 easy Β· 13 medium Β· 17 hard Β· Part of SQL: Databases from basics to window functions - 20 topics.

Key concepts in this topic

VIEWVirtual tableAbstractionMaterialized viewCachingIndexPerformanceTrade-offsIndex strategyComposite indexLeftmost prefixCovering indexIndex-only scanEXPLAINQuery planTable scanTransactionBEGIN/COMMITACIDTransactionsROLLBACKSAVEPOINTIsolationConcurrency

Jump to: Medium Β· Hard

Medium questions (13)

Q1. medium

What is a VIEW?

CREATE VIEW active_customers AS
SELECT * FROM customers WHERE active = 1;
  1. A A saved query that acts like a virtual table - it stores no data itself
  2. B A copy of a table
  3. C An index
  4. D A backup

Answer: A β€” A saved query that acts like a virtual table - it stores no data itself

CREATE VIEW names a query. Selecting from the view runs the underlying query. Views simplify complex logic and provide a stable interface even if base tables change.

VIEWVirtual table

Q2. medium

What is a key benefit of using views?

  1. A They hide complexity and restrict access - users query a simple view instead of complex joins or sensitive columns
  2. B They always speed up queries
  3. C They store data twice
  4. D They replace indexes

Answer: A β€” They hide complexity and restrict access - users query a simple view instead of complex joins or sensitive columns

Views encapsulate complicated joins and can expose only certain columns/rows (security). Consumers get a clean, stable interface without knowing the underlying structure.

VIEWAbstraction

Q4. medium

What is an INDEX?

CREATE INDEX idx_email ON customers(email);
  1. A A data structure that speeds up row lookups on one or more columns
  2. B A sorted copy of the table
  3. C A view
  4. D A constraint

Answer: A β€” A data structure that speeds up row lookups on one or more columns

Like a book's index, it lets the database jump to matching rows instead of scanning every row. The trade-off is extra storage and slightly slower writes.

IndexPerformance

Q6. medium

Which columns benefit most from an index?

  1. A Columns used in WHERE, JOIN and ORDER BY - especially foreign keys and frequently searched fields
  2. B Every column
  3. C Only text columns
  4. D Columns never queried

Answer: A β€” Columns used in WHERE, JOIN and ORDER BY - especially foreign keys and frequently searched fields

Index the columns your queries filter and join on. A column that is never in a WHERE/JOIN/ORDER BY gains nothing from an index and just slows writes.

Index strategy

Q9. medium

What does EXPLAIN (or EXPLAIN ANALYZE) show?

EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 5;
  1. A The query execution plan - how the database will run the query, including index use and join methods
  2. B The query result
  3. C The table structure
  4. D Syntax errors

Answer: A β€” The query execution plan - how the database will run the query, including index use and join methods

EXPLAIN reveals whether a query uses indexes or does full scans, its join order, and estimated costs. It is the primary tool for diagnosing slow queries.

EXPLAINQuery plan

Q11. medium

What is a transaction?

BEGIN;
UPDATE accounts SET bal = bal - 100 WHERE id = 1;
UPDATE accounts SET bal = bal + 100 WHERE id = 2;
COMMIT;
  1. A A group of statements executed as a single all-or-nothing unit
  2. B A single SELECT
  3. C A backup
  4. D An index rebuild

Answer: A β€” A group of statements executed as a single all-or-nothing unit

BEGIN starts it; COMMIT makes all changes permanent; ROLLBACK undoes them. Either every statement succeeds or none do - essential for operations like money transfers.

TransactionBEGIN/COMMIT

Q13. medium

What does ROLLBACK do?

  1. A Undoes all changes made since the transaction began
  2. B Saves the changes
  3. C Deletes the table
  4. D Creates a backup

Answer: A β€” Undoes all changes made since the transaction began

If an error occurs mid-transaction, ROLLBACK reverts everything to the pre-transaction state, preserving consistency. COMMIT is the opposite - it finalises the changes.

ROLLBACKTransactions

Q19. medium

Why must a money transfer use a transaction?

  1. A So the debit and credit both succeed or both fail - never one without the other
  2. B For speed
  3. C To use an index
  4. D It does not need one

Answer: A β€” So the debit and credit both succeed or both fail - never one without the other

If the debit succeeds but the credit fails without a transaction, money vanishes. Atomicity guarantees the pair is all-or-nothing - the textbook example of why transactions exist.

AtomicityTransactions

Q20. medium

Does a VIEW improve performance by storing results?

  1. A No - a regular view re-runs its query each time; only a MATERIALIZED view stores results
  2. B Yes, always
  3. C It stores half the results
  4. D Views cannot be queried

Answer: A β€” No - a regular view re-runs its query each time; only a MATERIALIZED view stores results

Regular views are purely a naming/abstraction convenience and add no caching. For stored results you need a materialized view (with periodic refresh).

VIEWMaterialized view

Q22. medium

What is a UNIQUE index?

  1. A An index that also enforces uniqueness - no two rows may share the indexed value
  2. B The fastest index
  3. C A backup index
  4. D A view

Answer: A β€” An index that also enforces uniqueness - no two rows may share the indexed value

A unique index doubles as a UNIQUE constraint and speeds lookups. Primary keys are implemented as unique indexes automatically.

Unique indexConstraints

Q25. medium

What does COMMIT do?

  1. A Makes all changes in the transaction permanent and visible to others
  2. B Undoes changes
  3. C Starts a transaction
  4. D Creates a backup

Answer: A β€” Makes all changes in the transaction permanent and visible to others

After COMMIT the changes are durable (survive a crash) and other transactions can see them. Before COMMIT, the work is provisional and can be rolled back.

COMMITDurability

Q27. medium

What does an index NOT help with?

  1. A Queries that must read most rows anyway, or conditions that wrap the column in a function
  2. B Equality lookups
  3. C Range scans
  4. D Joins on the indexed column

Answer: A β€” Queries that must read most rows anyway, or conditions that wrap the column in a function

If a query returns a large fraction of the table, a scan is cheaper than an index. And functions on the column (non-sargable conditions) prevent index use entirely.

Index limitsSargability

Q29. medium

How do you remove an index?

  1. A DROP INDEX idx_name;
  2. B DELETE INDEX
  3. C REMOVE INDEX
  4. D Indexes cannot be removed

Answer: A β€” DROP INDEX idx_name;

DROP INDEX removes an index that is unused or hurting write performance. Some databases require the table name: DROP INDEX idx_name ON table.

DROP INDEX

Hard questions (17)

Q3. hard

What is a materialized view?

  1. A A view whose results are STORED physically and refreshed periodically - fast reads, but data can be stale
  2. B A normal view
  3. C A temporary table
  4. D An index

Answer: A β€” A view whose results are STORED physically and refreshed periodically - fast reads, but data can be stale

Unlike a regular view (recomputed each query), a materialized view caches the result. It speeds up expensive aggregations at the cost of needing REFRESH to stay current.

Materialized viewCaching

Q5. hard

What is the trade-off of adding indexes?

  1. A Faster reads but slower writes (every INSERT/UPDATE/DELETE must maintain the index) and more storage
  2. B They only help, no downside
  3. C They slow reads
  4. D They save storage

Answer: A β€” Faster reads but slower writes (every INSERT/UPDATE/DELETE must maintain the index) and more storage

Indexes must be kept in sync on every write. Too many indexes hurt write-heavy tables. Index the columns you filter, join and sort on - not everything.

IndexTrade-offs

Q7. hard

What is a composite index, and why does column order matter?

CREATE INDEX idx_ab ON t(a, b);
  1. A An index on multiple columns; it helps queries filtering on a LEFT-prefix of those columns (leftmost-prefix rule)
  2. B It indexes columns in any order equally
  3. C It is two separate indexes
  4. D Order never matters

Answer: A β€” An index on multiple columns; it helps queries filtering on a LEFT-prefix of those columns (leftmost-prefix rule)

An index on (a, b) helps WHERE a = ? and WHERE a = ? AND b = ?, but not WHERE b = ? alone. Put the most selective/most-filtered column first.

Composite indexLeftmost prefix

Q8. hard

What is a covering index?

  1. A An index that contains ALL columns a query needs, so the database answers it from the index alone
  2. B An index on every column
  3. C A backup index
  4. D A unique index

Answer: A β€” An index that contains ALL columns a query needs, so the database answers it from the index alone

If the index already holds the selected columns, the database skips reading the table (an 'index-only scan'), which is very fast. Adding INCLUDE columns can create covering indexes.

Covering indexIndex-only scan

Q10. hard

What is a full table scan, and when is it a problem?

  1. A Reading every row - fine for small tables, but slow on large ones when an index could have been used
  2. B Always fast
  3. C A type of index
  4. D A backup

Answer: A β€” Reading every row - fine for small tables, but slow on large ones when an index could have been used

Seeing 'Seq Scan' or 'full scan' on a large filtered query in EXPLAIN usually signals a missing index or a non-sargable condition (a function wrapped around the column).

Table scanEXPLAIN

Q12. hard

What do the ACID properties guarantee?

  1. A Atomicity (all-or-nothing), Consistency (valid state), Isolation (no interference), Durability (survives crashes)
  2. B Speed and compression
  3. C Only backups
  4. D Index maintenance

Answer: A β€” Atomicity (all-or-nothing), Consistency (valid state), Isolation (no interference), Durability (survives crashes)

ACID is the contract of a reliable transaction. It is why relational databases are trusted for banking and orders - a committed transaction is complete, correct and permanent.

ACIDTransactions

Q14. hard

What is a SAVEPOINT?

  1. A A marker within a transaction you can roll back TO, without undoing the whole transaction
  2. B A full commit
  3. C A backup file
  4. D An index

Answer: A β€” A marker within a transaction you can roll back TO, without undoing the whole transaction

SAVEPOINT sp1 lets you ROLLBACK TO sp1, undoing only the work after that point. Useful in long transactions to recover from a partial failure without discarding everything.

SAVEPOINTTransactions

Q15. hard

What problem does transaction ISOLATION address?

  1. A Interference between concurrent transactions - dirty reads, non-repeatable reads and phantom reads
  2. B Disk space
  3. C Index size
  4. D Syntax errors

Answer: A β€” Interference between concurrent transactions - dirty reads, non-repeatable reads and phantom reads

When many transactions run at once, they can see each other's uncommitted or changing data. Isolation levels control which anomalies are allowed, trading consistency against concurrency.

IsolationConcurrency

Q16. hard

What is a dirty read?

  1. A Reading data another transaction has changed but NOT yet committed - which may be rolled back
  2. B Reading old backups
  3. C A corrupted file
  4. D A syntax error

Answer: A β€” Reading data another transaction has changed but NOT yet committed - which may be rolled back

Dirty reads happen at the READ UNCOMMITTED isolation level. If the other transaction rolls back, you acted on data that never really existed. Higher isolation levels prevent this.

Dirty readIsolation levels

Q17. hard

What are the four standard isolation levels, from weakest to strongest?

  1. A READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE
  2. B LOW, MEDIUM, HIGH, MAX
  3. C OPEN, CLOSED, LOCKED, FREE
  4. D There is only one level

Answer: A β€” READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE

Each level prevents more anomalies but reduces concurrency. SERIALIZABLE behaves as if transactions ran one at a time (safest, slowest); READ COMMITTED is a common default.

Isolation levels

Q18. hard

What is a deadlock?

  1. A Two transactions each waiting for a lock the other holds - neither can proceed; the database aborts one
  2. B A crashed server
  3. C A full disk
  4. D A slow query

Answer: A β€” Two transactions each waiting for a lock the other holds - neither can proceed; the database aborts one

Deadlocks arise from circular lock dependencies. Databases detect them and kill one transaction (a deadlock victim), which the application should retry. Consistent lock ordering reduces them.

DeadlockLocks

Q21. hard

Can you INSERT or UPDATE through a view?

  1. A Sometimes - simple single-table views are updatable; views with joins, aggregates or DISTINCT usually are not
  2. B Always
  3. C Never
  4. D Only DELETE works

Answer: A β€” Sometimes - simple single-table views are updatable; views with joins, aggregates or DISTINCT usually are not

If the database can unambiguously map the change back to base-table rows, the view is updatable. Complex views need INSTEAD OF triggers to be writable.

Updatable viewsINSTEAD OF triggers

Q23. hard

Why can too many indexes hurt a write-heavy table?

  1. A Every INSERT/UPDATE/DELETE must update all relevant indexes, adding overhead to each write
  2. B Indexes never affect writes
  3. C They speed writes up
  4. D They only affect reads

Answer: A β€” Every INSERT/UPDATE/DELETE must update all relevant indexes, adding overhead to each write

Indexes are a read optimisation paid for with write cost and storage. On a table with heavy inserts, keep only the indexes that meaningfully help your queries.

Index overheadWrite performance

Q24. hard

What makes a WHERE condition 'sargable' (index-friendly)?

  1. A The indexed column is compared directly, not wrapped in a function - so the index can be used
  2. B It uses more functions
  3. C It uses OR everywhere
  4. D It has no WHERE

Answer: A β€” The indexed column is compared directly, not wrapped in a function - so the index can be used

WHERE created_at >= '2026-01-01' is sargable; WHERE YEAR(created_at) = 2026 is not, because the function must run on every row. Keep the column bare and transform the constant instead.

SargabilityIndexes

Q26. hard

What is optimistic vs pessimistic locking?

  1. A Pessimistic locks rows upfront to prevent conflicts; optimistic checks for conflicts at commit (e.g. a version column)
  2. B They are the same
  3. C Optimistic locks everything
  4. D Neither involves locks

Answer: A β€” Pessimistic locks rows upfront to prevent conflicts; optimistic checks for conflicts at commit (e.g. a version column)

Pessimistic (SELECT ... FOR UPDATE) suits high-contention writes. Optimistic (compare a version/timestamp on update) suits low contention and avoids holding locks - common in web apps.

LockingConcurrency

Q28. hard

What is index selectivity?

  1. A How many distinct values a column has - high selectivity (many distinct values) makes an index effective
  2. B The index size
  3. C The number of rows
  4. D The column order

Answer: A β€” How many distinct values a column has - high selectivity (many distinct values) makes an index effective

An index on a boolean (2 values) is rarely useful because each value matches half the table. An index on email (near-unique) is highly selective and very effective.

SelectivityIndex effectiveness

Q30. hard

What is the durability guarantee in ACID?

  1. A Once a transaction commits, its changes survive crashes and power loss (written to durable storage)
  2. B Data is deleted safely
  3. C Queries run fast
  4. D Backups happen automatically

Answer: A β€” Once a transaction commits, its changes survive crashes and power loss (written to durable storage)

Durability is typically achieved via a write-ahead log: changes are logged to disk before COMMIT returns, so recovery can replay them after a crash. A committed transaction is never lost.

DurabilityWrite-ahead log

Practice β€œViews, Indexes & Transactions” as a quiz