Query Table Data

https://{your-workspace-slug}.xata.sh/db/{db_branch_name}/tables/{table_name}/query/

This endpoint serves data from a given table, inside a specific database''s branch. For a tutorial on using the Records API, see the Record API documentation.

Expected Parameters
NameDescriptionInRequiredSchema
db_branch_nameThe DBBranchName matches the pattern `{db_name}:{branch_name}`. pathstring
table_nameThe Table namepathstring

Query Table

POST  https://{your-workspace-slug}.xata.sh/db/{db_branch_name}/tables/{table_name}/query/

The Query Table API can be used to retrieve all records in a table. The API support filtering, sorting, selecting a subset of columns, and pagination.

The overall structure of the request looks like this:

// POST /db/<dbname>:<branch>/tables/<table>/query
{
  "columns": [...],
  "filter": {
    "$all": [...],
    "$any": [...]
    ...
  },
  "sort": {
    "multiple": [...]
    ...
  },
  "page": {
    ...
  }
}

Column selection

If the columns array is not specified, all columns are included. For link fields, only the ID column of the linked records is included in the response.

If the columns array is specified, only the selected columns are included. The * wildcard can be used to select all columns of the given array

For objects and link fields, if the column name of the object is specified, we include all of its sub-keys. If only some sub-keys are specified (via dotted notation, e.g. "settings.plan" ), then only those sub-keys from the object are included.

By the way of example, assuming two tables like this:

{
  "formatVersion": "1.0",
  "tables": [
    {
      "name": "teams",
      "columns": [
        {
          "name": "name",
          "type": "string"
        },
        {
          "name": "owner",
          "type": "link",
          "link": {
            "table": "users"
          }
        },
        {
          "name": "foundedDate",
          "type": "datetime"
        },
      ]
    },
    {
      "name": "users",
      "columns": [
        {
          "name": "email",
          "type": "email"
        },
        {
          "name": "full_name",
          "type": "string"
        },
        {
          "name": "address",
          "type": "object",
          "columns": [
            {
              "name": "street",
              "type": "string"
            },
            {
              "name": "number",
              "type": "int"
            },
            {
              "name": "zipcode",
              "type": "int"
            }
          ]
        },
        {
          "name": "team",
          "type": "link",
          "link": {
            "table": "teams"
          }
        }
      ]
    }
  ]
}

A query like this:

POST /db/<dbname>:<branch>/tables/<table>/query
{
  "columns": [
    "name",
    "address.*"
  ]
}

returns objects like:

{
  "name": "Kilian",
  "address": {
    "street": "New street",
    "number": 41,
    "zipcode": 10407
  }
}

while a query like this:

POST /db/<dbname>:<branch>/tables/<table>/query
{
  "columns": [
    "name",
    "address.street"
  ]
}

returns objects like:

{
  "name": "Kilian",
  "address": {
    "street": "New street"
  }
}

If you want to return all columns from the main table and selected columns from the linked table, you can do it like this:

{
  "columns": ["*", "team.name"]
}

The "*" in the above means all columns, including columns of objects. This returns data like:

{
  "name": "Kilian",
  "email": "kilian@gmail.com",
  "address": {
    "street": "New street",
    "number": 41,
    "zipcode": 10407
  },
  "team": {
    "id": "XX",
    "xata": {
      "version": 0
    },
    "name": "first team"
  }
}

If you want all columns of the linked table, you can do:

{
  "columns": ["*", "team.*"]
}

This returns, for example:

{
  "name": "Kilian",
  "email": "kilian@gmail.com",
  "address": {
    "street": "New street",
    "number": 41,
    "zipcode": 10407
  },
  "team": {
    "id": "XX",
    "xata": {
      "version": 0
    },
    "name": "first team",
    "code": "A1",
    "foundedDate": "2020-03-04T10:43:54.32Z"
  }
}

Filtering

There are two types of operators:

  • Operators that work on a single column: $is, $contains, $pattern, $includes, $gt, etc.
  • Control operators that combine multiple conditions: $any, $all, $not , $none, etc.

All operators start with an $ to differentiate them from column names (which are not allowed to start with a dollar sign).

Exact matching and control operators

Filter by one column:

{
  "filter": {
    "<column_name>": "value"
  }
}

