DynamoDB: Get Last Inserted Item (Guide w/ Code Examples)

Provided by Rafal Wilinski
Last updated: October 23rd, 2026
DynamoDB has no table-wide insertion order. For items in one partition, store a sortable creation timestamp as sk and query in descending order. This retrieves the latest timestamp values, not the most recently modified items.
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, QueryCommand } from "@aws-sdk/lib-dynamodb"; const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({})); const items = []; let lastKey; do { const page = await ddb.send(new QueryCommand({ TableName: "Orders", KeyConditionExpression: "#pk = :pk", ExpressionAttributeNames: { "#pk": "pk" }, ExpressionAttributeValues: { ":pk": "CUSTOMER#123" }, ScanIndexForward: false, Limit: 1 - items.length, ExclusiveStartKey: lastKey, })); items.push(...(page.Items ?? [])); lastKey = page.LastEvaluatedKey; } while (items.length < 1 && lastKey && Object.keys(lastKey).length > 0); console.log(items);
Use uniform UTC timestamps, with a tie-breaker when two items may share a timestamp. For latest items across customers, design an appropriate index; avoid a single hot global key at high write rates.
Reference: AWS Query API. For related access patterns, see DynamoDB query examples.
Similar Code Examples
- DynamoDB: Not Begins With
- DynamoDB: Get Last 10 Records
- DynamoDB: Delete Table
- DynamoDB: Query Items
- DynamoDB: Attribute Not Null
- DynamoDB Get in Typescript
- DynamoDB: BatchGetItem
- DynamoDB: Get All Items
- DynamoDB: Get Unique Values
- DynamoDB: Query Group By
- DynamoDB: Get Random Item
- DynamoDB: Query Date Range
- DynamoDB: Bulk Insert
- DynamoDB: Query Greater Than
- DynamoDB: Batch Get
Dynobase is a Professional GUI Client for DynamoDB
Start your 7-day free trial today