Getting the newest entry from Azure Table Storage

Sometimes, all you want is to be able to quickly get to the last value of a sensor, or the freshest product in your Azure Table without having to do complex artsy queries to achieve that result. Trouble is, querying against Azure tables does not give you a Last() option, so we have to get sneaky!

Turns out, Azure Tables are ordered by their RowKeys, which are indexed, so we’re in luck. The challenge is that you need to input a string that is ever descending in value, so that the newest elements are always fresh on top. Here’s a trick to do just that:

DateTime to the rescue!

The simple trick is to use the DateTime.MaxValue property, which gives us the highest possible value of DateTime. Then we convert that to ticks in order to get a huge number. Subtract the DateTime.Now value from that, and what we end up with is a large enough number to use as a RowKey that is “ever descending”:

image

The string formatting is just to populate the value with 19 digits.

The RowKeys are now stored in an ever descending order, here’s a snip of a table I’m storing some sensor values in (using Azure Storage Explorer):

image

On the reading side, you can now simply execute your query knowing that the order of the returned values will always have the first item as the last inserted:

image

 

Learn it, love it, live it!

About digitaldias

Software Engineer during the day, photographer, videographer and gamer in the evening. Also a father of 3. Pedro has a strong passion for technology, and gladly shares his findings with enthusiasm.

View all posts by digitaldias →

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.