Home > Net >  Guaranteed order of fetched data from Firebase Realtime Database
Guaranteed order of fetched data from Firebase Realtime Database

Time:12-05

What is the order of data when I fetch from my Firebase Realtime Database without using any orderBy() methods?

If I use get(), is it always 100% guaranteed that the data I will get are sorted from oldest to the newest, or will the keys be in lexicographical order?

CodePudding user response:

What is the order of data when I fetch from my Firebase Realtime Database without using any orderBy methods?

If you are looking to have your elements ordered even if you don't use a call to orderBy(), then you should use the pushed IDs provided by the DatabaseReference#push() method. These pushed IDs aren't actually timestamps but they contain a time component. As Michael Lehenbauer mentioned in this blog article:

Push IDs are string identifiers that are generated client-side. They are a combination of a timestamp and some random bits. The timestamp ensures they are ordered chronologically, and the random bits ensure that each ID is unique, even if thousands of people are creating push IDs at the same time.

And to answer your second question:

If I use the get(), is it always 100% guaranteed that the data I will get is sorted from oldest to the newest or will it be in lexicographical order?

It doesn't matter if you add a ValueEventListener or ChildEventListener or even if you call Query#get(), the results will be ordered in the same way.

However, if you need to explicitly have an order according to a time component, then you should add a property of type "timestamp", as explained in my answer from the following post:

If you want to reverse the order please check the following answer:

  • Related