JavaScript Academy · Lesson

Indexes and Queries

Query data efficiently with indexes.

Lesson 3 of 413 steps

Indexes and Queries is a free JavaScript Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, and your progress syncs across the web and the CoddyKit app. The JavaScript Academy course includes 4 lessons in total.

Why Indexes?

By default you can only look up records by their primary key. An index lets you query by another property efficiently, like finding all users with a given last name.

Creating an Index

Create indexes inside onupgradeneeded, right after creating the store, with store.createIndex(name, keyPath, options).

request.onupgradeneeded = (e) => {
  const db = e.target.result;
  const store = db.createObjectStore('users', { keyPath: 'id' });
  store.createIndex('byEmail', 'email', { unique: true });
};

Unique vs Non-Unique

The unique option enforces that no two records share the same index value. Use unique: false (the default) when many records can share a value, like a city.

store.createIndex('byCity', 'city', { unique: false });
store.createIndex('byEmail', 'email', { unique: true });

Querying Through an Index

Get the index from a store in a transaction, then call get or getAll on it using the indexed property's value.

const tx = db.transaction('users', 'readonly');
const index = tx.objectStore('users').index('byEmail');
const req = index.get('ada@example.com');
req.onsuccess = () => console.log(req.result);

getAll

getAll() returns every matching record as an array in one request, simpler than iterating with a cursor for moderate result sets.

const index = store.index('byCity');
const req = index.getAll('Paris');
req.onsuccess = () => {
  console.log('found', req.result.length, 'users in Paris');
};

Key Ranges

An IDBKeyRange describes a span of keys for range queries. Helpers include only, lowerBound, upperBound, and bound.

const range = IDBKeyRange.bound(18, 65); // ages 18..65
const index = store.index('byAge');
index.getAll(range);

Bound Options

IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen) can exclude endpoints. Open bounds are exclusive.

// 18 inclusive, 65 exclusive:
const range = IDBKeyRange.bound(18, 65, false, true);
// lowerBound(10) => keys >= 10
// upperBound(10, true) => keys < 10

Cursors

For large result sets or custom iteration, open a cursor with index.openCursor(range). It visits matching records one at a time so you do not load everything into memory.

const req = store.index('byCity').openCursor();
req.onsuccess = (e) => {
  const cursor = e.target.result;
  if (cursor) {
    console.log(cursor.value);
    cursor.continue(); // move to next match
  }
};

Counting Matches

index.count(range) returns how many records match without retrieving them, which is fast and memory-light.

const req = store.index('byCity').count('Paris');
req.onsuccess = () => console.log('count:', req.result);

Getting Keys Only

getAllKeys and a key cursor return just the primary keys of matching records, useful when you only need references, not full objects.

const req = store.index('byCity').getAllKeys('Paris');
req.onsuccess = () => console.log('keys:', req.result);

Querying Recap

Indexes turn IndexedDB into a queryable store: create them in onupgradeneeded, then use get, getAll, key ranges, and cursors to fetch exactly the records you need.

Quick Check

Test your understanding of indexes and queries.

Recap

You learned indexes and queries:

  • Create indexes in onupgradeneeded with createIndex.
  • The unique option enforces distinct values.
  • Query via index.get / getAll.
  • IDBKeyRange enables range queries.
  • Cursors iterate large sets; count tallies matches.

Next, versioning and upgrades.

Free to start

Learn JavaScript with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
59
Lessons
200

Frequently Asked Questions

Is the “Indexes and Queries” lesson free?

Yes — any 3 lessons of the JavaScript Academy learning path, including “Indexes and Queries”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The JavaScript Academy course includes 4 lessons in total.

What will I learn in “Indexes and Queries”?

Query data efficiently with indexes. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Indexes and Queries” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Opening a Database
  2. Transactions and CRUD
  3. Indexes and Queries
  4. Versioning and Upgrades
← Back to JavaScript Academy