Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 34/ 160
02. SQL & Data Engineering Basics

Database Indexing & Query Execution Plans

Speed up queries with indexes and read EXPLAIN plans to find scans, sorts, and join costs.

AdvancedB-tree Indexes · EXPLAIN3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

An index is like a book's index that jumps straight to the right pages, and EXPLAIN shows how the database plans to find your data.

Think of it like…

Finding a name in a phone book: scanning every page is a sequential scan; using the alphabetical order to jump to the right section is an index. EXPLAIN is asking the librarian how they plan to find your entry before they start.

Where you’ve seen it

A query pulling one customer's orders for a dashboard took 6 seconds on a 120-million-row table. EXPLAIN ANALYZE showed Seq Scan on orders (rows=120,000,000) with a Filter on customer_id, so it read every row to return 40. After CREATE INDEX ON orders (customer_id, created_at) the plan became an Index Scan reading 40 rows in 2 ms. A different query, filtering by DATE(created_at), didn't use the index until rewritten as a range on created_at.

Words you’ll hear

Seq Scan / Index Scan
Read the whole table / use an index to read only matching rows.
EXPLAIN ANALYZE
Executes the query and reports actual time and rows per plan node.
Selectivity
Fraction of rows a filter keeps; indexes pay off when it is small.
Partition pruning
Skipping partitions (such as other dates) that the filter rules out.

Visual diagram

Loading interactive diagram

Theory & deep dive

Indexes and when they help

A B-tree index on (customer_id, created_at) lets the database find a customer's rows by key lookup and read them already sorted by date. Indexes speed reads that filter on selective columns, join on keys and sort; they slow writes and use space, so index the columns you filter and join on, not everything. Column order matters: put equality columns first, then range or sort columns. They don't help when the filter matches a large share of the table (the planner correctly prefers a sequential scan), when a function wraps the column (WHERE lower(email) = … needs an index on lower(email)), or on leading-wildcard LIKE patterns.

Analytical queries typically scan large fractions of tables, where columnar storage, partitioning (by date) and clustering matter more than B-trees. In BigQuery and Snowflake you reduce cost and time by selecting fewer columns, filtering on the partition column, and avoiding SELECT *.

A sargable date filter

WHERE created_at >= '2026-10-01' AND created_at < '2026-11-01' can use an index or a partition. WHERE DATE(created_at) = '2026-10-15' or WHERE TO_CHAR(created_at, 'YYYY-MM') = '2026-10' wraps the column in a function, forcing a scan of every row.

Key takeaway: Filter on bare columns, index selective filters and joins, partition by time on warehouses.

Reading EXPLAIN

Run EXPLAIN to see the plan without executing, or EXPLAIN (ANALYZE, BUFFERS) (PostgreSQL) to run it and see actual time, rows and pages read. Read from the innermost, most-indented nodes outwards. Look for: Seq Scans on big tables with highly selective filters; large differences between estimated rows= and actual rows= (stale statistics, fixed with ANALYZE); expensive Sort or HashAggregate nodes that spill to disk (Sort Method: external merge); nested loops with huge outer row counts; and joins that multiply rows far beyond expectations (a fan-out bug, not an index problem).

Practical loop: get the baseline time, read the plan, make one change (rewrite a filter, add a column to the SELECT list less, create an index, pre-aggregate before joining), re-run EXPLAIN, and compare. Test on realistic data volumes: an index that helps 100 million rows may be ignored on a 10,000-row dev table. On shared production systems, ask a DBA before creating indexes, and run heavy analytical queries on a replica or warehouse. In BigQuery use the dry-run estimate and the query execution graph; in Snowflake the Query Profile.

Spotting a stale-statistics problem

Nested Loop (rows=10) … actual rows=3,200,000 means the planner expected 10 rows but got 3.2 million; run ANALYZE tablename; and re-check the plan, which should switch to a hash join.

Key takeaway: Compare estimated and actual rows, look for scans, sorts and fan-out, and change one thing at a time.

How it works, step by step

Step 1 of 4
Time it

1. Measure the baseline

Record runtime and rows returned on realistic data before changing anything.

6 s for 40 rows
Key numbers at this step
Realistic
data volume

When to use it & trade-offs

What it is

An index is a sorted structure (usually a B-tree) that lets the database find rows without scanning the whole table. EXPLAIN shows the query plan: how the database intends to run your query, with node types (Seq Scan reads everything, Index Scan jumps via an index), join methods (nested loop, hash join, merge join), row estimates and costs; EXPLAIN ANALYZE runs it and adds real times and row counts. For data scientists the practical goal isn't becoming a DBA: it's recognising why a query is slow (full scans, missing filters, huge joins, sorts) and making it cheaper.

Why it matters: A feature query that takes 40 minutes blocks iteration, strains a shared database and can run into timeouts. Most slow analytical queries share a few causes, and reading a plan shows which. On warehouses (BigQuery, Snowflake) there are no traditional indexes, but the same thinking (scan less data via partitions and clustering, filter early, avoid fan-out) applies.

When to reach for it

  • Diagnosing slow feature and reporting queries
  • Deciding which columns to filter on or index
  • Reducing warehouse scan costs

When to avoid or be careful

  • Wrapping filtered columns in functions
  • Indexing every column
  • Benchmarking on a tiny development table

Ways to make a query cheaper

Add or fix an index
Best for: Selective filters and key joins on transactional databases

Strengths: Large speed-ups for point lookups.

Watch out: Write cost and storage; no help for broad scans.

Rewrite the query (sargable filters, fewer columns, pre-aggregation)
Best for: Any database

Strengths: No schema change; often the biggest win.

Watch out: Needs understanding of the plan.

Partition and cluster (warehouses)
Best for: Large analytical tables

Strengths: Scans only relevant partitions; lower cost.

Watch out: Must filter on the partition column.

Interview signals & numbers to know

When this topic comes up

  • “This query takes 40 minutes”
  • “What does Seq Scan mean?”
  • “The index isn't being used”
  • EXPLAIN ANALYZE
  • Partition pruning in BigQuery

Benchmarks & rules of thumb

6 s → 2 ms -
speed-up in the index example
119,999,960 -
rows filtered out by a Seq Scan in the example
ANALYZE -
refreshes planner statistics

Common mistakes & follow-ups

Common interview mistakes

  • Writing WHERE DATE(created_at) = … and wondering why the created_at index is ignored.
  • Adding five indexes to a table that is mostly written to, slowing the application.
  • Blaming indexes for a slow query that actually multiplies rows through a many-to-many join.

Likely interviewer follow-ups

  • How do you tell whether a query is using an index?
  • Why can an index be ignored even though it exists?
  • How do you reduce cost in BigQuery without indexes?
Interview tip: Show one plan before and after a fix with row counts and times. A concrete before/after makes performance reasoning tangible.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Database Indexing & Query Execution Plans with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Views, Materialized Views & Stored Procedures
Next topic
Normalization vs Denormalization