DBMS & SQLLevel 16
PART 4 • DATABASE SYSTEMS

Make Queries Faster for the Right Reason

Separate reusable query interfaces from stored results, choose useful access paths and read execution plans without guessing.

Level 16 of 18Performance Engineering180–220 minutes
BY THE END, YOU CAN
  • Compare views and materialized views.
  • Explain B+ tree and hash indexes.
  • Design composite indexes.
  • Predict sequential and index scans.
  • Read an execution plan.
  • Follow a safe tuning workflow.
01 • SAVE A QUERY INTERFACE

A View Stores a Definition, Not Ordinary Result Rows

BASE TABLESstudents + departments

Current source data remains authoritative.

VIEW DEFINITIONCREATE VIEW active_students AS ...

The database stores the named query.

QUERY THE VIEWSELECT * FROM active_students

The result reflects current underlying data.

SIMPLIFY

Hide repeated joins

Give applications a stable, meaningful interface over complex SQL.

SECURE

Expose fewer columns

Grant access to an approved projection, while remembering that permissions and ownership rules vary by product.

ABSTRACT

Separate consumers

Shield reports from some schema details, but do not treat a view as a guaranteed compatibility layer for every change.

LIMITATION

Not automatically faster

A normal view is expanded into the surrounding query; it usually does not cache rows.

02 • STORE EXPENSIVE RESULTS DELIBERATELY

A Materialized View Trades Freshness for Faster Reads

NORMAL VIEWAlways derives current results
  • Stores query definition
  • No separate refresh
  • Work is performed when queried
MATERIALIZED VIEWStores a result snapshot
  • Consumes storage
  • Can be indexed
  • Needs refresh to become current
10:00Refresh snapshot
10:30Base tables change
11:00Report may still show 10:00 data
Good fit: expensive summaries read frequently where controlled staleness is acceptable. Poor fit: transaction screens that must show the latest committed value.
03 • BUILD AN ALTERNATE ACCESS PATH

An Index Reduces Search Work but Adds Maintenance Work

B+ TREE

Ordered navigation

Supports equality, range predicates, ordered traversal and often prefix matching.

40 | 70
10 20 3040 50 6070 80 90
HASH

Equality lookup

Maps a key to a bucket. Excellent for supported equality cases, but generally unsuitable for range ordering.

0 → 24, 601 → 13, 492 → 08, 32
COVERING

Answer from the index

When all required columns are available in the index and visibility rules permit, the engine may avoid fetching table pages.

INDEX (dept_id, salary) INCLUDE (name)
READ BENEFIT fewer pages, faster filtering, useful orderingWRITE COST extra work on INSERT, UPDATE and DELETESPACE COST additional disk and cache usageDESIGN COST redundant indexes complicate maintenance
04 • COLUMN ORDER CHANGES USEFULNESS

A Composite Index Is Not a Bag of Columns

INDEX KEY ORDER(department_id, salary, joined_at)
1
department_id
2
salary
3
joined_at

Useful starting patterns

  • department_id = ?
  • department_id = ? AND salary > ?
  • department_id = ? AND salary = ? AND joined_at > ?

Usually cannot seek efficiently from the left edge

  • salary > ? alone
  • joined_at = ? alone
Equality first

Put frequently used equality columns before a range column when it matches real workload needs.

Range changes the path

Columns after the first range may be less useful for narrowing the seek, though they can still help coverage.

Selectivity matters

An index on a low-cardinality flag may not save enough table work by itself.

Workload decides

Design from actual predicates, joins, ordering and returned columns—not from a universal formula.

05 • CHOOSE BETWEEN READING MANY OR FEW PAGES

A Sequential Scan Is Sometimes the Best Plan

SEQUENTIAL SCANRead the table pages in order

Often best when a large fraction of rows is needed, the table is small, or no useful index exists.

INDEX SCANNavigate index, then fetch rows

Often best for selective predicates, but scattered table lookups become expensive when many rows qualify.

INDEX-ONLY SCANRead required values from index

Possible only when the index covers the query and database visibility conditions allow it.

BITMAP ACCESSCollect locations, then visit pages

Some products use bitmap plans between highly selective index access and a full sequential scan.

SEARCH-FRIENDLYWHERE created_at >= DATE '2026-01-01'

The indexed column remains directly comparable.

