Intermediate6 min read

DynamoDB Key Condition Expressions

A key condition expression is the KeyConditionExpression you pass to a Query, the only part of the request DynamoDB uses to find items. Everything else (filters, projections) runs after the read is already metered.

What is a key condition expression in DynamoDB?

A key condition expression is the KeyConditionExpression on a Query that tells DynamoDB which items to read. The must be an equality (PK = :v); the takes one operator: =, <, <=, >, >=, BETWEEN, or begins_with. It decides what gets read and billed, unlike a filter.

  • The partition key is an address. DynamoDB hashes it to locate one partition, so it takes = and nothing else: no ranges, no begins_with, no IN.
  • It is not a filter. A FilterExpression only trims the result after you've paid for the read.
  • String and Binary sort keys are byte-ordered. Range operators compare them lexicographically, so the sort-key format decides which ranges you can query. A Number sort key compares numerically.

Values in these examples are : placeholders; the mechanics are in expression names and values.

Why the partition key is locked to equality

DynamoDB stores items by hashing the partition key to a physical partition. A hash gives you one location, not a range, so there's nothing to scan across.

That's why PK > :v or begins_with(PK, :v) are rejected outright. The engine can't answer "all partitions whose key starts with X" without reading the whole table, which is exactly the Scan it's built to avoid.

Coming from SQL, this feels backwards: WHERE id LIKE 'ticket%' is trivial in Postgres. In DynamoDB the partition key is an address, not a searchable column.

On a GSI with a multi-attribute key (up to four partition-key and four sort-key attributes), every partition-key attribute takes =, and the sort-key attributes chain left to right with only the last one taking a range (AWS: multi-attribute keys).

Sort-key operators

Within one partition, items are stored sorted by the sort key. That ordering is what range operators exploit: DynamoDB seeks to a position and reads forward.

OperatorReadsUse it for
SK = :vOne exact itemA specific child by its key
SK < / <= / > / >= :vOne open-ended slice"Everything after this point"
SK BETWEEN :a AND :bA closed range (inclusive)A bounded window, a date range
begins_with(SK, :p)A prefix sliceA type or hierarchy under the PK

There is no LIKE, no CONTAINS, no ENDS_WITH on the key. Substring and suffix matching aren't byte-ordered, so they'd force a full read, and the API won't let you.

For substrings, contains() works in a Scan filter, or in a Query filter on a non-key copy of the value; a Query filter can't reference the sort key.

For suffixes, store a reversed copy in its own attribute (RevEmail, e.g. moc.elpmaxe@ada) and make it the sort key of a GSI partitioned by tenant (or one shared bucket), and query begins_with(RevEmail, :rsuffix) with the suffix reversed (moc.elpmaxe@). (AWS: Key condition expressions)

A worked example: messages in a chat app

Say you're building channel-based chat. One table, partitioned by channel, sorted by message time. Original key schema:

  • Partition key ChannelRef: CH#{channelId}
  • Sort key PostedAt: an ISO-8601 timestamp, MSG#2026-06-23T14:05:00Z

The MSG# prefix keeps message rows sortable and distinct from any other row type you co-locate under the same channel, such as pinned messages under PIN#.

Load a channel's latest messages. Partition key plus the MSG# prefix, newest first:

KeyConditionExpression      ChannelRef = :ch AND begins_with(PostedAt, :msg)
ExpressionAttributeValues   { ":ch": { "S": "CH#general" }, ":msg": { "S": "MSG#" } }
ScanIndexForward            false

ScanIndexForward: false walks the sorted collection in reverse, the cheap way to get "most recent first" without sorting client-side. Leave out the prefix and the PIN# rows come back too, ahead of every message, because PIN# sorts after MSG#.

A specific day with begins_with. Because the timestamp is the sort key and it's stored as text, a date prefix is a clean slice:

KeyConditionExpression      ChannelRef = :ch AND begins_with(PostedAt, :day)
ExpressionAttributeValues   { ":ch": { "S": "CH#general" }, ":day": { "S": "MSG#2026-06-23" } }