This is equivalent to using the $is operator:

{
  "filter": {
    "<column_name>": {
      "$is": "value"
    }
  }
}

For example:

{
  "filter": {
    "name": "r2"
  }
}

Or:

{
  "filter": {
    "name": {
      "$is": "r2"
    }
  }
}

For objects, both dots and nested versions work:

{
  "filter": {
    "settings.plan": "free"
  }
}
{
  "filter": {
    "settings": {
      "plan": "free"
    }
  }
}

If you want to OR together multiple values, you can use the $any operator with an array of values:

{
  "filter": {
    "settings.plan": { "$any": ["free", "paid"] }
  }
}

If you specify multiple columns in the same filter, they are logically AND'ed together:

{
  "filter": {
    "settings.dark": true,
    "settings.plan": "free"
  }
}

The above matches if both conditions are met.

To be more explicit about it, you can use $all or $any:

{
  "filter": {
    "$any": {
      "settings.dark": true,
      "settings.plan": "free"
    }
  }
}

The $all and $any operators can also receive an array of objects, which allows for repeating column names:

{
  "filter": {
    "$any": [
      {
        "name": "r1"
      },
      {
        "name": "r2"
      }
    ]
  }
}

You can check for a value being not-null with $exists:

{
  "filter": {
    "$exists": "settings"
  }
}

This can be combined with $all or $any :

{
  "filter": {
    "$all": [
      {
        "$exists": "settings"
      },
      {
        "$exists": "name"
      }
    ]
  }
}

Or you can use the inverse operator $notExists:

{
  "filter": {
    "$notExists": "settings"
  }
}

Partial match

$contains is the simplest operator for partial matching. We should generally discourage overusing $contains because it typically can't make use of indices.

{
  "filter": {
    "<column_name>": {
      "$contains": "value"
    }
  }
}

Wildcards are supported via the $pattern operator:

{
  "filter": {
    "<column_name>": {
      "$pattern": "v*alu?"
    }
  }
}

The $pattern operator accepts two wildcard characters:

  • * matches zero or more characters
  • ? matches exactly one character

If you want to match a string that contains a wildcard character, you can escape them using a backslash (\). You can escape a backslash by usign another backslash.

We could also have $endsWith and $startsWith operators:

{
  "filter": {
    "<column_name>": {
      "$endsWith": ".gz"
    },
    "<column_name>": {
      "$startsWith": "tmp-"
    }
  }
}

Numeric or datetime ranges

{
  "filter": {
    "<column_name>": {
      "$ge": 0,
      "$lt": 100
    }
  }
}

Date ranges support the same operators, with the date using the format defined in RFC 3339:

{
  "filter": {
    "<column_name>": {
      "$gt": "2019-10-12T07:20:50.52Z",
      "$lt": "2021-10-12T07:20:50.52Z"
    }
  }
}

The supported operators are $gt, $lt, $ge, $le.

Negations

A general $not operator can inverse any operation.

{
  "filter": {
    "$not": {
      "<column_name1>": "value1",
      "<column_name2>": "value1"
    }
  }
}

Note: in the above the two condition are AND together, so this does (NOT ( ... AND ...))

Or more complex:

{
  "filter": {
    "$not": {
      "$any": [
        {
          "<column_name1>": "value1"
        },
        {
          "$all": [
            {
              "<column_name2>": "value2"
            },
            {
              "<column_name3>": "value3"
            }
          ]
        }
      ]
    }
  }
}

The $not: { $any: {}} can be shorted using the $none operator:

{
  "filter": {
    "$none": {
      "<column_name1>": "value1",
      "<column_name2>": "value1"
    }
  }
}

In addition, you can use operators like $isNot or $notExists to simplify expressions:

{
  "filter": {
    "<column_name>": {
      "$isNot": "2019-10-12T07:20:50.52Z"
    }
  }
}

Working with arrays

To test that an array contains a value, use $includes.

{
  "filter": {
    "<array_name>": {
      "$includes": "value"
    }
  }
}

The $includes operator accepts a custom predicate that will check if any array values matches the predicate. For example a complex predicate can include the $all , $contains and $endsWith operators:

