DynamoDB: Get Random Item (Guide w/ Code Examples)

Provided by Rafal Wilinski
Last updated: October 23rd, 2026
DynamoDB has no random-item API. Reservoir sampling can choose one item using constant memory, but it must scan the whole table and pay for every page read.
Install @aws-sdk/client-dynamodb and @aws-sdk/lib-dynamodb, use an ES module on a supported Node.js runtime, and configure an AWS Region and credentials. The examples use an existing Orders table with String keys pk and sk unless an index or timestamp key is described.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, ScanCommand } from "@aws-sdk/lib-dynamodb"; const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({})); let seen = 0; let chosen; let lastKey; do { const page = await ddb.send(new ScanCommand({ TableName: "Orders", ExclusiveStartKey: lastKey, })); for (const item of page.Items ?? []) { seen++; if (Math.random() < 1 / seen) chosen = item; } lastKey = page.LastEvaluatedKey; } while (lastKey && Object.keys(lastKey).length > 0); console.log(chosen ?? "Table is empty");
This is suitable for small offline samples, not a frequent production query. Concurrent changes mean the scan is not a uniform sample of a fixed snapshot. For repeated sampling, maintain a sampling index or sample an export.
Reference: AWS Scan API. For related access patterns, see DynamoDB query examples.
Similar Code Examples
- DynamoDB: GetItem
- DynamoDB: Bulk Insert
- DynamoDB: Delete Multiple Items in Javascript
- DynamoDB: Batch Get
- DynamoDB: Query KeyConditionExpression
- DynamoDB: Increment Counter
- DynamoDB Get in Typescript
- DynamoDB: Get Last Inserted Item
- DynamoDB: Attribute Not Null
- DynamoDB: Get Multiple Items
- DynamoDB: Get All Items
- DynamoDB: Delete All Items With Partition Key
- DynamoDB: Delete Table
- DynamoDB: Query Items
- DynamoDB: Query Ends With
Dynobase is a Professional GUI Client for DynamoDB
Start your 7-day free trial today