SimpleDB: Finally Supports Sorting
Jul 30th, 2008 by James Murty
The latest version of Amazon’s SimpleDB service is available, and happily it now allows for sorting of query results. This highly-anticipated feature will make the service much more useful.
Sorting still suffers from some limitations: you can only sort by a single attribute, you cannot perform sorting in queries that contain
or
predicates, and the attribute against which you are sorting must be present in a query predicate. However, it is still a massive improvement on sorting query results in your own client code.
For example, given the following SimpleDB query that finds historic stock records for a given time period:
With the new
operator, you can now instruct the service to return the results in reverse (descending) date order like so:
Although you can only sort by an attribute that is also mentioned in a predicate, you can easily work around this restriction by including a
predicate for that criteria, which will always evaluate to true. Here is a query to return stock records sorted according to the closing price, from lowest to highest:
The SimpleDB update also includes some other new features, such as a new
operator and support for 10 predicates per query instead of 5, but I think it is the sorting that will have the most impact.
Hi James,
Thanks for this post. I’m trying to use the sort feature and get the following error: “The specified query expression syntax is not valid.” Here’s the query I’m sending: ['tags' = 'shirt'] sort ‘category’ desc. I appreciate any help you can provide. Thanks.
Hello again James,
It appears that in order to sort on an attribute you have to have that attribute in the query string, as you have in your example.
Hi Robert,
You are correct: in order to sort on an attribute you must first use that attribute in a query condition (aka predicate). It is unfortunate that the SimpleDB error message isn’t more descriptive if you forget to do this.