Introduction
We want to find data quickly and efficiently in DynamoDB. Understanding the difference between Scan and Query helps us choose the faster way.
Jump into concepts and practice - no test required
We want to find data quickly and efficiently in DynamoDB. Understanding the difference between Scan and Query helps us choose the faster way.
Query:
Use KeyConditionExpression to specify the key.
Optionally use FilterExpression to narrow results.
Scan:
Reads every item in the table.
Optionally use FilterExpression to narrow results after reading.Query is faster because it looks only at items with matching keys.
Scan reads the whole table, so it is slower and costs more.
Query example: aws dynamodb query \ --table-name Music \ --key-condition-expression "Artist = :artist" \ --expression-attribute-values '{":artist":{"S":"No One You Know"}}'
Scan example: aws dynamodb scan \ --table-name Music \ --filter-expression "Genre = :genre" \ --expression-attribute-values '{":genre":{"S":"Rock"}}'
The Query example uses the Artist key to find matching songs fast.
The Scan example reads all songs and then filters, which takes more time.
SELECT * FROM Music WHERE Artist = 'No One You Know'; -- Query example -- This returns only songs by 'No One You Know' quickly -- Scan example (conceptual): -- Scan the whole Music table and filter Genre = 'Rock' -- This is slower and reads all items
Query uses the primary key or index to find data fast.
Scan reads every item, so it is slower and costs more.
Always prefer Query when you can specify the key.
Query is fast and efficient for known keys.
Scan reads the whole table and is slower.
Use Query to save time and money whenever possible.
dynamoDbClient.scan({ TableName: 'MyTable' })dynamoDbClient.query({ TableName: 'MyTable', KeyConditionExpression: '#pk = :pk', ExpressionAttributeNames: { '#pk': 'PartitionKey' }, ExpressionAttributeValues: { ':pk': '123' } })const params = { TableName: 'MyTable', KeyConditionExpression: 'PartitionKey = :pk', ExpressionAttributeValues: { ':pk': '123' } };
const data = await dynamoDbClient.query(params);