Amazon DynamoDB Tutorial 0/30 lessons ~6 min read Lesson 14

    Query vs Scan: Reading Data Efficiently

    DynamoDB has two ways to read many items.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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, and begins_with.
    • Results are sorted by sort key; ScanIndexForward: false returns them in descending order.
    • Each request returns at most 1 MB of data read (before filters) and a LastEvaluatedKey when 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; Segment and TotalSegments split it across workers for parallel exports and migrations.

    Informative example

    Same question, two costs — list a customer's orders from 2026:

    ts
    import { QueryCommand, ScanCommand } from "@aws-sdk/lib-dynamodb";
    import { ddb, TABLE } from "./ddb";
    // Efficient: reads only this customer's 2026 orders
    const 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 filters
    const 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).

    ts
    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 ReturnConsumedCapacity in 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.

    2 questions
    1BeginnerQuestionDoes a FilterExpression reduce read cost?+

    Answer

    No. Filters run after items are read, so you pay for everything the Query or Scan read (up to 1 MB per page). Filters only reduce the data sent back to the client.
    2IntermediateQuestionWhen is a Scan acceptable?+

    Answer

    Small tables, one-off maintenance jobs and migrations, or full exports — ideally with parallel segments, rate limiting, and off-peak scheduling. For analytics, Export to S3 is usually better.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.