{
  "filter": {
    "<array name>": {
      "$includes": {
        "$all": [
          { "$contains": "label" },
          { "$not": { "$endsWith": "-debug" } }
        ]
      }
    }
  }
}

The $includes all operator succeeds if any column in the array matches the predicate. The $includesAll operator succeeds if all array items match the predicate. The $includesNone operator succeeds if no array item matches the predicate. The $includes operator is a synonym for the $includesAny operator.

Here is an example of using the $includesAll operator:

{
  "filter": {
    "settings.labels": {
      "$includesAll": [{ "$contains": "label" }]
    }
  }
}

The above matches if all label values contain the string "labels".

Sorting

Sorting by one element:

POST /db/demo:main/tables/table/query
{
  "sort": {
    "index": "asc"
  }
}

or descendently:

POST /db/demo:main/tables/table/query
{
  "sort": {
    "index": "desc"
  }
}

Sorting by multiple fields:

POST /db/demo:main/tables/table/query
{
  "sort": [
    {
      "index": "desc"
    },
    {
      "createdAt": "desc"
    }
  ]
}

Pagination

We offer cursor pagination and offset pagination. The offset pagination is limited in the amount of data it can retrieve, so we recommend the cursor pagination if you have more than 1000 records.

Example of size + offset pagination:

POST /db/demo:main/tables/table/query
{
  "page": {
    "size": 100,
    "offset": 200
  }
}

The page.size parameter represents the maximum number of records returned by this query. It has a default value of 20 and a maximum value of 200. The page.offset parameter represents the number of matching records to skip. It has a default value of 0 and a maximum value of 800.

Example of cursor pagination:

POST /db/demo:main/tables/table/query
{
  "page": {
    "after":"fMoxCsIwFIDh3WP8c4amDai5hO5SJCRNfaVSeC9b6d1FD"
  }
}

In the above example, the value of the page.after parameter is the cursor returned by the previous query. A sample response is shown below:

{
  "meta": {
    "page": {
      "cursor": "fMoxCsIwFIDh3WP8c4amDai5hO5SJCRNfaVSeC9b6d1FD",
      "more": true
    }
  },
  "records": [...]
}

The page object might contain the follow keys, in addition to size and offset that were introduced before:

  • after: Return the next page 'after' the current cursor
  • before: Return the previous page 'before' the current cursor.
  • first: Return the first page in the table from a cursor.
  • last: Return the last N records in the table from a cursor, where N is the page.size parameter.

The request will fail if an invalid cursor value is given to page.before, page.after, page.first , or page.last. No other cursor setting can be used if page.first or page.last is set in a query.

If both page.before and page.after parameters are present we treat the request as a range query. The range query will return all entries after page.after, but before page.before, up to page.size or the maximum page size. This query requires both cursors to use the same filters and sort settings, plus we require page.after < page.before. The range query returns a new cursor. If the range encompass multiple pages the next page in the range can be queried by update page.after to the returned cursor while keeping the page.before cursor from the first range query.

The filter , columns, sort , and page.size configuration will be encoded with the cursor. The pagination request will be invalid if filter or sort is set. The columns returned and page size can be changed anytime by passing the columns or page.size settings to the next query.

Special cursors:

  • page.after=end: Result points past the last entry. The list of records returned is empty, but page.meta.cursor will include a cursor that can be used to "tail" the table from the end waiting for new data to be inserted.
  • page.before=end: This cursor returns the last page.
  • page.first=<cursor>: Go to first page. This is equivalent to querying the first page without a cursor but filter and sort . Yet the page.first cursor can be convenient at times as user code does not need to remember the filter, sort, columns or page size configuration. All these information are read from the cursor.
  • page.last=<cursor>: Go to the end of the table. This is equivalent to querying the last page with page.before=end, filter, and sort . Yet the page.last cursor can be more convenient at times as user code does not need to remember the filter, sort, columns or page size configuration. All these information are read from the cursor.

When using special cursors like page.after="end" or page.before="end", we still allow filter and sort to be set.

Example of getting the last page:

POST /db/demo:main/tables/table/query
{
  "page": {
    "size": 10,
    "before": "end"
  }
}
Request Body Type Definition
type QueryTable = {
    filter?: FilterExpression;
    sort?: SortExpression;
    page?: PageConfig;
    columns?: ColumnsProjection;
};

