Query vs Scan: Reading Data Efficiently
DynamoDB has two ways to read many items.
Introduction
DynamoDB has two ways to read many items. Query reads one item collection — items with a single partition key value — optionally narrowed by a sort-key condition. Scan reads every item in the table or index. Both read up to 1 MB per request and charge for every item they read, so the difference in cost grows with table size.
Purpose of this lesson
You will learn exactly what each operation reads and charges for, how key conditions differ from filters, and when a parallel Scan is the right tool.
Understanding the topic
Key facts:
- Query requires an equality condition on the partition key; the sort key supports
=,<,<=,>,>=,BETWEEN, andbegins_with. - Results are sorted by sort key;
ScanIndexForward: falsereturns them in descending order. - Each request returns at most 1 MB of data read (before filters) and a
LastEvaluatedKeywhen there is more. - Capacity is charged on the data read, rounded up per 4 KB for reads — not on the data returned after a filter.
- Scan reads the whole table;
SegmentandTotalSegmentssplit it across workers for parallel exports and migrations.
Informative example
Same question, two costs — list a customer's orders from 2026:
import { QueryCommand, ScanCommand } from "@aws-sdk/lib-dynamodb";import { ddb, TABLE } from "./ddb";// Efficient: reads only this customer's 2026 ordersconst query = await ddb.send(new QueryCommand({TableName: TABLE,KeyConditionExpression: "PK = :pk AND begins_with(SK, :year)",ExpressionAttributeValues: { ":pk": "CUSTOMER#c1", ":year": "ORDER#2026" },ReturnConsumedCapacity: "TOTAL",}));// Expensive: reads every item in the table, then filtersconst scan = await ddb.send(new ScanCommand({TableName: TABLE,FilterExpression: "PK = :pk AND begins_with(SK, :year)",ExpressionAttributeValues: { ":pk": "CUSTOMER#c1", ":year": "ORDER#2026" },ReturnConsumedCapacity: "TOTAL",}));console.log("query RCU", query.ConsumedCapacity?.CapacityUnits, "items", query.Count);console.log("scan RCU", scan.ConsumedCapacity?.CapacityUnits, "scanned", scan.ScannedCount, "items", scan.Count);
Both return the same items, but the Scan's consumed capacity and ScannedCount grow with the whole table. ReturnConsumedCapacity is the fastest way to see the cost of a request during development.
Useful templates
Parallel Scan for a one-off export
For large exports prefer the managed Export to S3 feature (it needs point-in-time recovery and does not consume table capacity).
import { ScanCommand } from "@aws-sdk/lib-dynamodb";import { ddb, TABLE } from "./ddb";async function scanSegment(segment: number, totalSegments: number) {let ExclusiveStartKey: Record<string, unknown> | undefined;let count = 0;do {const page = await ddb.send(new ScanCommand({TableName: TABLE, Segment: segment, TotalSegments: totalSegments, ExclusiveStartKey,}));count += page.Count ?? 0;ExclusiveStartKey = page.LastEvaluatedKey;} while (ExclusiveStartKey);return count;}const counts = await Promise.all([0, 1, 2, 3].map((s) => scanSegment(s, 4)));console.log("total items", counts.reduce((a, b) => a + b, 0));
Best practices
- Design keys so hot paths use GetItem or Query.
- Use
ReturnConsumedCapacityin tests to catch accidental Scans. - Use Export to S3 instead of Scan for analytics and backfills when possible.
Common mistakes
- Using Scan with a FilterExpression as a substitute for a missing index.
- Assuming a Query returns all results — always handle
LastEvaluatedKey. - Running an unthrottled parallel Scan against a production table during peak hours.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionDoes a FilterExpression reduce read cost?+
Answer
2IntermediateQuestionWhen is a Scan acceptable?+
Answer
Hands-on exercise
Hands-on: load 500 items for 50 customers into ShopTable. Compare ConsumedCapacity and ScannedCount for a Query on one customer and an equivalent filtered Scan. Write down the ratio.
Summary
Query reads one item collection with key conditions; Scan reads everything. Both page at 1 MB and charge for data read, so design keys for Query and keep Scan for maintenance.