0
0
AWScloud~5 mins

Scan vs query performance in AWS - CLI Comparison

Choose your learning style9 modes available
Introduction
When you want to find data in a database, you can either look through everything or search smartly. Scanning checks every item, which can be slow. Querying looks only where it needs to, making it faster and cheaper.
When you need to find a few specific items quickly in a large database table.
When you want to avoid reading the whole table to save time and cost.
When you have a known key or index to search by in your data.
When you want to get all items regardless of keys, but understand it will be slower.
When you want to filter data but don't have a key to query on.
Commands
This command scans the entire MusicCollection table and returns up to 5 items. It reads all data, which can be slow for big tables.
Terminal
aws dynamodb scan --table-name MusicCollection --limit 5
Expected OutputExpected
{ "Items": [ {"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}}, {"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Happy Day"}}, {"Artist": {"S": "The Wild Sax Band"}, "SongTitle": {"S": "Take Five"}}, {"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "I Want It That Way"}}, {"Artist": {"S": "Acme Band"}, "SongTitle": {"S": "Another One Bites The Dust"}} ], "Count": 5, "ScannedCount": 5 }
--table-name - Specifies the DynamoDB table to scan
--limit - Limits the number of items returned
This command queries the MusicCollection table for items where the Artist is 'No One You Know'. It reads only matching items, making it faster and cheaper.
Terminal
aws dynamodb query --table-name MusicCollection --key-condition-expression "Artist = :artist" --expression-attribute-values '{":artist":{"S":"No One You Know"}}' --limit 5
Expected OutputExpected
{ "Items": [ {"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "Call Me Today"}}, {"Artist": {"S": "No One You Know"}, "SongTitle": {"S": "I Want It That Way"}} ], "Count": 2, "ScannedCount": 2 }
--key-condition-expression - Defines the condition to find matching keys
--expression-attribute-values - Provides values for the condition placeholders
--limit - Limits the number of items returned
Key Concept

If you remember nothing else, remember: querying uses keys to find data fast, scanning reads everything and is slower.

Common Mistakes
Using scan when you can use query with a key
Scan reads the whole table, wasting time and money when a query could find data faster.
Use query with key conditions whenever possible to improve performance.
Trying to query without specifying key conditions
Query requires a key condition; without it, the command fails or returns no data.
Always provide a key condition expression when using query.
Summary
Scan reads every item in the table and is slower and more expensive.
Query uses keys to find matching items quickly and efficiently.
Use query when you know the key; use scan only when you need to read all data.