Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Queries, Scans and Indexes

The Query Operation

Learn the DynamoDB Query operation: key condition expressions, sort key operators, ScanIndexForward, Limit, Select COUNT and why Query is the workhorse of every design.

GetItem fetches one item whose full key you know. Most real screens need more: a customer's orders, a device's latest readings, the comments on a post. For those, DynamoDB offers Query, which returns all items that share one partition key, optionally narrowed by a condition on the sort key. It is the workhorse operation: fast, cheap and independent of table size, because it jumps to one partition and reads a contiguous, sorted range.

What Query needs

Every Query has a KeyConditionExpression with:

  1. an equality condition on the partition key (mandatory), and
  2. optionally one condition on the sort key.
Terminal
aws dynamodb query \
  --table-name AppData \
  --key-condition-expression "PK = :pk AND begins_with(SK, :prefix)" \
  --expression-attribute-values '{
      ":pk":     {"S": "CUSTOMER#amina"},
      ":prefix": {"S": "ORDER#2026-03"}
  }'

The partition key must be an exact match. You cannot use begins_with, ranges or <> on it. If you need that, you need a different key design or an index.

Sort key conditions

Condition Meaning
SK = :v Exactly one item (a Query that returns at most one)
SK < :v, SK <= :v Everything before a value
SK > :v, SK >= :v Everything after a value
SK BETWEEN :a AND :b A closed range, inclusive at both ends
begins_with(SK, :prefix) All sort keys starting with a prefix

Because items in a partition are stored sorted by sort key, these conditions read only the matching range. This is why sort key design is half of DynamoDB modelling: choose sort key values so that the lookups you need become ranges or prefixes. Dates in ISO format (2026-03-14), zero-padded numbers and prefixes like ORDER# all sort and range correctly as strings.

flowchart LR
    subgraph "Partition CUSTOMER#amina, sorted by SK"
    A["ORDER#2026-02-11"] --> B["ORDER#2026-03-01"] --> C["ORDER#2026-03-14"] --> D["PROFILE"]
    end
    Q["begins_with(SK, 'ORDER#2026-03')"] -.-> B
    Q -.-> C

A prefix or range selects a contiguous slice.

Controlling the result

Parameter Effect
ScanIndexForward true (default) ascending by sort key, false descending
Limit Maximum items evaluated in this call (not necessarily returned if a filter is also used)
Select ALL_ATTRIBUTES (default), COUNT (only the number), SPECIFIC_ATTRIBUTES (with a projection)
ProjectionExpression Which attributes to return
ConsistentRead Strong consistency (not available on global secondary indexes)
ExclusiveStartKey Where to continue after a previous page

ScanIndexForward=false with Limit=1 is the classic "latest item" query: the newest order, the last reading, the most recent message.

Each call reads at most 1 MB. If more matching data exists, the response includes LastEvaluatedKey, and you pass it back as ExclusiveStartKey to continue. The next lesson covers pagination in detail.

The Python SDK

Python
from boto3.dynamodb.conditions import Key

response = table.query(
    KeyConditionExpression=Key("PK").eq("CUSTOMER#amina")
                           & Key("SK").begins_with("ORDER#2026-03"),
    ScanIndexForward=False,
    Limit=5,
)
orders = response["Items"]

Key(...) objects build the expression for you, which avoids string typos.

A Query engine you can run

This stand-in implements Query on a composite-key table: the key condition parser, sort order and Limit, Select=COUNT. It is a model of the semantics, not a client.

Python Stand-in: Query with key conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check the third result: it uses a ~ after the last date as an upper bound, a handy trick because ~ sorts after digits, so ORDER#2026-03-01~ includes every sort key that starts with ORDER#2026-03-01.

Time series: the latest N readings

A very common model: one partition per device (or per device and day) and a timestamp as the sort key.

Python Stand-in: latest readings and a time window

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Query cost

A Query is charged for the total size of all items read in the key range (rounded up to 4 KB per call, half for eventually consistent reads), not for the items returned. Projections and filters do not reduce it. So you design sort keys to make the range as tight as you need, and keep items small when they are read in bulk.

What Query cannot do

  • Query across several partition keys. Run one query per key, in parallel, and merge.
  • Order by anything other than the sort key. A different order needs an index.
  • Filter by a non-key attribute before reading. Filters run after the read (next lesson).
  • Return more than 1 MB per call without pagination.

Common mistakes

  • Using a filter where a sort key range would do. You pay for everything read.
  • Forgetting ScanIndexForward=false when the screen wants "newest first".
  • Wrong key attribute names in the expression: use ExpressionAttributeNames aliases for reserved ones.
  • Assuming Limit means "return this many". It limits evaluated items, which matters once filters are involved.
  • Ignoring LastEvaluatedKey and silently showing a truncated list.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is mandatory in a Query's KeyConditionExpression?

    The partition key must be matched exactly. The sort key condition is optional.
  2. 2. How do you fetch the single newest order in a partition sorted by date?

    Reading the sort key range in descending order and stopping after one item returns the newest.
  3. 3. What are you charged for in a Query?

    Capacity is based on the data read from the key range. Filters and projections do not reduce it.
  4. 4. Which sort key condition is NOT supported?

    Sort key conditions allow =, <, <=, >, >=, BETWEEN and begins_with, but not contains.

Summary

  • Query returns items that share a partition key, optionally narrowed by one sort key condition.
  • Sort key conditions are =, <, <=, >, >=, BETWEEN and begins_with; the partition key needs equality.
  • ScanIndexForward, Limit, Select and ProjectionExpression shape the result.
  • Capacity depends on the data read, not on what is returned.
  • Sort key design determines which questions Query can answer cheaply.

Next: Filters, Projections and Pagination