VERSUS
FUNCTION-WRAPPEDWHERE EXTRACT(YEAR FROM created_at) = 2026

A normal index on created_at may be harder to use unless a matching expression index exists.

06 • READ THE OPTIMIZER'S DECISION

EXPLAIN Shows a Tree of Physical Operations

Aggregatecost 240..241 · rows 10
Hash Joincost 80..220 · rows 4,200
Seq Scan: ordersrows 100,000
Hash → Index Scan: customersrows 2,000
Cost

An optimizer estimate in product-specific units—not elapsed milliseconds.

Rows

Estimated output cardinality. Large estimate-versus-actual errors can cause poor choices.

Loops

How many times an operation ran in an actual plan. Multiply per-loop work when interpreting totals.

Width

Estimated average bytes per output row, which affects memory and I/O estimates.

EXPLAIN versus EXPLAIN ANALYZE

EXPLAIN estimates without executing in common systems. EXPLAIN ANALYZE actually runs the statement and reports measurements. Use it cautiously with writes or expensive production queries; product syntax and behavior vary.

07 • TUNE WITH EVIDENCE

A Responsible Optimization Workflow

  1. 1
    Measure the real workload

    Capture slow, frequent or resource-heavy statements with representative parameters.

  2. 2
    Inspect the plan

    Locate expensive nodes, large row flows, repeated loops and estimate errors.

  3. 3
    Check query shape and data

    Review predicates, joins, selected columns, statistics and data distribution.

  4. 4
    Make one justified change

    Rewrite a predicate, update statistics or add the smallest useful index.

  5. 5
    Measure again

    Compare latency, reads, writes, storage and plan stability under representative load.

  6. 6
    Monitor side effects

    Confirm that other queries and write operations did not regress.

08 • DESIGN FOR A REAL QUERY

Interactive Index Design Advisor

Select a workload and compare candidate indexes. The explanation includes benefits, limitations and write cost.

WORKLOAD QUERY
09 • ESTIMATE THE ACCESS PATH

Execution Plan Explorer

Change table size, expected matches and index availability. This simplified cost model teaches the optimizer's trade-off; it is not a real database plan.

SEQUENTIAL PATH

Read table pages in order.

INDEX PATH

Educational model: actual optimizers use product-specific costs, statistics, page layout, caching, parallelism and many other factors.

10 • CHECK YOUR UNDERSTANDING

Ten Formative Concept Checks

1. A normal SQL view primarily stores:

2. A materialized view normally needs what to reflect later base-table changes?

3. Which index structure naturally supports ordered range lookup?

4. For index (department_id, salary), which predicate best uses its left edge?

5. Adding an index generally increases the cost of:

6. A sequential scan can be optimal when:

7. In a query plan, estimated cost is usually:

8. A large estimated-versus-actual row difference often suggests:

9. Which predicate is more search-friendly for a normal index on created_at?

10. The safest first step in query tuning is to:

Answered correctly: 0 of 10
11 • EXPLAIN & PREPARE

University and Interview Questions

2-MARK
  1. Define a view.
  2. What is selectivity?
  3. B+ tree versus hash?
  4. What does EXPLAIN show?
5-MARK / PRACTICAL
  1. Compare views and materialized views.
  2. Design a composite index for a query.
  3. Explain sequential versus index scans.
  4. Interpret a plan tree.
INTERVIEW
  1. Why might a database ignore an index?
  2. Can too many indexes hurt?
  3. How do stale statistics affect plans?
  4. How would you verify an optimization?
Show the optimization answer framework
  1. State the workload and required result.
  2. Identify filters, joins, ordering and output columns.
  3. Estimate selectivity and row flow.
  4. Describe candidate access paths.
  5. Read the plan from leaves toward the root.
  6. Compare estimated and actual rows where safe.
  7. Measure the change and its read/write trade-offs.

You Can Now Optimize with Evidence

  • Views store definitions; materialized views store refreshable results.
  • Indexes trade write and space cost for useful access paths.
  • Composite-index column order follows workload patterns.
  • Sequential scans are correct choices for many-row reads.
  • Plans expose estimated operations and row flow.
  • Measure before and after every tuning change.
COURSE CHECKPOINT

Mark this level when you can justify an access path using workload, selectivity and plan evidence.

Saved in this browser only.