15

I was wondering if we could create auto increment ID's(Keys) in Firebase like we have in SQL!

I was wanting to create a structure like this

rules:
  Line1:
    1: Smith
    2: Alex
    3: Hello
  Line2:
    1: Brown
    2: Michael

So lets say if I want to add "Erik" to Line 1 it should do it like this

Line1:
    1: Smith
    2: Alex
    3: Hello
    4: Erik

Is it possible have structure like that?

I do know we have

push()

and

childByAutoId()

but this does not fit for my problem. I am working with Swift iOS just.

AL.
  • 36,815
  • 10
  • 142
  • 281
Neel Patel
  • 163
  • 1
  • 1
  • 9

1 Answers1

21

Such sequential keys inherently limit the scalability of a multi-user distributed system that also needs to deal with a lack of connectivity. That's one of the reasons why Firebase doesn't support them.

Instead Firebase has its own key type, called push IDs. Like the sequence you're looking for these are monotonously increasing, and they are also guaranteed to be unique. But the big difference is that push IDs, unlike the sequence numbers of most SQL databases, can be determined client side.

For more information on arrays (which are similar to sequences) in Firebase, see this blog post: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html.

For more information on Firebase's push IDs, see this blog post: https://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html

If you still decide that you must use sequential IDs, have a look at Kato's implementation of that here: http://jsfiddle.net/katowulf/5ESSp/. The core of this is keeping a counter property in the database with the current highest sequence number, and then using a transaction to update that.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for your answer, so I can basically use "push()" to create ordered numbers instead of this "1 : name 2: Name" it would work like this " 'pushid1': Name 'pushid2': name'? – Neel Patel Sep 16 '16 at 16:11
  • 1
    If you want a chronologically ordered collection of children in Firebase, it is indeed common to use push. – Frank van Puffelen Sep 16 '16 at 23:54
  • 1
    @FrankvanPuffelen check this link on the sequence number, they call it 'increment'. https://firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html Is it sequence number right? – BIS Tech Dec 10 '19 at 16:07
  • That blog is for Firestore, while this 3+ year old answer is about Realtime Database. Also note that an `increment` operation is not yet a full sequence operation. To build a sequence, you need all client incrementing the same location, which is a throughput limit for both Realtime Database and (even more) Firestore. – Frank van Puffelen Dec 10 '19 at 16:50