0Pricing
JavaScript Academy · Lesson

Indexes and Queries

Query data efficiently with indexes.

Indexes and Queries is a free JavaScript Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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.

Frequently asked questions

Is the “Indexes and Queries” lesson free?

Yes — the full text of “Indexes and Queries” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.

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; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

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