0
0
DynamoDBquery~5 mins

Query result ordering (ascending, descending) in DynamoDB

Choose your learning style9 modes available
Introduction

We order query results to see data in a specific sequence, like oldest to newest or highest to lowest.

When you want to see your recent purchases first.
When you need to list events from earliest to latest.
When sorting scores from highest to lowest in a game.
When displaying messages in a chat app by newest first.
Syntax
DynamoDB
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.

Examples
Returns results in ascending order (smallest to largest).
DynamoDB
ScanIndexForward: true
Returns results in descending order (largest to smallest).
DynamoDB
ScanIndexForward: false
Sample Program

This query fetches orders for customer 'C123' and shows the order dates from newest to oldest.

DynamoDB
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);
OutputSuccess
Important Notes

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.

Summary

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.