How to Query a DynamoDB Table: Syntax and Examples
To query a DynamoDB table, use the
Query operation specifying the TableName and a KeyConditionExpression to filter items by their partition key. You can also add optional filters and specify attributes to return. This lets you efficiently retrieve items matching your criteria.Syntax
The basic syntax for querying a DynamoDB table involves specifying the table name, a key condition expression to filter by partition key, and optionally a filter expression for other attributes. You can also set parameters like ProjectionExpression to select specific attributes and Limit to control the number of results.
- TableName: The name of your DynamoDB table.
- KeyConditionExpression: Expression to specify the partition key and optionally sort key conditions.
- ExpressionAttributeValues: Values used in the expressions.
- FilterExpression: Optional filter for non-key attributes.
- ProjectionExpression: Attributes to return.
javascript
const params = { TableName: 'YourTableName', KeyConditionExpression: 'PartitionKeyName = :pkvalue', ExpressionAttributeValues: { ':pkvalue': { S: 'PartitionKeyValue' } }, ProjectionExpression: 'Attribute1, Attribute2', Limit: 10 }; const command = new QueryCommand(params); const data = await client.send(command);
Example
This example shows how to query a DynamoDB table named Books to find all items where the partition key Author equals 'Alice'. It returns the Title and Year attributes of the matching books.
javascript
import { DynamoDBClient, QueryCommand } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({ region: "us-east-1" }); async function queryBooksByAuthor() { const params = { TableName: "Books", KeyConditionExpression: "Author = :author", ExpressionAttributeValues: { ":author": { S: "Alice" } }, ProjectionExpression: "Title, Year" }; try { const command = new QueryCommand(params); const data = await client.send(command); console.log("Query succeeded:", data.Items); } catch (err) { console.error("Query failed:", err); } } queryBooksByAuthor();
Output
Query succeeded: [
{ Title: { S: "Wonderland Adventures" }, Year: { N: "2018" } },
{ Title: { S: "Through the Looking Glass" }, Year: { N: "2020" } }
]
Common Pitfalls
Common mistakes when querying DynamoDB include:
- Using
Scaninstead ofQueryfor key-based lookups, which is less efficient. - Not specifying the partition key in
KeyConditionExpression, which causes errors. - Confusing
FilterExpressionwithKeyConditionExpression; filters apply after fetching data and do not reduce read capacity usage. - Forgetting to use
ExpressionAttributeValuesplaceholders for values in expressions.
Example of a wrong query missing partition key:
javascript
const wrongParams = { TableName: 'Books', KeyConditionExpression: 'Year = :year', // Wrong: Year is not a key ExpressionAttributeValues: { ':year': { N: '2020' } } }; // Correct way: const correctParams = { TableName: 'Books', KeyConditionExpression: 'Author = :author', ExpressionAttributeValues: { ':author': { S: 'Alice' } } };
Quick Reference
| Parameter | Description | Required |
|---|---|---|
| TableName | Name of the DynamoDB table | Yes |
| KeyConditionExpression | Expression to specify partition key and optional sort key | Yes |
| ExpressionAttributeValues | Values for placeholders in expressions | Yes |
| FilterExpression | Optional filter for non-key attributes | No |
| ProjectionExpression | Attributes to return | No |
| Limit | Maximum number of items to return | No |
Key Takeaways
Always specify the partition key in KeyConditionExpression to query efficiently.
Use ExpressionAttributeValues to safely pass values in your query expressions.
FilterExpression filters results after query and does not reduce read capacity usage.
Query returns only items matching the key condition, making it faster than Scan.
Use ProjectionExpression to return only needed attributes and reduce data transfer.