> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ditto.live/llms.txt
> Use this file to discover all available pages before exploring further.

# Execute a DQL query

> Execute a Ditto Query Language (DQL) statement against your data store. DQL is a powerful query language that supports complex queries, updates, and data manipulation. This endpoint serves as the primary interface for running DQL operations. See the comprehensive DQL guide for detailed syntax and examples.

## Authorization

All requests to this endpoint require authentication using an API key or JWT token in the `Authorization: Bearer` header. For detailed instructions on creating and managing API keys, see [Auth and Parameters](/cloud/http-api/auth-and-params#including-the-api-key).

## API versions

This endpoint is available at both `/api/v4/store/execute` and `/api/v5/store/execute`. The v5 API defaults to `DQL_STRICT_MODE=false`, which treats nested objects as MAPs instead of REGISTERs. For more information, see [API v4 vs v5](/cloud/http-api/getting-started#api-v4-vs-v5).

## Examples

The following examples demonstrate common DQL operations using curl. Replace `{YOUR_CLOUD_URL_ENDPOINT}` with your Cloud URL Endpoint from the portal (see [Getting your Cloud URL Endpoint](/cloud/http-api/getting-started#getting-your-cloud-url-endpoint)) and `{YOUR_API_KEY}` with your API key.

### Insert a document

Insert a new document into a collection:

```bash cURL theme={null}
curl -X POST 'https://{YOUR_CLOUD_URL_ENDPOINT}/api/v5/store/execute' \
  -H 'Authorization: Bearer {YOUR_API_KEY}' \
  -H 'Content-Type: application/json' \
  -d '{
    "statement": "INSERT INTO cars DOCUMENTS (:newCar)",
    "args": {
      "newCar": {
        "_id": "car-123",
        "make": "Toyota",
        "model": "Camry",
        "year": 2024,
        "color": "blue"
      }
    }
  }'
```

### Select documents

Query documents from a collection:

```bash cURL theme={null}
curl -X POST 'https://{YOUR_CLOUD_URL_ENDPOINT}/api/v5/store/execute' \
  -H 'Authorization: Bearer {YOUR_API_KEY}' \
  -H 'Content-Type: application/json' \
  -d '{
    "statement": "SELECT * FROM cars WHERE color = :color",
    "args": {
      "color": "blue"
    }
  }'
```

### Update a document

Update an existing document:

```bash cURL theme={null}
curl -X POST 'https://{YOUR_CLOUD_URL_ENDPOINT}/api/v5/store/execute' \
  -H 'Authorization: Bearer {YOUR_API_KEY}' \
  -H 'Content-Type: application/json' \
  -d '{
    "statement": "UPDATE cars SET color = :newColor WHERE _id = :id",
    "args": {
      "newColor": "red",
      "id": "car-123"
    }
  }'
```

### Delete a document

<Warning>
  **Important:** The `DELETE` operation permanently removes documents from the Ditto system. Deleted documents cannot be recovered. For detailed guidance on delete behavior, tombstones, and best practices, see [Removing Documents](/sdk/latest/crud/delete).

  Key considerations:

  * Deleting large numbers of documents (50,000+) at once can impact system performance. Use `LIMIT` to batch deletions.
  * Concurrent delete and update operations on the same document can result in unexpected "husked documents."
  * Consider using the soft-delete pattern or `EVICT` for local-only removal instead of permanent deletion.
</Warning>

Delete a document from a collection:

```bash cURL theme={null}
curl -X POST 'https://{YOUR_CLOUD_URL_ENDPOINT}/api/v5/store/execute' \
  -H 'Authorization: Bearer {YOUR_API_KEY}' \
  -H 'Content-Type: application/json' \
  -d '{
    "statement": "DELETE FROM cars WHERE _id = :id",
    "args": {
      "id": "car-123"
    }
  }'
```

To delete documents in batches (recommended for large datasets):

```bash cURL theme={null}
curl -X POST 'https://{YOUR_CLOUD_URL_ENDPOINT}/api/v5/store/execute' \
  -H 'Authorization: Bearer {YOUR_API_KEY}' \
  -H 'Content-Type: application/json' \
  -d '{
    "statement": "DELETE FROM cars WHERE year < :year LIMIT 30000",
    "args": {
      "year": 2020
    }
  }'
```

### Upsert a document

Insert a document or update it if it already exists:

```bash cURL theme={null}
curl -X POST 'https://{YOUR_CLOUD_URL_ENDPOINT}/api/v5/store/execute' \
  -H 'Authorization: Bearer {YOUR_API_KEY}' \
  -H 'Content-Type: application/json' \
  -d '{
    "statement": "INSERT INTO cars DOCUMENTS (:car) ON ID CONFLICT DO UPDATE",
    "args": {
      "car": {
        "_id": "car-123",
        "make": "Toyota",
        "model": "Camry",
        "year": 2024,
        "color": "green",
        "mileage": 15000
      }
    }
  }'
```

## Response

A successful response includes:

* `transactionId`: The transaction ID for this operation
* `queryType`: The type of query executed (e.g., "select", "insert", "update", "delete")
* `items`: For SELECT queries, the array of matching documents
* `mutatedDocumentIds`: For mutations, the IDs of affected documents

## API reference


## OpenAPI

````yaml post /store/execute
openapi: 3.0.3
info:
  title: Ditto HTTP RPC API
  version: 4.0.0
  description: >-
    The Ditto HTTP RPC API provides a RESTful interface for interacting with
    Ditto's distributed data store. It enables you to query, insert, update and
    delete data across your Ditto network while maintaining strong consistency
    guarantees.
servers:
  - url: '{base_url}/api/v4'
    description: >-
      The Ditto Big Peer acts as a central synchronization point and data store
      in your Ditto network. It coordinates data replication between peers and
      provides a consistent view of your data.
    variables:
      base_url:
        default: https://REPLACE_WITH_MY_APP_ID.cloud.ditto.live
        description: >-
          Your unique Ditto application endpoint URL, found in the Ditto Portal
          under Application Settings. Replace REPLACE_WITH_MY_APP_ID with your
          actual app ID.
security:
  - api_key_or_jwt_token: []
externalDocs:
  url: https://docs.ditto.live/http/installation/
  description: >-
    For more detailed instructions on how to use this API and the Ditto SDK,
    please see the documentation.
paths:
  /store/execute:
    post:
      summary: Execute a DQL query
      description: >-
        Execute a Ditto Query Language (DQL) statement against your data store.
        DQL is a powerful query language that supports complex queries, updates,
        and data manipulation. This endpoint serves as the primary interface for
        running DQL operations. See the comprehensive DQL guide for detailed
        syntax and examples.
      operationId: execute_endpoint
      parameters:
        - name: X-DITTO-TXN-ID
          in: header
          description: >-
            Optional transaction ID that ensures consistency across operations.
            When provided, the operation will only execute if the Big Peer's
            current transaction ID meets or exceeds this value, preventing stale
            reads and ensuring causal consistency in your application.
          required: false
          deprecated: false
          schema:
            type: integer
            format: int64
      requestBody:
        description: >-
          The DQL statement to execute, along with any parameterized arguments.
          Using parameterized queries with the args field helps prevent
          injection attacks and improves query performance through statement
          caching.
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/QueryRequest'
        required: true
      responses:
        '200':
          description: >-
            The DQL statement executed successfully. The response includes the
            results of the query, any mutated document IDs, the transaction ID,
            and any warnings that occurred during execution. For SELECT queries,
            results appear in the items array. For mutations, affected IDs
            appear in mutatedDocumentIds.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QueryResponse'
              example:
                transactionId: 100
                queryType: select
                items:
                  - _id: 1
                    name: Francis
                    favoriteBook:
                      title: The Great Gatsby
                      published: 1925
                mutatedDocumentIds: []
                error: {}
                warnings: []
                totalWarningsCount: 0
        '400':
          description: >-
            The DQL statement was invalid or malformed. This could be due to
            syntax errors, invalid collection names, type mismatches, or other
            query validation failures. Check the error response for detailed
            information about what went wrong.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QueryResponse'
              example:
                queryType: unknown
                items: []
                mutatedDocumentIds: []
                error:
                  description: ...
                warnings: []
                totalWarningsCount: 0
        '401':
          description: >-
            Authentication failed. Ensure you're providing a valid API key or
            JWT token in the Authorization header and that it has sufficient
            permissions for the requested operation.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QueryResponse'
              example:
                queryType: unknown
                items: []
                mutatedDocumentIds: []
                error:
                  description: ...
                warnings: []
                totalWarningsCount: 0
        '404':
          description: >-
            The requested transaction ID (if specified) is not available on the
            Big Peer. This typically means the Big Peer has not yet reached that
            transaction ID or the transaction has been garbage collected.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QueryResponse'
              example:
                queryType: unknown
                items: []
                mutatedDocumentIds: []
                error:
                  description: ...
                warnings: []
                totalWarningsCount: 0
        '408':
          description: >-
            The query execution timed out. This can happen with complex queries
            over large datasets or when the system is under heavy load. Consider
            optimizing your query or adding appropriate indexes.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QueryResponse'
              example:
                queryType: unknown
                items: []
                mutatedDocumentIds: []
                error:
                  description: ...
                warnings: []
                totalWarningsCount: 0
        '500':
          description: >-
            An unexpected server error occurred while executing the query. This
            could be due to resource constraints, internal errors, or temporary
            service disruptions. The operation may succeed if retried.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QueryResponse'
              example:
                queryType: unknown
                items: []
                mutatedDocumentIds: []
                error:
                  description: ...
                warnings: []
                totalWarningsCount: 0
        '503':
          description: >-
            The service is temporarily unavailable, typically due to maintenance
            or capacity issues. Clients should implement exponential backoff and
            retry the request later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/QueryResponse'
              example:
                queryType: unknown
                items: []
                mutatedDocumentIds: []
                error:
                  description: ...
                warnings: []
                totalWarningsCount: 0
      deprecated: false
components:
  schemas:
    QueryRequest:
      type: object
      description: >-
        Request parameters for executing a DQL statement. DQL is Ditto's
        powerful query language that supports complex queries and data
        modifications.
      required:
        - statement
      properties:
        args:
          $ref: '#/components/schemas/AnyValue'
          description: >-
            Named parameters to use in the DQL statement, providing safe value
            substitution and better query performance
        statement:
          type: string
          description: >-
            The DQL statement to execute. See https://docs.ditto.live/dql-guide
            for comprehensive documentation on DQL syntax and features.
      example:
        statement: SELECT * FROM people WHERE favoriteBook.title = :title
        args:
          title: The Great Gatsby
    QueryResponse:
      type: object
      description: >-
        Response from executing a DQL statement. Contains query results,
        affected document IDs, and any warnings or errors that occurred.
      required:
        - queryType
        - items
        - mutatedDocumentIds
        - warnings
        - totalWarningsCount
      properties:
        error:
          $ref: '#/components/schemas/QueryResponseError'
        items:
          type: array
          items:
            $ref: '#/components/schemas/AnyValue'
        mutatedDocumentIds:
          type: array
          items:
            $ref: '#/components/schemas/AnyValue'
        queryType:
          type: string
          description: Indicates the type of query that was executed
        totalWarningsCount:
          type: integer
          format: int64
          description: Total number of warnings generated during query execution
        transactionId:
          type: integer
          format: int64
        warnings:
          type: array
          items:
            $ref: '#/components/schemas/QueryResponseWarning'
    AnyValue: {}
    QueryResponseError:
      type: object
      description: >-
        An error occurred that prevented the query from executing or completing
        successfully
      properties:
        description:
          type: string
    QueryResponseWarning:
      type: object
      description: Indicates any run-time warnings that might arise during query execution
      required:
        - description
      properties:
        _id:
          $ref: '#/components/schemas/AnyValue'
        description:
          type: string
  securitySchemes:
    api_key_or_jwt_token:
      type: http
      scheme: bearer
      bearerFormat: API Key or JWT
      description: >-
        Authentication using either an API key or JWT token in the Authorization
        header

````