/**
 * @minProperties 1
 */
type FilterExpression = {
    $exists?: string;
    $existsNot?: string;
    $any?: FilterList;
    $all?: FilterList;
    $none?: FilterList;
    $not?: FilterList;
} & {
    [key: string]: FilterColumn;
};

type SortExpression = string[] | {
    [key: string]: SortOrder;
} | {
    [key: string]: SortOrder;
}[];

/**
 * Pagination settings.
 */
type PageConfig = {
    /*
     * Query the next page that follow the cursor.
     */
    after?: string;
    /*
     * Query the previous page before the cursor.
     */
    before?: string;
    /*
     * Query the first page from the cursor.
     */
    first?: string;
    /*
     * Query the last page from the cursor.
     */
    last?: string;
    /*
     * Set page size. If the size is missing it is read from the cursor. If no cursor is given xata will choose the default page size.
     *
     * @default 20
     */
    size?: number;
    /*
     * Use offset to skip entries. To skip pages set offset to a multiple of size.
     *
     * @default 0
     */
    offset?: number;
};

type ColumnsProjection = string[];

type FilterList = FilterExpression | FilterExpression[];

type FilterColumn = FilterColumnIncludes | FilterPredicate | FilterList;

type SortOrder = "asc" | "desc";

/**
 * @maxProperties 1
 * @minProperties 1
 */
type FilterColumnIncludes = {
    $includes?: FilterPredicate;
    $includesAny?: FilterPredicate;
    $includesAll?: FilterPredicate;
    $includesNone?: FilterPredicate;
};

type FilterPredicate = FilterValue | FilterPredicate[] | FilterPredicateOp | FilterPredicateRangeOp;

type FilterValue = number | string | boolean;

/**
 * @maxProperties 1
 * @minProperties 1
 */
type FilterPredicateOp = {
    $any?: FilterPredicate[];
    $all?: FilterPredicate[];
    $none?: FilterPredicate | FilterPredicate[];
    $not?: FilterPredicate | FilterPredicate[];
    $is?: FilterValue | FilterValue[];
    $isNot?: FilterValue | FilterValue[];
    $lt?: FilterRangeValue;
    $le?: FilterRangeValue;
    $gt?: FilterRangeValue;
    $ge?: FilterRangeValue;
    $contains?: string;
    $startsWith?: string;
    $endsWith?: string;
    $pattern?: string;
};

/**
 * @maxProperties 2
 * @minProperties 2
 */
type FilterPredicateRangeOp = {
    $lt?: FilterRangeValue;
    $le?: FilterRangeValue;
    $gt?: FilterRangeValue;
    $ge?: FilterRangeValue;
};

type FilterRangeValue = number | string;
Possible Responses
Status CodeDescriptionExample Response/Type Definition
200OK
type QueryTable = {
    records: Record[];
    meta: RecordsMetadata;
};

/**
 * Xata Table Record Metadata
 */
type Record = RecordMeta & {
    [key: string]: any;
};

/**
 * Records metadata
 */
type RecordsMetadata = {
    page: {
        /*
         * last record id
         */
        cursor: string;
        /*
         * true if more records can be fetch
         */
        more: boolean;
    };
};

/**
 * Xata Table Record Metadata
 */
type RecordMeta = {
    id: RecordID;
    xata: {
        /*
         * The record's version. Can be used for optimistic concurrency control.
         */
        version: number;
        /*
         * The record's table name. APIs that return records from multiple tables will set this field accordingly.
         */
        table?: string;
        /*
         * Highlights of the record. This is used by the search APIs to indicate which fields and parts of the fields have matched the search.
         */
        highlight?: {
            [key: string]: string[] | {
                [key: string]: any;
            };
        };
        /*
         * The record's relevancy score. This is returned by the search APIs.
         */
        score?: number;
        /*
         * Encoding/Decoding errors
         */
        warnings?: string[];
    };
};

/**
 * @pattern [a-zA-Z0-9_-~:]+
 */
type RecordID = string;
400Bad Request
type QueryTable = {
    id?: string;
    message: string;
};
401Authentication Error
{
  "message": "invalid API key"
}
404Example response
type QueryTable = {
    id?: string;
    message: string;
};
5XXUnexpected Error