ποΈ 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.
Medium questions (13)
Q1. medium
What is a VIEW?
CREATE VIEW active_customers AS
SELECT * FROM customers WHERE active = 1;
- A A saved query that acts like a virtual table - it stores no data itself
- B A copy of a table
- C An index
- 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?
- A They hide complexity and restrict access - users query a simple view instead of complex joins or sensitive columns
- B They always speed up queries
- C They store data twice
- 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);
- A A data structure that speeds up row lookups on one or more columns
- B A sorted copy of the table
- C A view
- 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?
- A Columns used in WHERE, JOIN and ORDER BY - especially foreign keys and frequently searched fields
- B Every column
- C Only text columns
- 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;
- A The query execution plan - how the database will run the query, including index use and join methods
- B The query result
- C The table structure
- 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;
- A A group of statements executed as a single all-or-nothing unit
- B A single SELECT
- C A backup
- 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?
- A Undoes all changes made since the transaction began
- B Saves the changes
- C Deletes the table
- 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?
- A So the debit and credit both succeed or both fail - never one without the other
- B For speed
- C To use an index
- 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?
- A No - a regular view re-runs its query each time; only a MATERIALIZED view stores results
- B Yes, always
- C It stores half the results
- 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?
- A An index that also enforces uniqueness - no two rows may share the indexed value
- B The fastest index
- C A backup index
- 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?
- A Makes all changes in the transaction permanent and visible to others
- B Undoes changes
- C Starts a transaction
- 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?
- A Queries that must read most rows anyway, or conditions that wrap the column in a function
- B Equality lookups
- C Range scans
- 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?
- A DROP INDEX idx_name;
- B DELETE INDEX
- C REMOVE INDEX
- 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?
- A A view whose results are STORED physically and refreshed periodically - fast reads, but data can be stale
- B A normal view
- C A temporary table
- 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?
- A Faster reads but slower writes (every INSERT/UPDATE/DELETE must maintain the index) and more storage
- B They only help, no downside
- C They slow reads
- 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);
- A An index on multiple columns; it helps queries filtering on a LEFT-prefix of those columns (leftmost-prefix rule)
- B It indexes columns in any order equally
- C It is two separate indexes
- 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?
- A An index that contains ALL columns a query needs, so the database answers it from the index alone
- B An index on every column
- C A backup index
- 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?
- A Reading every row - fine for small tables, but slow on large ones when an index could have been used
- B Always fast
- C A type of index
- 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?
- A Atomicity (all-or-nothing), Consistency (valid state), Isolation (no interference), Durability (survives crashes)
- B Speed and compression
- C Only backups
- 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?
- A A marker within a transaction you can roll back TO, without undoing the whole transaction
- B A full commit
- C A backup file
- 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?
- A Interference between concurrent transactions - dirty reads, non-repeatable reads and phantom reads
- B Disk space
- C Index size
- 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?
- A Reading data another transaction has changed but NOT yet committed - which may be rolled back
- B Reading old backups
- C A corrupted file
- 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?
- A READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE
- B LOW, MEDIUM, HIGH, MAX
- C OPEN, CLOSED, LOCKED, FREE
- 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?
- A Two transactions each waiting for a lock the other holds - neither can proceed; the database aborts one
- B A crashed server
- C A full disk
- 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?
- A Sometimes - simple single-table views are updatable; views with joins, aggregates or DISTINCT usually are not
- B Always
- C Never
- 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?
- A Every INSERT/UPDATE/DELETE must update all relevant indexes, adding overhead to each write
- B Indexes never affect writes
- C They speed writes up
- 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)?
- A The indexed column is compared directly, not wrapped in a function - so the index can be used
- B It uses more functions
- C It uses OR everywhere
- 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?
- A Pessimistic locks rows upfront to prevent conflicts; optimistic checks for conflicts at commit (e.g. a version column)
- B They are the same
- C Optimistic locks everything
- 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?
- A How many distinct values a column has - high selectivity (many distinct values) makes an index effective
- B The index size
- C The number of rows
- 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?
- A Once a transaction commits, its changes survive crashes and power loss (written to durable storage)
- B Data is deleted safely
- C Queries run fast
- 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