AWS SimpleDB and Auto Incrementing Primary Keys


Key
photo by: http://www.flickr.com/people/44532984@N00

I wanted some of my items in simpledb to have unique identifiers. SimpleDB does not provide this function natively because it’s not an RDBMS. Here’s my solution:

  1. Before inserting a new item, get the id from the last item in the domain with this select: $query = $sdb->select(“select id from `domain` where id is not null order by id desc limit 1”);
  2. Get the value of that query from the returned object: $last_id = $query->body->SelectResult->Item->Attribute->Value;
  3. Then, you add one (or however much you want) to it: $new_id = $last_id + 1;

I thought I had things pretty well taken care of at that point. Not so! During testing I found that any id subsequent to 9 became 10. No matter how many new items I added after the item with an id of 9, $new_id became 10.

The problem is that all data in simpledb are just strings. So when grabbing ids in the query “9” > “10”. 9 would be returned as the last id, and then 1 would be added to make it 10.

The answer: zero padding – AWS Docs. Adding zeros before a number/string that looks like a number will allow you to return the results you would expect: “0009” < “0010”.

See my more complete answer at stackoverflow.


Leave a Reply

Your email address will not be published. Required fields are marked *