> This page is for Developers.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://zuora.ferndocs.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://zuora.ferndocs.com/_mcp/server.

# Submit a data query

POST https://rest.test.zuora.com/query/jobs
Content-Type: application/json

Submits a [data query](https://knowledgecenter.zuora.com/DC_Developers/BA_Data_Query) to be executed by Zuora, creating a new query job. Use the [Retrieve a data query job](https://developer.zuora.com/v1-api-reference/api/operation/GET_DataQueryJob/) endpoint to monitor the job status and access the results once complete.

**Note:** The request must include the `Content-Type: application/json` header. If this header is missing, the request will fail with the following error:   `{"code":415,"message":"HTTP 415 Unsupported Media Type"}`

Reference: https://zuora.ferndocs.com/developers/api-reference/zuora-api/data-query/data-queries/post-data-query-job

## Authentication

- `Authorization` header (bearer token, required) — Use `Bearer {{token}}` in the `Authorization` header for authentication.

## Servers

- `https://rest.test.zuora.com` (US Developer & Central Sandbox (incl. Test Drive), default)
- `https://rest.sandbox.na.zuora.com` (US API Sandbox Cloud 1)
- `https://rest.apisandbox.zuora.com` (US API Sandbox Cloud 2)
- `https://rest.na.zuora.com` (US Production Cloud 1)
- `https://rest.zuora.com` (US Production Cloud 2)
- `https://rest.test.eu.zuora.com` (EU Developer & Central Sandbox)
- `https://rest.sandbox.eu.zuora.com` (EU API Sandbox)
- `https://rest.eu.zuora.com` (EU Production)
- `https://rest.test.ap.zuora.com` (APAC Developer & Central Sandbox)
- `https://rest.ap.zuora.com` (APAC Production)

## Request

### Headers

- `Idempotency-Key` (string, optional) — Specify a unique idempotency key if you want to perform an idempotent POST or PATCH request. Do not use this header in other request types. With this header specified, the Zuora server can identify subsequent retries of the same request using this value, which prevents the same operation from being performed multiple times by accident.
- `Accept-Encoding` (string, optional) — Include the `Accept-Encoding: gzip` header to compress responses as a gzipped file. It can significantly reduce the bandwidth required for a response. If specified, Zuora automatically compresses responses that contain over 1000 bytes of data, and the response contains a `Content-Encoding` header with the compression algorithm so that your client can decompress it.
- `Content-Encoding` (string, optional) — Include the `Content-Encoding: gzip` header to compress a request. With this header specified, you should upload a gzipped file for the request payload instead of sending the JSON payload.
- `Zuora-Entity-Ids` (string, optional) — An entity ID. If you have [Zuora Multi-entity](https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/Multi-entity) enabled and the OAuth token is valid for more than one entity, you must use this header to specify which entity to perform the operation in. If the OAuth token is only valid for a single entity, or you do not have Zuora Multi-entity enabled, you should not set this header.
- `Zuora-Org-Ids` (string, optional) — Comma separated IDs. If you have Zuora Multi-Org enabled, you can use this header to specify which orgs to perform the operation in. If you do not have Zuora Multi-Org enabled, you should not set this header. The IDs must be a sub-set of the user's accessible orgs. If you specify an org that the user does not have access to, the operation fails. This header is important in Multi-Org (MO) setups because it defines the organization context under which the API should operate—mainly used for read access or data visibility filtering. If the header is not set, the operation is performed in scope of the user's accessible orgs.
- `Zuora-Track-Id` (string, optional) — A custom identifier for tracing the API call. If you set a value for this header, Zuora returns the same value in the response headers. This header enables you to associate your system process identifiers with Zuora API calls, to assist with troubleshooting in the event of an issue. The value of this field must use the US-ASCII character set and must not include any of the following characters: colon (`:`), semicolon (`;`), double quote (`"`), and quote (`'`).

### Body (application/json)

This endpoint expects a SubmitDataQueryRequest.

- `compression` (enum, required) — Specifies whether Zuora compresses the query results.
  - Allowed values: `NONE`, `GZIP`, `ZIP`
- `output` (SubmitDataQueryRequestOutput, required) — Additional information about the query results.
- `outputFormat` (enum, required) — Specifies the format of the query results. * `JSON` - Each row in the query results will be a JSON object. The format of the query result file is [JSON Lines](http://jsonlines.org/). * `CSV` - Each row in the query results will be a comma-separated list of values. * `TSV` - Each row in the query results will be a tab-separated list of values. * `DSV` - Pass any character as your custom delimiter into the `columnSeparator` field.
  - Allowed values: `JSON`, `CSV`, `TSV`, `DSV`
- `query` (string, required) — The query to perform. See [SQL Queries in Data Query](https://knowledgecenter.zuora.com/DC_Developers/BA_Data_Query/BA_SQL_Queries_in_Data_Query) for more information.
- `columnSeparator` (string, optional) — The column separator. Only applicable if the `outputFormat` is `DSV`.
- `encryptionKey` (string, optional) — Base-64 encoded public key of an RSA key-pair. Note that Data Query only supports 1024-bit RSA keys. If you set this field, Zuora encrypts the query results using the provided public key. You must use the corresponding private key to decrypt the query results.
- `readDeleted` (boolean, optional, default: false) — Indicates whether the query will retrieve only the deleted record. If `readDeleted` is set to `false` or it is not included in the request body, the query will retrieve only the non-deleted records. If it is set to `true`, only the deleted records will be retrieved. If you select the `deleted` column in the `query` field, both non-deleted and deleted records will be retrieved regardless of the value in the `readDeleted` field. Note that Data Query is subject to Zuora Data Retention Policy. The retention period of deleted data is 30 days. You can only retrieve deleted data for 30 days through Data Query.
- `sourceData` (enum, optional) — Specify the source that data queries run against: * `LIVE` represents the live transactional databases at Zuora (Data Query Live). * `WAREHOUSE` represents Zuora Warehouse, which has better performance and fewer limitations than the live transactional database. This option is available only if you have the Zuora Warehouse feature enabled in your tenant. For more information, see Zuora Warehouse. If this option is selected, you can specify warehouse size in `warehouseSize`. If this field is not specified, the default value `LIVE` will be used.
  - Allowed values: `LIVE`, `WAREHOUSE`
- `useIndexJoin` (boolean, optional) — Indicates whether to use Index Join. Index join is useful when you have a specific reference value in your WHERE clause to index another large table by. See [Use Index Join](https://knowledgecenter.zuora.com/DC_Developers/BA_Data_Query/Best_practices_of_Data_Query#Use_Index_Join) for more information.
- `warehouseSize` (enum, optional) — Specify the size of Zuora Warehouse. This field is available only if the `sourceData` is `WAREHOUSE`. If this field is not specified or set to `NULL`, the default value `xsmall` will be used.
  - Allowed values: `xsmall`, `NULL`

## Response

### 200

OK

- `data` (DataQueryJob, optional) — A data query job.

## Errors

### 400 Bad Request Error

Bad Request

- `code` (integer, optional) — Error code.
- `message` (string, optional) — Error message.

### 415 Unsupported Media Type Error

Unsupported Media Type. This error is returned when the request is missing the required `Content-Type: application/json` header.

- `code` (integer, optional) — Error code.
- `message` (string, optional) — Error message.

## Types

### SubmitDataQueryRequestOutput

Additional information about the query results.

- `target` (enum, required) — Set this field to `S3`.
  - Allowed values: `S3`

### DataQueryJob

A data query job.

- `createdBy` (string, optional) — The query job creator's Id.
- `id` (string, optional) — Internal identifier of the query job.
- `query` (string, optional) — The query that was submitted.
- `remainingRetries` (integer, optional) — The number of times that Zuora will retry the query if Zuora is unable to perform the query.
- `sourceData` (string, optional) — Indicates the source that data queries run against: * `LIVE` represents the live transactional databases at Zuora (Data Query Live). * `WAREHOUSE` represents Zuora Warehouse, which has better performance and fewer limitations than the live transactional database. For more information, see Zuora Warehouse.
- `updatedOn` (datetime, optional) — Date and time when the query job was last updated, in ISO 8601 format.
- `useIndexJoin` (boolean, optional) — Indicates whether to use Index Join. See Index Join for more information.
- `dataFile` (string, optional) — The URL of the query results. Only applicable if the value of the `queryStatus` field is `completed`.
- `outputRows` (integer, optional) — The number of rows the query results. Only applicable if the value of the `queryStatus` field is `completed`.
- `processingTime` (integer, optional) — Processing time of the query job, in milliseconds. Only applicable if the value of the `queryStatus` field is `completed`.
- `queryStatus` (enum, optional) — Status of the query job. * `submitted` - query submitted to query service for processing * `accepted` - query accepted by the query service * `in_progress` - query executed by the query service * `completed` - query execution completed by the query service * `failed` - query unable to be processed by the query service * `cancelled` - query cancelled by the user If the value of this field is `completed`, the `dataFile` field contains the location of the query results. If the value of this field is `accepted` or `in_progress`, you can use [Cancel a data query job](#operation/DELETE_DataQueryJob) to prevent Zuora from performing the query. Zuora then sets the status of the query job to `cancelled`.
  - Allowed values: `submitted`, `accepted`, `in_progress`, `completed`, `failed`, `cancelled`

## Examples

**Request**

```json
{
  "compression": "NONE",
  "output": {
    "target": "S3"
  },
  "outputFormat": "CSV",
  "query": "SELECT accountnumber, balance FROM Account WHERE Account.balance > 100"
}
```

**Response**

```json
{
  "data": {
    "createdBy": "514f3ea1-6716-4f44-b6e0-9a8f0cf44bd2",
    "id": "5948abde-b875-4d06-ad07-c2138853d8bc",
    "query": "SELECT accountnumber, balance FROM Account WHERE Account.balance > 100",
    "remainingRetries": 3,
    "sourceData": "LIVE",
    "updatedOn": "2024-07-09T09:47:49.675Z",
    "useIndexJoin": false,
    "queryStatus": "accepted",
    "createdByUserEmail": "amy@mycompany.com",
    "createdOn": "2024-07-09T09:47:49.675Z",
    "retries": 3
  }
}
```

**SDK Code**

```python response
import requests

url = "https://rest.test.zuora.com/query/jobs"

payload = {
    "compression": "NONE",
    "output": { "target": "S3" },
    "outputFormat": "CSV",
    "query": "SELECT accountnumber, balance FROM Account WHERE Account.balance > 100"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript response
const url = 'https://rest.test.zuora.com/query/jobs';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"compression":"NONE","output":{"target":"S3"},"outputFormat":"CSV","query":"SELECT accountnumber, balance FROM Account WHERE Account.balance > 100"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go response
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://rest.test.zuora.com/query/jobs"

	payload := strings.NewReader("{\n  \"compression\": \"NONE\",\n  \"output\": {\n    \"target\": \"S3\"\n  },\n  \"outputFormat\": \"CSV\",\n  \"query\": \"SELECT accountnumber, balance FROM Account WHERE Account.balance > 100\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby response
require 'uri'
require 'net/http'

url = URI("https://rest.test.zuora.com/query/jobs")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"compression\": \"NONE\",\n  \"output\": {\n    \"target\": \"S3\"\n  },\n  \"outputFormat\": \"CSV\",\n  \"query\": \"SELECT accountnumber, balance FROM Account WHERE Account.balance > 100\"\n}"

response = http.request(request)
puts response.read_body
```

```java response
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://rest.test.zuora.com/query/jobs")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"compression\": \"NONE\",\n  \"output\": {\n    \"target\": \"S3\"\n  },\n  \"outputFormat\": \"CSV\",\n  \"query\": \"SELECT accountnumber, balance FROM Account WHERE Account.balance > 100\"\n}")
  .asString();
```

```php response
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://rest.test.zuora.com/query/jobs', [
  'body' => '{
  "compression": "NONE",
  "output": {
    "target": "S3"
  },
  "outputFormat": "CSV",
  "query": "SELECT accountnumber, balance FROM Account WHERE Account.balance > 100"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp response
using RestSharp;

var client = new RestClient("https://rest.test.zuora.com/query/jobs");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"compression\": \"NONE\",\n  \"output\": {\n    \"target\": \"S3\"\n  },\n  \"outputFormat\": \"CSV\",\n  \"query\": \"SELECT accountnumber, balance FROM Account WHERE Account.balance > 100\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift response
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "compression": "NONE",
  "output": ["target": "S3"],
  "outputFormat": "CSV",
  "query": "SELECT accountnumber, balance FROM Account WHERE Account.balance > 100"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://rest.test.zuora.com/query/jobs")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```