Amazon DynamoDB Fundamentals: Tables, Keys, Items and CRUD Operations with the SDK

AWS Developer Associate 50 min min read Updated: Nov 17, 2026 Beginner
Amazon DynamoDB Fundamentals: Tables, Keys, Items and CRUD Operations with the SDK
Beginner Topic 1 of 3

What DynamoDB Is

Amazon DynamoDB is a serverless NoSQL key-value and document database. It gives single-digit millisecond reads and writes at any scale, replicates data across three AZs, and has no servers, patching or capacity planning in on-demand mode.

Data Model

TermMeaning
TableCollection of items. There is no fixed schema except the key
ItemOne record, up to 400 KB
AttributeA field. Types: scalar (S string, N number, B binary, BOOL, NULL), set (SS, NS, BS), document (L list, M map)
Partition key (hash key)Required. DynamoDB hashes it to choose the partition where data lives
Sort key (range key)Optional. Items with the same partition key are stored sorted by it
Primary keyEither the partition key alone, or partition key + sort key. Must be unique per item
text Table: Orders PK = customerId (HASH) SK = orderId (RANGE) customerId orderId status total items C-100 2026-11-01#9001 SHIPPED 499 [...] C-100 2026-11-12#9002 PENDING 129 [...] C-200 2026-11-05#9003 DELIVERED 899 [...] Query "all orders of C-100 in November" = one partition, a range on the sort key (fast)

Create a Table

bash aws dynamodb create-table --table-name Orders \ --attribute-definitions AttributeName=customerId,AttributeType=S AttributeName=orderId,AttributeType=S \ --key-schema AttributeName=customerId,KeyType=HASH AttributeName=orderId,KeyType=RANGE \ --billing-mode PAY_PER_REQUEST

You declare only the key attributes. Other attributes are free-form.

CRUD with boto3 (Resource API)

