AskHandle

AskHandle Blog

How Do I Query DynamoDB with Multiple Conditions in Node.js?

December 9, 2025Elise Taylor3 min read

How Do I Query DynamoDB with Multiple Conditions in Node.js?

Querying DynamoDB with multiple conditions is a common task when building applications with Node.js. This article explains different methods to implement complex queries and shows you practical examples to handle various query scenarios.

Basic Query Structure

When you want to search for items in DynamoDB using multiple conditions, you'll need to use the query operation. The query operation lets you search for items based on primary key values and optional sort key conditions. Here's a simple example:

javascript
1const params = {
2  TableName: 'Users',
3  KeyConditionExpression: 'userId = :uid AND createdAt > :date',
4  ExpressionAttributeValues: {
5    ':uid': '12345',
6    ':date': '2023-01-01'
7  }
8};
9
10const result = await dynamodb.query(params).promise();

Using Filter Expressions

Sometimes you need to filter results based on non-key attributes. You can add a FilterExpression to your query parameters. Keep in mind that filter expressions are applied after the query runs, which means you still pay for reading all matching items:

javascript
1const params = {
2  TableName: 'Users',
3  KeyConditionExpression: 'userId = :uid',
4  FilterExpression: 'age > :minAge AND status = :active',
5  ExpressionAttributeValues: {
6    ':uid': '12345',
7    ':minAge': 21,
8    ':active': true
9  }
10};

Combining Multiple Conditions

You can combine multiple conditions using AND and OR operators in your expressions. Here's how to structure more complex queries:

javascript
1const params = {
2  TableName: 'Orders',
3  KeyConditionExpression: 'customerId = :cid AND orderDate BETWEEN :start AND :end',
4  FilterExpression: '(status = :status1 OR status = :status2) AND total > :minTotal',
5  ExpressionAttributeValues: {
6    ':cid': 'C123',
7    ':start': '2023-01-01',
8    ':end': '2023-12-31',
9    ':status1': 'shipped',
10    ':status2': 'delivered',
11    ':minTotal': 100
12  }
13};

Performance Considerations

When working with multiple conditions, consider these performance tips:

  1. Use KeyConditionExpression for the most selective conditions to reduce the amount of data scanned.
  2. Place the most selective conditions first in FilterExpression to fail fast.
  3. Create secondary indexes for frequently queried attributes to improve query efficiency.

Error Handling

Proper error handling is crucial when querying with multiple conditions. Here's a practical approach:

javascript
1async function queryWithConditions(params) {
2  try {
3    const result = await dynamodb.query(params).promise();
4    return result.Items;
5  } catch (error) {
6    if (error.code === 'ValidationException') {
7      throw new Error('Invalid query parameters: ' + error.message);
8    }
9    if (error.code === 'ResourceNotFoundException') {
10      throw new Error('Table not found');
11    }
12    throw error;
13  }
14}

Pagination

When dealing with large result sets, implement pagination to manage your data efficiently:

javascript
1async function queryWithPagination(params, limit = 100) {
2  const items = [];
3  let lastKey = null;
4  
5  do {
6    if (lastKey) {
7      params.ExclusiveStartKey = lastKey;
8    }
9    params.Limit = limit;
10    
11    const response = await dynamodb.query(params).promise();
12    items.push(...response.Items);
13    lastKey = response.LastEvaluatedKey;
14  } while (lastKey);
15  
16  return items;
17}

Best Practices

Following these practices will help you write better queries:

  1. Use consistent naming for expression attributes
  2. Break complex queries into smaller, manageable functions
  3. Cache frequently accessed query results
  4. Monitor query performance using CloudWatch metrics
  5. Test queries with different data volumes

Writing efficient queries with multiple conditions requires careful planning of your data model and thorough testing. Start with simple queries and gradually add complexity as needed. Make sure to monitor your application's performance and adjust your query patterns based on real usage data.