0
0
FirebaseHow-ToBeginner · 3 min read

How to Use orderByChild in Firebase Realtime Database

Use orderByChild in Firebase Realtime Database queries to sort data by a specific child key. Attach it to a database reference, then use once or on to read the sorted data.
📐

Syntax

The orderByChild method sorts data by the value of a specified child key. You call it on a database reference, passing the child key name as a string.

  • ref: The database reference to the node you want to query.
  • orderByChild('childKey'): Sorts the children of ref by the value of childKey.
  • Use once('value') or on('value') to read the sorted data.
javascript
firebase.database().ref('path/to/data').orderByChild('childKey').once('value').then(snapshot => {
  // handle sorted data here
});
💻

Example

This example shows how to get a list of users sorted by their age child key from the Realtime Database.

javascript
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, query, orderByChild, get } from 'firebase/database';

const firebaseConfig = {
  // your config here
};

const app = initializeApp(firebaseConfig);
const db = getDatabase(app);

const usersRef = ref(db, 'users');
const usersByAgeQuery = query(usersRef, orderByChild('age'));

get(usersByAgeQuery).then(snapshot => {
  if (snapshot.exists()) {
    snapshot.forEach(childSnapshot => {
      const user = childSnapshot.val();
      console.log(user.name + ': ' + user.age);
    });
  } else {
    console.log('No users found');
  }
}).catch(error => {
  console.error(error);
});
Output
Alice: 22 Bob: 25 Charlie: 30
⚠️

Common Pitfalls

Common mistakes when using orderByChild include:

  • Using a child key that does not exist on all child nodes, which can cause unexpected ordering.
  • Not indexing the child key in Firebase rules, leading to slow queries or errors.
  • Trying to combine orderByChild with incompatible filters like orderByKey or orderByValue in the same query.

Always ensure your database rules index the child key you order by for best performance.

javascript
/* Wrong: Using orderByChild on a non-indexed key */
firebase.database().ref('users').orderByChild('nonIndexedKey').once('value')
  .catch(error => console.error('Indexing error:', error));

/* Right: Add indexing in rules and then query */
// In Firebase Realtime Database rules:
// {
//   "rules": {
//     "users": {
//       ".indexOn": ["age"]
//     }
//   }
// }

firebase.database().ref('users').orderByChild('age').once('value').then(snapshot => {
  // handle data
});
📊

Quick Reference

  • orderByChild('key'): Sorts data by the specified child key.
  • once('value'): Reads data once.
  • on('value'): Listens for data changes.
  • Ensure the child key is indexed in Firebase rules.
  • Works only with Realtime Database, not Firestore.

Key Takeaways

Use orderByChild('childKey') to sort data by a specific child key in Realtime Database.
Always index the child key in your Firebase rules for efficient queries.
orderByChild works only with Realtime Database, not Firestore.
Avoid using orderByChild with keys that are missing in some child nodes.
Use once('value') or on('value') to read or listen to the sorted data.