Bird
Raised Fist0
Firebasecloud~20 mins

Query optimization in Firebase - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Firestore Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ service_behavior
intermediate
2:00remaining
Understanding Firestore Query Index Requirements
You have a Firestore collection with documents containing fields: age (number), city (string), and status (string). You run this query:
collection.where('age', '>', 25).where('city', '==', 'Seattle').orderBy('status')
What will happen when you run this query without any additional setup?
AThe query fails with an error asking to create a composite index.
BThe query runs successfully without any errors.
CThe query returns documents but ignores the orderBy clause.
DThe query returns documents but only filters by age.
Attempts:
2 left
💡 Hint
Firestore requires composite indexes for queries with multiple where filters and orderBy on different fields.
❓ Architecture
intermediate
2:00remaining
Optimizing Firestore Queries for Large Collections
You have a Firestore collection with millions of documents. You want to efficiently fetch documents where status is 'active' and order them by createdAt descending. Which approach is best to optimize query performance?
AUse multiple queries for each status value and merge results in the app.
BUse a query with where('status', '==', 'active') and orderBy('createdAt', 'desc') with a composite index on status and createdAt.
CUse orderBy('createdAt', 'desc') only and filter status after fetching.
DFetch all documents and filter 'active' status in your application code.
Attempts:
2 left
💡 Hint
Filtering and ordering in the query with proper indexes is more efficient than client-side filtering.
❓ security
advanced
2:00remaining
Securing Firestore Queries with Rules and Indexes
You want to allow users to query their own orders by userId and filter by orderStatus. You create a composite index on userId and orderStatus. Which Firestore security rule best ensures users can only query their own orders?
Aallow read: if request.auth.token.admin == true;
Ballow read: if request.auth.uid != null;
Callow read: if resource.data.orderStatus == 'completed';
Dallow read: if request.auth.uid == resource.data.userId;
Attempts:
2 left
💡 Hint
Security rules should restrict access based on user identity matching document fields.
✅ Best Practice
advanced
2:00remaining
Reducing Firestore Query Costs with Pagination
You have a Firestore query that returns thousands of documents. To reduce cost and improve performance, what is the best practice to paginate results?
AUse offset() to skip documents and limit() to fetch pages.
BFetch all documents at once and slice the results in the client.
CUse limit() with startAfter() or startAt() cursors to fetch pages incrementally.
DRun multiple queries with different where filters to split data.
Attempts:
2 left
💡 Hint
Firestore charges for documents read, so fetching only needed documents is best.
🧠 Conceptual
expert
2:00remaining
Analyzing Firestore Query Execution Behavior
Consider a Firestore collection with documents having fields: category, price, and rating. You run this query:
collection.where('category', '==', 'books').orderBy('price').orderBy('rating')
Which statement best describes how Firestore executes this query?
AFirestore uses a composite index on category, price, and rating to efficiently filter and order results.
BFirestore orders by price only and ignores the rating orderBy clause.
CFirestore filters by category first, then orders by price and rating without needing an index.
DFirestore requires separate queries for price and rating ordering.
Attempts:
2 left
💡 Hint
Multiple orderBy clauses require a composite index covering all fields in order.

Practice

(1/5)
1. What is the main benefit of using query optimization in Firebase?
easy
A. It makes your app faster and reduces costs by fetching only needed data.
B. It automatically backs up your database.
C. It increases the size of your database.
D. It disables security rules temporarily.

Solution

  1. Step 1: Understand query optimization purpose

    Query optimization aims to improve performance and reduce costs by limiting data fetched.
  2. Step 2: Identify correct benefit

    Only "It makes your app faster and reduces costs by fetching only needed data." describes faster app and cost reduction by fetching needed data.
  3. Final Answer:

    It makes your app faster and reduces costs by fetching only needed data. -> Option A
  4. Quick Check:

    Query optimization = faster app and lower cost [OK]
Hint: Optimization means fetching only what you need [OK]
Common Mistakes:
  • Thinking optimization backs up data
  • Assuming optimization increases database size
  • Confusing optimization with security settings
