Number Type in DynamoDB: What It Is and How to Use It
Number type stores numeric values as strings to maintain precision. It supports positive, negative, and decimal numbers, allowing you to store integers and floating-point values accurately.How It Works
The Number type in DynamoDB is designed to store any kind of numeric value, including whole numbers and decimals. Unlike some databases that store numbers in binary formats, DynamoDB stores numbers as strings internally. This approach helps keep the exact value without losing precision, especially for very large or very small numbers.
Think of it like writing numbers on a piece of paper instead of using a calculator that might round them. This way, DynamoDB can handle numbers like 123, -45, or 3.14159 without changing their value. When you query or update these numbers, DynamoDB converts them back and forth seamlessly.
Example
This example shows how to put an item with a Number attribute into a DynamoDB table using AWS SDK for JavaScript.
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({ region: "us-east-1" }); async function putNumberItem() { const params = { TableName: "Products", Item: { "ProductId": { S: "123" }, "Price": { N: "19.99" }, "Stock": { N: "100" } } }; try { const data = await client.send(new PutItemCommand(params)); console.log("Item added successfully", data); } catch (err) { console.error("Error adding item", err); } } putNumberItem();
When to Use
Use the Number type in DynamoDB whenever you need to store numeric data such as prices, quantities, ratings, or timestamps. It is ideal for calculations, sorting, and filtering based on numeric values.
For example, an online store can use Number to store product prices and stock counts. A game leaderboard can store player scores as numbers. Since DynamoDB supports decimals, you can also store precise measurements or financial data without losing accuracy.
Key Points
- DynamoDB stores numbers as strings internally to preserve precision.
- Supports positive, negative, integer, and decimal numbers.
- Use
Numbertype for any numeric data you want to query or sort. - Numbers are sent and received as strings in the API but behave like numbers in queries.