So I have a relatively simple system. A mobile client creates records in a sqlite database that I would like to have synced to a remote SQL server (that is shared with other mobile clients). So when I create a new record in the phone's sqlite table, I then push that change to my remote service through a RESTful API. The problem I'm having, is how do I order the primary keys so that there isn't collisions in the data (i.e. a record in the phone has the same primary key as a completely different record on the server). What is the usual "best practice for referencing the record on the client, and for referencing the same record on the server?
-
The over-arching idea, would be that the client acts as a cache for the web server, with changes being created in the client, then pushed to the web server – JoeCortopassi Jan 31 '12 at 19:47
3 Answers
You could use a GUID type of column for the primary key. SQL Server supports the type UNIQUEIDENTIFIER
SQLite supports the type GUID
as far as i know (otherwise your client app on the phone has to produce a GUID value). This should guarantee unique values on client and server.

- 24,869
- 6
- 50
- 66
GUID is a good choice but not very meaningful. It would be nice you could send a device ID + an incrementing identity value and/or a time
That way by looking at the records you could identify what device it came from and the sequence they occured.
Depending on your application this could be very useful information.

- 2,529
- 19
- 22
Few options, in order of my preference. Feel free to clarify in comments if these won't work for your situation:
Identify a natural key, or if one doesn't exist create an artificial one that uniquely identifies local data attributes. Note that an artificial key is different from a surrogate as explained here. Use this with a unique device ID to create composite primary key
Use the SQLite ROWID (surrogate key) and a unique device ID as a composite primary key
Use a global unique identifier for each row, beware of potential pitfalls documented here

- 17,112
- 7
- 57
- 80