2. Which Firebase query syntax correctly limits results to 10 documents ordered by 'score'?
easy
A. db.collection('games').orderBy('score').limit(10)
B. db.collection('games').limit(10).orderBy('score')
C. db.collection('games').where('score', '==', 10).orderBy('score')
D. db.collection('games').orderBy('score', 10)

Solution

  1. Step 1: Check correct method order

    In Firebase, orderBy must come before limit to sort then limit results.
  2. Step 2: Validate syntax correctness

    db.collection('games').orderBy('score').limit(10) uses correct chaining: orderBy('score').limit(10). Others misuse order or parameters.
  3. Final Answer:

    db.collection('games').orderBy('score').limit(10) -> Option A
  4. Quick Check:

    orderBy then limit = correct syntax [OK]
Hint: Always orderBy before limit in Firebase queries [OK]
Common Mistakes:
  • Placing limit before orderBy
  • Using where instead of limit for count
  • Passing number as second orderBy argument
3. Given this query:
db.collection('users').where('age', '>=', 18).orderBy('age').limit(3)

What will this query return?
medium
A. All users younger than 18.
B. An error because orderBy and where fields differ.
C. The first 3 users aged 18 or older, ordered by age ascending.
D. The last 3 users regardless of age.

Solution

  1. Step 1: Analyze where and orderBy fields

    Both where and orderBy use 'age', which is allowed and required for range filters.
  2. Step 2: Understand limit effect

    Limit(3) returns only first 3 documents matching criteria ordered by age ascending.
  3. Final Answer:

    The first 3 users aged 18 or older, ordered by age ascending. -> Option C
  4. Quick Check:

    where and orderBy on same field + limit = first 3 matching [OK]
Hint: where range and orderBy must use same field [OK]
Common Mistakes:
  • Thinking it returns users younger than 18
  • Assuming error due to different fields
  • Ignoring limit effect
4. You wrote this query:
db.collection('orders').where('status', '==', 'shipped').orderBy('date')

But it throws an error about missing index. What should you do?
medium
A. Remove orderBy to fix the error.
B. Create a composite index on 'status' and 'date' fields in Firebase console.
C. Change '==' to '>=' in where clause.
D. Use limit(1) to avoid indexing.

Solution

  1. Step 1: Understand composite index requirement

    Queries with where and orderBy on different fields need a composite index in Firebase.
  2. Step 2: Fix error by creating index

    Creating a composite index on 'status' and 'date' fields resolves the error.
  3. Final Answer:

    Create a composite index on 'status' and 'date' fields in Firebase console. -> Option B
  4. Quick Check:

    Missing index error = create composite index [OK]
Hint: Missing index error means create composite index [OK]
Common Mistakes:
  • Removing orderBy instead of indexing
  • Changing operators incorrectly
  • Using limit to bypass index requirement
5. You want to optimize a query to fetch only active users with scores above 50, ordered by score descending, limited to 5 results. Which query is best?
hard
A. db.collection('users').where('active', '==', true).orderBy('score').limit(5)
B. db.collection('users').orderBy('score', 'desc').limit(5).where('active', '==', true).where('score', '>', 50)
C. db.collection('users').where('score', '>', 50).limit(5).orderBy('score', 'desc').where('active', '==', true)
D. db.collection('users').where('active', '==', true).where('score', '>', 50).orderBy('score', 'desc').limit(5)

Solution

  1. Step 1: Check correct chaining and order

    db.collection('users').where('active', '==', true).where('score', '>', 50).orderBy('score', 'desc').limit(5) correctly chains where filters first, then orderBy with descending, then limit.
  2. Step 2: Validate query logic

    It filters active users with score > 50, orders by score descending, and limits to 5 results as required.
  3. Final Answer:

    db.collection('users').where('active', '==', true).where('score', '>', 50).orderBy('score', 'desc').limit(5) -> Option D
  4. Quick Check:

    Filter then orderBy desc then limit = optimized query [OK]
Hint: Chain where filters before orderBy and limit [OK]
Common Mistakes:
  • Placing limit before where
  • Incorrect orderBy direction
  • Missing one of the filters
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard