Intermediate6 min read

DynamoDB Sort Key Strategies: 3 Patterns, When to Use Each

A DynamoDB primary key is a alone, or a partition key plus a sort key.

The partition key decides where an item lives; the sort key decides the order of items that share a partition key, and that order is what range reads in Query run on.

Coming from SQL, you'd add ORDER BY or an index after the fact. In DynamoDB you bake the order into the key up front, or you don't get it.

How do DynamoDB sort keys work?

A sort key orders the items under one partition key, so Query can read a range (>=, between, begins_with) instead of one item at a time. Strings compare by UTF-8 bytes and Numbers numerically.

Three patterns cover most designs: a sortable encoding, a composite prefix for hierarchy, and the read direction.

PatternUse it whenExample sort key
1. Sortable encodingYou read a range of times or numbersEVT#2026-06-23T09:12:04Z
2. Composite prefix (hierarchy)You read a whole sub-tree (a month, a type)EVENT#2026-06#01#login
3. Read directionYou need newest first as well as oldest firstsame key, ScanIndexForward = false
  • A String key's byte order must equal your read order. Use an ISO-8601 timestamp or a zero-padded number, never a raw UUID or 6/23/2026.
  • One composite key serves several access patterns. EVT#<timestamp> is a prefix and a range at once, with no GSI.
  • Direction costs nothing. Read newest first with ScanIndexForward = false instead of storing reversed values.

Why the sort key decides your range reads

Without a sort key, each partition key holds one item, and Query returns at most that item.

Add a sort key and the items sharing a partition key form an , stored in sort-key order, per the AWS core components guide.

Query uses that order through range conditions (>=, between), prefix matching (begins_with) and the ScanIndexForward direction flag. The sort key is the index you query inside a partition.

The order is byte order on the encoded value: Strings compare by UTF-8 bytes, Numbers numerically. For range reads to mean anything, that byte order has to match the order you want to read.

Strategy 1: make the sort key sortable

The most common mistake is a sort key with no useful order. A random UUID is unique, but "give me the last 20" is impossible because its byte order is arbitrary.

