Skip to content
Quest 11Advanced16 min

Finding the Strongest (Sort Keys)

The Johto region is filled with powerful trainers! To become the best, you need to find the strongest Pokémon. By creating a second GSI with a Sort Key (Type1-Attack-Index), we can have DynamoDB order our query results automatically.
Start the lesson

What you'll learn

  • Sort Keys automatically organize data within a Partition Key.
  • Use ScanIndexForward to control ascending or descending order.
  • A KeyConditionExpression needs an equality test on the partition key (Type1 = :type); the sort key can add =, <, <=, >, >=, BETWEEN, or begins_with (e.g. Attack >= :min).

Section 01

Sort Keys in GSIs

If we set Type1 as the Partition Key and Attack as the Sort Key, DynamoDB automatically keeps our Water-type Pokémon sorted by their Attack power! (Store Attack as a Number: as a String, "105" would sort before "65".) When querying, you can easily fetch the strongest Water Pokémon by reading the items in reverse order.

Query with Sort KeyJavaScript
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, QueryCommand } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({ region: "ap-south-1" });
const docClient = DynamoDBDocumentClient.from(client);

await docClient.send(new QueryCommand({
  TableName: "JohtoPokemon",
  IndexName: "Type1-Attack-Index",
  KeyConditionExpression: "Type1 = :type",
  ExpressionAttributeValues: { ":type": "water" },
  ScanIndexForward: false // false means descending order (highest attack first!)
}));
Your appAWS SDK v3DynamoDBtableP0P1P2P3CONSUMED0

Ready · 5 steps · Wick

This animation plays when you scroll to it. Press Play to start it now.

All steps as text
  1. Your app sends Query to the Type1-Attack-Index index with Type1 = "fire". ScanIndexForward left at its default (true).
  2. DynamoDB hashes "Fire" to b476151f, which routes the request to partition P3.
  3. P3 returns Cyndaquil (52), Typhlosion (84), Ho-Oh (130).
  4. This call consumed 0.5 RCU.
  5. DynamoDB responds with success: ascending order, so the weakest comes back first.

Practice

Your turn

You want the strongest Fire types first. The GSI Type1-Attack-Index already sorts by Attack — flip the scan direction so the highest Attack comes back at the top.
Add ScanIndexForward: false to return results in descending Attack order.
Tab inserts two spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the code.
Simulated — no AWS calls

Check

Check your understanding

Quick Quiz · one question, as many tries as you need.

How do you fetch items in descending order (highest to lowest) using a Query in DynamoDB?

Choose one answer.