[[DynamoDB]] [added support for null fields in 2020](https://aws.amazon.com/about-aws/whats-new/2020/05/amazon-dynamodb-now-supports-empty-values-for-non-key-string-and-binary-attributes-in-dynamodb-tables/).
In DynamoDB JSON, this looks like so:
```json
{
"pk": {
"S": "abcdef"
},
"sk": {
"S": "qwerty"
},
"myNullableField": {
"NULL": true
}
}
```
## Limitation of NULL (and empty string) attribute values
However, there is one key limitation to using NULL values—they cannot be used as part of keys. While this is probably obvious for the main partition and sort keys of the table (as these make up the item's primary key which needs to be unique), it may not be clear for GSIs.
If you try to put an item which has a field that is included as part of a GSI's key, you will get an error:
![[DynamoDBNullGSIFieldError.png]]
Similarly, it does not allow an empty string value to be used for a field which is part of a GSI key:
![[DynamoDBEmptyStringGSIError.png]]
I had expected the behaviour to be like [sparse indexes](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-indexes-general-sparse-indexes.html), where the item write would be allowed, but the item would simply not be written to the `gsi2` index.
In order to write these items, you need to omit the empty attribute completely from the item. If you are using the [AWS DynamoDB SDK For Javascript's DocumentClient](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#constructor-property), this means setting the field to `undefined` or not including it at all in the object you pass to the `put` function.
## Creating a GSI which references pre-existing NULL field
If you have a data item in your DynamoDB table which has a NULL value, and you then attempt to create a GSI which references this field, the index creation is allowed.
So if I have the following item already written to my table:
```json
{
"pk": {
"S": "abc1"
},
"sk": {
"S": "abc1"
},
"myNewGSIsk": {
"NULL": true
},
"myNewGSIpk": {
"S": "v1"
}
}
```
and I then attempt to create a new GSI as follows:
![[ddb-gsi-index-creation-defn.png]]
the index creation succeeds, but I cannot make any further edits to this existing item until I remove the NULL value for the `myNewGSIsk` field:
![[Pasted image 20211126101550.png]]
Also, the existing item doesn't get added to this index and so isn't returned when I query `myNewGSI` for `myNewGSIpk='v1'` (which I would expect).
## Rule of thumb
This behaviour has implications generally around designing your data item attributes for which you may wish to create a GSI on in the future.
Therefore a useful rule of thumb is:
**==When writing an item to DynamoDB, omit nullable string fields altogether (or set them to `undefined` in the JS SDK) instead of setting them to NULL or empty string.== This allows you to include such fields within a GSI index definition, now or in the future.**
A minor added benefit of this is that you're saving a little on storage space.