Introduction
We order query results to see data in a specific sequence, like oldest to newest or highest to lowest.
Jump into concepts and practice - no test required
We order query results to see data in a specific sequence, like oldest to newest or highest to lowest.
const QueryInput = {
TableName: 'YourTableName',
KeyConditionExpression: 'PartitionKeyName = :value',
ExpressionAttributeValues: {
':value': { S: 'YourPartitionKeyValue' }
},
ScanIndexForward: true_or_false
};ScanIndexForward controls order: true means ascending, false means descending.
Ordering works only on the sort key of the table or index.
ScanIndexForward: true
ScanIndexForward: false
This query fetches orders for customer 'C123' and shows the order dates from newest to oldest.
const { DynamoDBClient, QueryCommand } = require('@aws-sdk/client-dynamodb');
const client = new DynamoDBClient({ region: 'us-east-1' });
async function runQuery() {
const params = {
TableName: 'Orders',
KeyConditionExpression: 'CustomerId = :cid',
ExpressionAttributeValues: {
':cid': { S: 'C123' }
},
ScanIndexForward: false
};
const command = new QueryCommand(params);
const data = await client.send(command);
return data.Items.map(item => item.OrderDate.S);
}
runQuery().then(console.log).catch(console.error);If you don't set ScanIndexForward, the default is true (ascending order).
Ordering only applies when you query by partition key and have a sort key defined.
Use ScanIndexForward to control ascending or descending order.
Ordering works on the sort key, not the partition key.
Default order is ascending if you don't specify.
ScanIndexForward controls ascending (true) or descending (false) order.ScanIndexForward -> Option COrders with results in descending order on the sort key OrderDate?ScanIndexForward must be set to false.ScanIndexForward: false correctly; other options use invalid or wrong parameters.UserId and sort key Timestamp, what will be the order of results returned by this query?client.query({
TableName: 'UserActivity',
KeyConditionExpression: 'UserId = :uid',
ExpressionAttributeValues: { ':uid': 'user123' },
ScanIndexForward: false
})ScanIndexForward: false returns results in descending order of the sort key.Timestamp, so results are ordered newest to oldest.client.query({
TableName: 'Sales',
KeyConditionExpression: 'StoreId = :sid',
ExpressionAttributeValues: { ':sid': 'store1' },
ScanIndexForward: 'false'
})cust123 from a DynamoDB table Orders with partition key CustomerId and sort key OrderDate. Which query will correctly return these orders in descending order by OrderDate?ScanIndexForward: false to get descending order by OrderDate.Limit: 5 to get only the top 5 recent orders.