python import boto3 from decimal import Decimal from boto3.dynamodb.conditions import Key, Attr table = boto3.resource("dynamodb").Table("Orders") # Create or replace table.put_item(Item={"customerId": "C-100", "orderId": "2026-11-12#9002", "status": "PENDING", "total": Decimal("129.50"), "tags": {"gift", "express"}}) # Read one item by full key r = table.get_item(Key={"customerId": "C-100", "orderId": "2026-11-12#9002"}, ConsistentRead=True) item = r.get("Item") # None if missing # Update only some attributes table.update_item( Key={"customerId": "C-100", "orderId": "2026-11-12#9002"}, UpdateExpression="SET #s = :new, updatedAt = :t ADD attempts :one", ExpressionAttributeNames={"#s": "status"}, # status is a reserved word ExpressionAttributeValues={":new": "SHIPPED", ":t": "2026-11-13T09:00:00Z", ":one": 1}, ReturnValues="UPDATED_NEW") # Delete table.delete_item(Key={"customerId": "C-100", "orderId": "2026-11-12#9002"})
  • Use Decimal for numbers in Python (floats are rejected)
  • put_item replaces the whole item if the key exists. update_item changes only the named attributes and creates the item if it does not exist (an upsert)
  • Reserved words (status, name, date...) need ExpressionAttributeNames (#s). Values always use ExpressionAttributeValues (:v)
  • Update expression actions: SET, REMOVE, ADD (numbers and sets), DELETE (from sets)

Query vs Scan

QueryScan
ReadsItems with one partition key value, optional sort-key conditionEvery item in the table or index
EfficiencyFast and cheapSlow and expensive on big tables
Needs keyYes, partition key equality requiredNo
UseNormal application readsRare: export, migration, small tables
python # All November orders of one customer, newest first r = table.query( KeyConditionExpression=Key("customerId").eq("C-100") & Key("orderId").begins_with("2026-11"), FilterExpression=Attr("status").eq("PENDING"), ProjectionExpression="orderId, #s, total", ExpressionAttributeNames={"#s": "status"}, ScanIndexForward=False, # descending by sort key Limit=25) print(r["Items"], r.get("LastEvaluatedKey"))
Filter expressions do not save read cost. Filters run after DynamoDB reads the items, so you still pay for (and are limited by) everything read. Put the selection into the key design instead.
Sort-key conditionsExamples
Equality, <, <=, >, >=Key('orderId').gt('2026-11-01')
betweenKey('orderId').between('2026-11-01', '2026-11-30')
begins_withKey('orderId').begins_with('2026-11')

Pagination

A Query or Scan returns at most 1 MB of data per call. If LastEvaluatedKey is present, there is more. Pass it back as ExclusiveStartKey.

python items, start = [], None while True: kw = {"KeyConditionExpression": Key("customerId").eq("C-100")} if start: kw["ExclusiveStartKey"] = start r = table.query(**kw) items += r["Items"] start = r.get("LastEvaluatedKey") if not start: break

Conditional Writes (Optimistic Locking)

python from botocore.exceptions import ClientError try: table.put_item(Item={"customerId": "C-300", "orderId": "A1", "status": "NEW"}, ConditionExpression="attribute_not_exists(orderId)") # insert only if new except ClientError as e: if e.response["Error"]["Code"] == "ConditionalCheckFailedException": print("already exists") else: raise # Optimistic locking with a version number table.update_item(Key={"customerId": "C-100", "orderId": "A1"}, UpdateExpression="SET total = :t, version = :next", ConditionExpression="version = :cur", ExpressionAttributeValues={":t": 150, ":cur": 3, ":next": 4})
  • Conditions are evaluated atomically with the write. This prevents lost updates in concurrent code
  • Atomic counters: SET views = views + :one works without reading first

Read Consistency

TypeBehaviorCost
Eventually consistent (default)May return slightly stale data (usually within a second)0.5 RCU per 4 KB
Strongly consistent (ConsistentRead=True)Returns the latest committed write. Not available on global secondary indexes or global tables replicas1 RCU per 4 KB
TransactionalACID across items (next lessons)2 RCU per 4 KB

Batch Operations

python with table.batch_writer() as batch: # handles 25-item batches and retries UnprocessedItems for i in range(1000): batch.put_item(Item={"customerId": f"C-{i}", "orderId": "seed", "status": "NEW"}) client = boto3.client("dynamodb") r = client.batch_get_item(RequestItems={"Orders": {"Keys": [ {"customerId": {"S": "C-1"}, "orderId": {"S": "seed"}}, {"customerId": {"S": "C-2"}, "orderId": {"S": "seed"}}]}}) print(r["Responses"]["Orders"], r.get("UnprocessedKeys"))
  • BatchGetItem: up to 100 items / 16 MB. BatchWriteItem: up to 25 put/delete requests / 16 MB
  • Batches are not transactions. Check UnprocessedItems and retry them with backoff
  • BatchWriteItem cannot update items or use conditions

Low-Level vs Resource Client

APIFormatNote
boto3.client('dynamodb')Typed JSON: {'S': 'text'}, {'N': '5'}Closest to the HTTP API
boto3.resource('dynamodb')Plain Python valuesEasier. Uses Decimal
TypeDeserializerConvert typed JSON to PythonUseful in Lambda for DynamoDB Streams events

Limits to Remember

ItemLimit
Item size400 KB
Partition key valueUp to 2,048 bytes. Sort key up to 1,024 bytes
Query/Scan response1 MB per call
TransactionUp to 100 items (check the current limit)
Table name3 to 255 characters

Practice Tasks

  1. Create the Orders table and insert five orders for two customers
  2. Query one customer's orders in a month with a sort-key range
  3. Update an order status with an expression and an atomic counter
  4. Prevent duplicate inserts with attribute_not_exists
  5. Load 500 items with batch_writer and page through them with LastEvaluatedKey

Conclusion

DynamoDB tables need only a primary key (partition key, optionally a sort key). Read with GetItem or Query for key-based access and avoid Scan, use expressions and reserved-word aliases, paginate with LastEvaluatedKey, protect writes with conditions, and know the 400 KB item and 1 MB response limits.

Quick Summary: model; table; CRUD; Query vs Scan; pagination; conditions; consistency; batch; clients; limits.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators