---
title: INSERT
slug: dql/insert
docTags: 
createdAt: 2023-11-02T21:43:20.895Z
---

When using DQL's <font color="#db2777">`INSERT`</font> command, you can add new documents using JSON objects:

:::CodeblockTabs
DQL

```sql
INSERT INTO your_collection_name
DOCUMENTS ([document1]),([document2]), ([document3]), ...
[ON ID CONFLICT [FAIL | DO NOTHING | DO UPDATE]]
```
:::

- <font color="#db2777">`INSERT INTO`</font> is the name of the collection from which you want to retrieve the data.
- `DOCUMENTS ([document1]), ([document2]), ([document3]), ...` represent the documents being inserted.
- `[ ON ID CONFLICT [DO FAIL | DO NOTHING | DO UPDATE ([policy])]]` is an optional clause that allows for defining a policy if the ID already exists in the local data store. The default is to throw an error (`FAIL`).

:::hint{type="info"}
In Ditto, excluding fields from your payload doesn't remove the existing data from the system.&#x20;

To remove a specific field from a document, use an explicit <font color="#db2777">`UPDATE`</font> statement and `tombstone` that field. (See [UPDATE](docId:_vxfd7_jJFfTzByIVqoxh))
:::

# INSERT Document

:::CodeblockTabs
```swift
await ditto.store.execute(
  query: "INSERT INTO cars DOCUMENTS (:newCar)",
  arguments: ["newCar": ["color": "blue"]]);
```

```kotlin
ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  mapOf("newCar" to mapOf("color" to "blue")))
```

```javascript
await ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  { newCar: { color: "blue" } }
);
```

```java
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO cars DOCUMENTS (:newCar)",
    Collections.singletonMap("newCar", Collections.singletonMap("color", "blue")),
);
```

```csharp
var args = new Dictionary<string, object>();
args.Add("newCar", new { color = "blue" });

await ditto.Store.ExecuteAsync(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  args);
```

```cpp
std::map<std::string, std::map<std::string, std::string>> args;
args["newCar"] = {{"color", "blue"}};

ditto.get_store().execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  args);
```

```rust
let query_result = ditto
    .store()
    .execute(
        "INSERT INTO cars DOCUMENTS (:newCar)",
        Some(serde_json::json!({
            "newCar": {
                "color": "blue"
            }
        }).into()),
    ).await?;
```

```dart
await ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:newCar)",
  arguments: {"newCar": {"color": "blue"}},
);
```
:::

# INSERT with Multiple Documents

:::CodeblockTabs
```swift
await ditto.store.execute(
  query: "INSERT INTO cars DOCUMENTS (:car1), (:car2)",
  arguments: [
    "car1": ["color": "blue"],
    "car2": ["color": "red"]
  ]);
```

```kotlin
ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
  mapOf(
    "car1" to mapOf("color" to "blue"),
    "car2" to mapOf("color" to "red")
  ))
```

```javascript
await ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
  {
    car1: { color: 'blue' },
    car2: { color: 'red' }
  });
```

```java
Map<String, Map<String, String>> args = new HashMap<>();
args.put("car1", Collections.singletonMap("color", "blue"));
args.put("car2", Collections.singletonMap("color", "red"));

DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
    args,
    new Continuation<>() {
        @NonNull
        @Override
        public CoroutineContext getContext() {
            return EmptyCoroutineContext.INSTANCE;
        }

        @Override
        public void resumeWith(@NonNull Object o) {
            if (o instanceof Result.Failure) {
                // Handle failure
            }
        }
    }
);
```

```csharp
var args = new Dictionary<string, object>();
args.Add("car1", new { color = "blue" });
args.Add("car2", new { color = "red" });

await ditto.Store.ExecuteAsync(
  "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
  args);
```

```cpp
std::map<std::string, std::map<std::string, std::string>> args;
args["car1"] = {{"color", "blue"}};
args["car2"] = {{"color", "red"}};

auto result = ditto.get_store().execute(
    "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
    args).get();
```

```rust
let query_result = ditto
    .store()
    .execute(
        "INSERT INTO cars DOCUMENTS (:car1), (:car2)",
        Some(serde_json::json!({
            "car1": {
                "color": "blue"
            },
            "car2": {
                "color": "red"
            }
        }).into()),
    ).await?;
```

```dart
await ditto.store.execute(
  "INSERT INTO cars DOCUMENTS (:car1),(:car2)",
  arguments: {
    "car1": { "color": "blue" },
    "car2": { "color": "red" },
  },
);
```
:::

# INSERT Document with MAP Type

For full `MAP` syntax, see [MAP](docId\:NL2T9noZi_1ajWdJNRmMu).

:::CodeblockTabs
```swift
let arguments: [String: Any] = [
  "newCar": [
    "_id": "123",
    "properties": [
      "color": "blue",
      "mileage": 3000
    ]
  }
];

await ditto.store.execute(
  query: "INSERT INTO COLLECTION cars (properties MAP) DOCUMENTS (:newCar)",
  arguments: arguments);
```

```kotlin
val arguments = mapOf(
  "newCar" to mapOf(
    "_id" to "123",
    "properties" to mapOf(
      "color" to "blue",
      "mileage" to 3000
      )
    )
  )
)

ditto.store.execute("""
  INSERT INTO COLLECTION cars (properties MAP)
  DOCUMENTS (:newCar)
  """,
  arguments)
```

```javascript
const newCar = {
  _id: "123",
  properties: {
    color: 'blue',
    mileage: 3000
  }
}

await ditto.store.execute(`
  INSERT INTO COLLECTION cars (properties MAP)
  DOCUMENTS (:newCar)`,
  { newCar });
```

```java
Map<String, Object> properties = new HashMap<>();
properties.put("color", "blue");
properties.put("mileage", 3000);

Map<String, Object> newCar = new HashMap<>();
newCar.put("_id", "123");
newCar.put("properties", properties);

DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO COLLECTION cars (properties MAP) DOCUMENTS (:newCar)",
    Collections.singletonMap("newCar", newCar),
    new Continuation<>() {
        @NonNull
        @Override
        public CoroutineContext getContext() {
            return EmptyCoroutineContext.INSTANCE;
        }

        @Override
        public void resumeWith(@NonNull Object o) {
            if (o instanceof Result.Failure) {
                // Handle failure
            }
        }
    }
);
```

```csharp
var subMap = new {
  color = "blue",
  mileage = 3000
};
var insertArgs = new Dictionary<string, object>();
insertArgs.Add("newCar", new { _id = newId, properties = subMap })

var result = await ditto.Store.ExecuteAsync(
  "INSERT INTO COLLECTION cars (properties MAP) DOCUMENTS (:newCar)",
  insertArgs);
```

```cpp
struct Properties {
  std::string color;
  int mileage;
};
struct Car {
  std::string _id;
  Properties properties;
};

// ...

std::map<std::string, Car> args;
args["newCar"] = {"123", {"blue", 3000}};

ditto.get_store().execute(
  "INSERT INTO COLLECTION your_collection_name (properties MAP)"
+ " DOCUMENTS (:newCar)",
  args).get();
```

```rust
let query_result = ditto
    .store()
    .execute(
        "INSERT INTO COLLECTION cars (properties MAP) DOCUMENTS (:newCar)",
        Some(serde_json::json!({
            "newCar": {
                "_id": "123",
                "properties": {
                    "color": "blue",
                    "mileage": 3000
                }
            }
        }).into()),
    ).await?;
```

```dart
final newCar = {
  "_id": "123",
  "properties": {
    "color": 'blue',
    "mileage": 3000,
  },
};

await ditto.store.execute("""
  INSERT INTO COLLECTION cars (properties MAP) 
  DOCUMENTS (:newCar)""",
  arguments: {"newCar": newCar},
);
```
:::

# INSERT JSON-serialized Document

From SDK 4.8, you can insert JSON-serialized Documents into Ditto directly using the `deserialize_json()` function.

:::CodeblockTabs
```swift
await ditto.store.execute(
  query: """
    INSERT INTO cars
    DOCUMENTS (deserialize_json(:jsonData))
    ON ID CONFLICT DO UPDATE
    """,
  arguments: [ "jsonData": "{\"_id\": \"123\",\"color\": \"blue\"}" ])
```

```kotlin
ditto.store.execute("""
  INSERT INTO cars
  DOCUMENTS (deserialize_json(:jsonData))
  """,
  mapOf("jsonData", "{\"_id\": \"123\",\"color\": \"blue\"}"))
```

```javascript
await ditto.store.execute(`
  INSERT INTO cars
  DOCUMENTS (deserialize_json(:jsonData))`,
  { jsonData: "{\"_id\": \"123\",\"color\": \"blue\"}" });
```

```java
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO cars DOCUMENTS (deserialize_json(:jsonData))",
    Collections.singletonMap("jsonData", "{\"_id\": \"123\",\"color\": \"blue\"}"),
);
```

```csharp
var args = new Dictionary<string, string>();
args.Add("jsonData", "{\"_id\": \"123\",\"color\": \"blue\"}")

var result = await ditto.Store.ExecuteAsync(
  "INSERT INTO cars"
+ " DOCUMENTS (deserialize_json(:jsonData))",
  args);
```

```cpp
std::map<std::string, string> args;
args["jsonData"] = "{\"_id\": \"123\",\"color\": \"blue\"}";

auto result = ditto.get_store().execute(
  "INSERT INTO cars DOCUMENTS (deserialize_json(:jsonData))",
  args).get();
```

```rust
let json_string = r#"{"_id": "123", "color": "blue"}"#.to_string();

let query_result = ditto
    .store()
    .execute(
        "INSERT INTO cars DOCUMENTS (deserialize_json(:jsonData))",
        Some(serde_json::json!({
            "jsonData": "{\"_id\": \"123\",\"color\": \"blue\"}"
        }).into()),
    ).await; 
```

```dart
final newCar = '{"_id": "123", "color": "blue"}';

await ditto.execute("""
  INSERT INTO cars
  DOCUMENTS (deserialize_json(:jsonData))""",
  queryArgs: {"jsonData": "{\"_id\": \"123\",\"color\": \"blue\"}"},
);
```
:::

***

# INSERT with ID Conflict Handling

By default, the <font color="#db2777">`INSERT`</font> operation throws an error if an existing document with the same ID exists in the local Ditto store.  &#x20;

However, Ditto allows some flexibility by allowing you to choose between ignoring the conflict (`DO NOTHING`) or updating existing documents (`DO UPDATE`) when a conflict occurs during an <font color="#db2777">`INSERT`</font> operation:

:::CodeblockTabs
DQL

```sql
ON ID CONFLICT [DO FAIL | DO NOTHING | DO UPDATE]
```
:::

In this syntax:

- `DO FAIL` (default) will cause an error to be thrown if a document with the same `_id` currently exists in the local data store.
- `DO NOTHING` will make the statement succeed with no action taken
- `DO UPDATE` will perform a value update on every field in the provided document, even if the value is the same. (This will result in all fields provided being replicated).

For example, inserting or updating a car — if there is a conflict (<font color="#db2777">`ON ID CONFLICT)`</font>, execute the  <font color="#db2777">`DO UPDATE`</font> conflict resolution policy:

:::CodeblockTabs
```swift
let newCar = [
  "_id": "123",
  "color": "blue"
]

await ditto.store.execute(
  query: """
    INSERT INTO cars
    DOCUMENTS (:newCar)
    ON ID CONFLICT DO UPDATE
    """,
  arguments: [ "newCar": newCar ])
```

```kotlin
var newCar = mapOf(
  "_id" to "123",
  "color" to "blue"
)

ditto.store.execute("""
  INSERT INTO cars
  DOCUMENTS (:newCar)
  ON ID CONFLICT DO UPDATE
  """,
  mapOf("newCar", newCar))
```

```javascript
const newCar = {
  _id: "123",
  color: "blue",
};

await ditto.store.execute(`
  INSERT INTO cars
  DOCUMENTS (:newCar)
  ON ID CONFLICT DO UPDATE`,
  { newCar });
```

```java
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO cars DOCUMENTS (:newCar) ON ID CONFLICT DO UPDATE",
    Collections.singletonMap("newCar", Collections.singletonMap("color", "blue")),
);
```

```csharp
var args = new Dictionary<string, object>();
args.Add("newCar", new { _id = "123", color = "blue" })

var result = await ditto.Store.ExecuteAsync(
  "INSERT INTO cars"
+ " DOCUMENTS (:newCar) ON ID CONFLICT DO UPDATE",
  args);
```

```cpp
struct Car {
  std::string _id;
  std::string color;
};

// ...

std::map<std::string, Car> args;
args["newCar"] = {"123", "blue"};

auto result = ditto.get_store().execute(
  "INSERT INTO cars DOCUMENTS (:newCar) ON ID CONFLICT DO UPDATE",
  args).get();
```

```rust
let query_result = ditto
    .store()
    .execute(
        "INSERT INTO cars DOCUMENTS (:newCar) \
        ON ID CONFLICT DO UPDATE",
        Some(serde_json::json!({
            "newCar": {
                "_id": "123",
                "color": "blue"
            }
        }).into()),
    ).await?;
```

```dart
final newCar = {
  "_id": "123",
  "color": "blue",
};

await ditto.execute("""
  INSERT INTO cars
  DOCUMENTS (:newCar)
  ON ID CONFLICT DO UPDATE""",
  queryArgs: {"newCar": newCar},
);
```
:::

***

# INSERT with INITIAL DOCUMENTS

<font color="#db2777">`INSERT`</font> allows you to set specific documents as default data using the <font color="#db2777">`INITIAL DOCUMENTS`</font> action.&#x20;

*Initial documents* are the documents inserted at the beginning of time and are viewed by all peers as the same <font color="#db2777">`INSERT`</font> operation. This allows multiple peers to independently initialize the same default data *safely*, so regardless of the individual peer's starting point.

:::hint{type="info"}
When inserting, the initial documents <font color="#db2777">`DO NOTHING`</font> if the document ID already exists in the local Ditto store. The <font color="#db2777">`ON ID CONFLICT`</font> policy cannot change this behavior.
:::

:::CodeblockTabs
DQL

```sql
INSERT INTO your_collection_name
INITIAL DOCUMENTS ([document])
```
:::

In this syntax:

- `your_collection_name` is the name of the collection from which you want to retrieve the data.
- `[document]` represents the document.

For example, setting up default data by inserting the given car details as an initial document:

:::CodeblockTabs
```swift
let newCar = [
  "_id": "123",
  "color": "blue"
]

await ditto.store.execute(
  query: """
    INSERT INTO cars
    INITIAL DOCUMENTS (:newCar)
    """,
  arguments: [ "newCar": newCar ])
```

```kotlin
var newCar = mapOf(
  "_id" to "123",
  "color" to "blue"
)

ditto.store.execute("""
  INSERT INTO cars
  INITIAL DOCUMENTS (:newCar)
  """,
  mapOf("newCar", newCar))
```

```javascript
const newCar = {
  _id: "123"
  color: "blue",
};

await ditto.store.execute(`
  INSERT INTO cars
  INITIAL DOCUMENTS (:newCar)`,
  { newCar });
```

```java
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
    "INSERT INTO cars INITIAL DOCUMENTS (:newCar)",
    Collections.singletonMap("newCar", Collections.singletonMap("color", "blue")),
);
```

```csharp
var args = new Dictionary<string, object>();
args.Add("newCar", new { _id = "123", field1 = 0 })

await ditto.Store.ExecuteAsync(
  "INSERT INTO cars INITIAL DOCUMENTS (:newCar)",
  args);
```

```cpp
struct Car {
  std::string _id;
  std::string color;
};

// ...

std::map<std::string, Car> args;
args["newCar"] = {"123", "blue"};

auto result = ditto.get_store().execute(
  "INSERT INTO cars INITIAL DOCUMENTS (:newCar)",
  args).get();
```

```rust
let query_result = ditto
    .store()
    .execute(
        "INSERT INTO cars INITIAL DOCUMENTS (:newCar)",
        Some(serde_json::json!({
            "newCar": {
                "_id": "123",
                "color": "blue"
            }
        }).into())
    ).await?; 
```

```dart
const newCar = {
  "_id": "123"
  "color": "blue",
};

await ditto.execute("""
  INSERT INTO cars
  INITIAL DOCUMENTS (:newCar)""",
  {"newCar": newCar},
);
```
:::

