Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 31 ยท Firebase Cloud Firestore

Queries, Indexes and Pagination

Learn Firestore where, orderBy and limit, why compound queries need composite indexes, how startAfter cursors paginate, and how to live without joins.

A Firestore query asks one collection for the documents that match some conditions, in a chosen order, up to a limit. That is nearly the whole language. There are no joins, no GROUP BY and no LIKE '%text%'. This looks restrictive next to SQL, but the restriction buys a guarantee: a query's cost depends on the number of documents it returns, not on the size of the collection. A query over ten million documents that returns ten results is as fast as one over a hundred.

To keep that promise, every query must be answerable by walking an index, a sorted list the database maintains for you. This lesson shows how to build queries, when you need to create an index yourself, how to paginate, and how to design data when joins are not available. The previous lessons covered the data model and writes.

Firestore itself cannot run on this site, so SDK code is read-only. The runnable query engine below is a stand-in that works on a plain array. It shows the ideas (filters, ordering, cursors) but is not how Firestore is implemented.

Building a query

JavaScript
import { getFirestore, collection, query, where, orderBy, limit, getDocs } from "firebase/firestore";

const db = getFirestore();

const q = query(
  collection(db, "products"),
  where("category", "==", "books"),
  where("price", "<=", 20),
  orderBy("price", "asc"),
  limit(10),
);

const snapshot = await getDocs(q);
snapshot.forEach(d => console.log(d.id, d.data()));

query() takes a collection and any number of constraints. The common ones:

Constraint Meaning
where(field, op, value) Keep documents where the condition holds
orderBy(field, "asc" or "desc") Sort by a field
limit(n) Return at most n documents
startAfter(...), endBefore(...) Cursor boundaries for pagination

The operators for where are ==, !=, <, <=, >, >=, in, not-in, array-contains and array-contains-any. Strings compare by their UTF-8 bytes, so capital letters sort before lowercase ones.

Some rules to remember:

  • A query searches one collection (or, with a collection-group query, all collections that share a name). It never reaches into subcollections of the documents it returns.
  • If you filter with a range (<, >) on a field and also sort, the first orderBy must be on that same field.
  • Documents that lack the field you filter or sort on are never returned. A missing field is not the same as null.
  • Results are always paged by the server: asking for limit(10) really reads ten documents, which is also what you are billed for.

Indexes

An index is a list of documents sorted by one or more fields. Firestore automatically creates a single-field index for every field, so these just work:

  • one where on any field,
  • a where plus an orderBy on the same field,
  • several equality filters (==) with no ordering. Firestore merges the single-field indexes.

Once a query mixes different fields, the database needs a composite index: one list sorted by several fields in a specific order. For example, "books, cheapest first" filters on category and sorts by price. If you run it without a matching composite index, the SDK fails with an error that contains a link. Opening the link pre-fills the index in the console. You can also declare indexes in a file and deploy them with the CLI:

JSON
{
  "indexes": [
    {
      "collectionGroup": "products",
      "queryScope": "COLLECTION",
      "fields": [
        { "fieldPath": "category", "order": "ASCENDING" },
        { "fieldPath": "price", "order": "ASCENDING" }
      ]
    }
  ]
}
Terminal
firebase deploy --only firestore:indexes

Treat firestore.indexes.json as source code: commit it, so staging and production stay in step. Indexes cost storage and add a little to each write, so create the ones your screens need and delete the rest.

Try it: a stand-in query engine with cursors

This engine takes a where list, an orderBy list and a limit, and it supports a startAfter cursor built from the last document of the previous page. It also reports whether the query would need a composite index under a simplified rule (more than one field involved, unless all conditions are plain equalities).

JS Filters, ordering, limit and startAfter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the two books priced at 18. They sit next to each other, and the cursor, built from the last document of page 1, continues correctly from the right one because ties are ordered by ID. Real Firestore also appends the document ID as a hidden last sort key for the same reason.

Pagination with cursors

SQL developers reach for OFFSET. Firestore has an offset(), but it still reads and bills for every skipped document, so avoid it. Use cursors instead: remember the last document you showed and ask for what comes after it.

JavaScript
import { startAfter } from "firebase/firestore";

const first = query(collection(db, "products"), orderBy("price"), limit(10));
const firstPage = await getDocs(first);

const lastVisible = firstPage.docs[firstPage.docs.length - 1];

const next = query(
  collection(db, "products"),
  orderBy("price"),
  startAfter(lastVisible),   // or startAfter(lastVisible.data().price)
  limit(10),
);
const secondPage = await getDocs(next);

The cursor must be consistent with your orderBy. If you order by price, a cursor made from a price value continues from that price. Passing the snapshot itself is the safest choice because it also carries the document ID for tie-breaking. A "Load more" button simply keeps the last snapshot in memory. Jumping straight to page 50 is awkward with cursors, which is rarely a loss on feeds and infinite lists.

Living without joins

Suppose each order stores only customerId, and your screen must show the customer's name beside each order. In SQL, you join. In Firestore you have three choices:

  1. N+1 reads: fetch the orders, then fetch each customer. Fast to write, slow and costly on a long list (cacheable if customers repeat).
  2. Denormalize: store customerName inside each order. One query renders the screen.
  3. Combine in a function: build a server-side view in a Cloud Function and store the result.

Denormalization is the usual answer. Its price is paid on writes: when a customer renames, every order holding the old name is out of date. Decide per field:

  • Values that never change (a product's SKU at purchase time) are perfect to copy. A historical order should keep the old price anyway.
  • Values that change rarely and where a short delay is fine can be updated by a background function.
  • Values that change often are better fetched at read time.

Because writes are cheap and reads dominate most apps, trading a little duplicated data for simple reads is almost always the right deal. The modeling lesson compares both approaches in depth.

Try it: seeing the cost of N+1

This counts document reads for a screen showing 20 orders with customer names, using the N+1 approach, N+1 with a small cache, and denormalized data.

JS Counting reads: N+1 versus denormalized

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Billing and speed follow reads, so the 40 versus 20 reads here is the whole argument in miniature.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is true of a Firestore query's cost?

    Queries walk an index, so cost follows the number of results (and index entries scanned), not the collection size.
  2. 2. You run where('category','==','books') plus orderBy('price') and get an error with a link. What is missing?

    Combining a filter and an ordering on different fields needs a composite index. The error link pre-fills it.
  3. 3. Why are cursors (startAfter) preferred over offset()?

    A cursor starts reading right after a known document. An offset reads the skipped documents first.
  4. 4. A document has no price field. Does orderBy('price') include it?

    Filtering or sorting on a field only returns documents that contain that field.
  5. 5. What is the main cost of denormalizing a customer's name into orders?

    Copies make reads cheap but shift work to writes when the source value changes.

Summary

  • A query reads one collection and combines where, orderBy and limit; cost follows the results returned.
  • Single-field indexes are automatic; mixed-field queries need composite indexes you declare and deploy.
  • Paginate with startAfter cursors, not offset().
  • Documents lacking a filtered or sorted field are excluded.
  • There are no joins: denormalize stable values, update copies deliberately, and count reads when you choose.

Next: Realtime Listeners and Offline Support.