Keep the id for uniqueness and put a timestamp in front of it (EVT#<ISO-8601>#<uuid>). "Last 20" is then ScanIndexForward = false with Limit = 20.

For timestamps, use a format whose byte order is chronological: an ISO-8601 string or a zero-padded epoch. ISO-8601 sorts correctly as long as every value has the same precision and the same UTC Z offset.

Mix 14:05:11.250Z with 14:05:11Z and the millisecond value sorts first, because . (0x2E) comes before Z (0x5A).

Avoid formats like 6/23/2026: they sort wrong as soon as a day or month gains a digit (6/9/2026 lands after 6/23/2026).

If you sort on numbers (a version counter, a score), use the native Number type, so 42 sorts after 9 instead of before it.

If a number must live inside a composite String key, zero-pad it to a fixed width.

Strategy 2: composite sort keys for hierarchy

A sort key can encode a hierarchy by joining segments with a delimiter, most often #. One begins_with condition then selects a whole sub-tree:

SK
EVENT#2026-06#01#login
EVENT#2026-06#03#export
EVENT#2026-07#02#login

begins_with(SK, "EVENT#2026-06#") returns June's events; the broader begins_with(SK, "EVENT#") returns all of them.

Order the segments coarse to fine (year, month, day). Related items then sit next to each other, and a range read stays one Query instead of a scatter across the partition.

Strategy 3: control direction at read time

DynamoDB reads a collection in ascending sort-key order by default; set ScanIndexForward = false to read it newest first at the same cost, as the descending-order guide shows.

Don't store reversed timestamps to get descending reads.

The one exception is a key that mixes directions, such as score high-to-low with ties oldest first: there you store an inverted number for one segment, as in zero-padding sort keys.

Worked example: an actor-scoped audit log

Suppose you record timestamped events produced by actors (users, services, API keys) in a SaaS product, and you have two reads:

  1. The activity stream for one actor, newest event first.
  2. One actor's events within a time window (e.g. "everything between the two deploys"), for an investigation.

Both reads are scoped to a single actor, so the actor is the partition key and the event time is the sort key. Use generic key names so the same table can hold other entities later:

PKSKattributes
ACTOR#u_8814EVT#2026-06-23T09:12:04Zaction=login, ip, ua
ACTOR#u_8814EVT#2026-06-23T14:05:11Zaction=export, target
ACTOR#u_8814EVT#2026-06-24T08:40:55Zaction=login, ip, ua
ACTOR#svc_billingEVT#2026-06-23T00:00:00Zaction=invoice.run

The EVT# prefix plus an ISO-8601 timestamp gives a sortable sort key. Read 1 is Query PK = "ACTOR#u_8814" with ScanIndexForward = false. Read 2 narrows the same partition with a between condition on the sort key:

Query
  PK = "ACTOR#u_8814"
  AND SK BETWEEN "EVT#2026-06-23T00:00:00Z"
              AND "EVT#2026-06-23T23:59:59Z"

One collection, two access patterns, no GSI, because the sort key is both a prefix (EVT#) and a range (the timestamp).

Run the access patterns
Query PK = "ACTOR#u_8814"
ScanIndexForward = false

3 of 4 items read — one Query, one partition. The key condition filters before any data leaves it, so you pay only for the matches.

Base table, in stored order
#PKSKAttributes
3ACTOR#u_8814EVT#2026-06-23T09:12:04Zaction=login, ip, ua
2ACTOR#u_8814EVT#2026-06-23T14:05:11Zaction=export, target
1ACTOR#u_8814EVT#2026-06-24T08:40:55Zaction=login, ip, ua
ACTOR#svc_billingEVT#2026-06-23T00:00:00Zaction=invoice.run

The items and keys are this guide’s own example. Highlighted rows are what the one call above touches; the numbers show the order they come back in. “Items read” counts items, not read units — real billing rounds each read up to 4 KB blocks.

Watch the upper bound once keys carry a suffix (see the uniqueness pitfall below). EVT#2026-06-23T23:59:59Z#002 sorts after EVT#2026-06-23T23:59:59Z, so this BETWEEN silently drops it.

For a whole day, use begins_with(SK, "EVT#2026-06-23"). For any other window, end the upper bound with ~ ("EVT#2026-06-23T23:59:59Z~"), which sorts after every # suffix.

The DynamoDB Expression Builder generates the KeyConditionExpression, ExpressionAttributeNames and ExpressionAttributeValues for a begins_with condition on a String sort key. It offers between and the range operators on Number sort keys only.

Copy it into your SDK call instead of debugging reserved-word escaping at runtime.

Do it in DynoTable

Designing a sort key is iterative: write a few representative items, run the range query, and check the rows come back in the order you expect. Doing that against a live table in a GUI is quicker than a round trip through code.

Querying an actor's audit-log collection in DynoTable with a between condition on the sort key, results ordered newest-first.
Querying an actor's audit-log collection in DynoTable with a between condition on the sort key, results ordered newest-first.

Flip the sort direction and tighten the between bounds, and the grid shows the returned collection change without a line of code.

Pitfalls and next steps

  • Sort keys must be unique within a partition. If two events can share a timestamp, append a disambiguator (a sequence number or short id) so the composite stays unique, and size your BETWEEN upper bound for it as shown above.
  • A hot partition can't be sorted around. If one actor writes far more than the rest, split its partition key across N shards (ACTOR#u_8814#0 … #N-1), query each shard and merge by sort key. The hot partition guide covers how to pick the suffix.
  • A changing value doesn't belong in the base sort key. Key attributes can't be updated; see mutable sort keys for the GSI pattern.
  • A second sort order needs a second index. To order the same items differently (by event type, say), add a GSI with a different sort key, weighing the local vs global secondary index trade-offs.
  • Don't Scan to "sort later". Sorting client-side after a Scan reads the whole table; that's the Scan footgun.

More on how items group under one key in item collections.

Once the key condition is right, try DynoTable to flip one query between ascending and descending and check your sort-key strategy against real data before it ships.

By Dmitriy · Updated