That reads every message on 2026-06-23 and nothing else. DynamoDB seeks to the prefix and stops when it falls off the end. This only works because the prefix is a true left-anchor of a byte-sorted string. A whole hour works the same way (MSG#2026-06-23T14).

A precise window with BETWEEN. For "the messages from 14:15 to 14:45", no prefix fits, so use an inclusive range:

KeyConditionExpression      ChannelRef = :ch AND PostedAt BETWEEN :lo AND :hi
ExpressionAttributeValues   { ":ch": { "S": "CH#general" },
                              ":lo": { "S": "MSG#2026-06-23T14:15:00Z" },
                              ":hi": { "S": "MSG#2026-06-23T14:45:00Z" } }

BETWEEN is inclusive on both bounds, so pick your endpoints deliberately. An off-by-one here silently drops or doubles an edge message.

The DynamoDB expression builder assembles any of these with the ExpressionAttributeValues map filled in. The one below is preset to the day query above (ChannelRef = CH#general AND begins_with(PostedAt, MSG#2026-06-23)); change the operator to see the KeyConditionExpression update:

Build your request
Generated code
new QueryCommand({
  "TableName": "ChatMessages",
  "KeyConditionExpression": "#hashKey = :hashKeyValue AND begins_with(#rangeKey, :rangeKeyValue)",
  "ExpressionAttributeNames": {
    "#hashKey": "ChannelRef",
    "#rangeKey": "PostedAt"
  },
  "ExpressionAttributeValues": {
    ":hashKeyValue": {
      "S": "CH#general"
    },
    ":rangeKeyValue": {
      "S": "MSG#2026-06-23"
    }
  }
})

dynamodb-expression-builder is the open-source (MIT) library behind this tool.

The trap: confusing a key condition with a filter

The expensive mistake is reaching for FilterExpression to do a key's job. A Query filter can't even reference PostedAt: it's the sort key, and DynamoDB rejects a filter on a key attribute with a ValidationException.

So the workaround is to duplicate the date into a plain, non-key attribute (MessageDate) and filter on that instead:

KeyConditionExpression   ChannelRef = :ch
FilterExpression         begins_with(MessageDate, :day)

This looks equivalent to the begins_with key condition above and returns the same rows, but it reads the entire channel partition first, then discards everything outside the day. You're billed for the full read.

Filters never reduce read cost. They run after DynamoDB has metered the items, the same footgun as a filtered Scan. If a predicate can go in the key condition, it belongs there.

Fix it upstream. If an access pattern can't be expressed as one PK equality plus a sort-key range, that's a modeling signal: put the attribute you filter on into the sort key, or add an index keyed for the pattern.

Filtering strategies compares the options; GSI vs LSI and single-table design show how to lay the keys out.

See it in DynoTable

Run the same key condition against a real channel partition. The moment you set a partition-key value in the key pill, DynoTable issues a Query, so you load only that slice, not the whole table.

Pitfalls and next steps

  • Partition key is always =. For a range across partitions, add a GSI whose partition key is a small set of shard values (MSG#0 to MSG#9) and whose sort key is the value you range on, then query each shard and merge client-side (write sharding).
  • One sort-key condition per query. You can't AND two sort-key predicates (on a multi-attribute GSI key, equality on the leading sort-key attributes plus one range on the last). To combine a prefix with a range, put the prefix in both BETWEEN bounds, as the 14:15 to 14:45 window above does: the PIN# rows stay out.
  • Reserved words need aliases. A key named Timestamp or Name must use ExpressionAttributeNames (#ts), or the query errors; see expression names and values. (AWS: reserved words)
  • BETWEEN is inclusive. Both endpoints are matched, so design your bounds accordingly.

Once a Query reads the right slice, trim what it returns with projection expressions. Draft your key conditions in the expression builder, then try DynoTable and set the same condition in the key pills to see which slice it returns.

By Dmitriy · Updated