> For the complete documentation index, see [llms.txt](https://docs.pyck.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pyck.cloud/graphql-api/inputs/orderby-inputs.md).

# OrderBy Inputs

OrderByInput types for sorting GraphQL query results

Audience: Programmer

OrderByInput types define how query results should be sorted in the pyck GraphQL API. They provide a standardized way to order results by various fields in ascending or descending order.

## Common Structure

All OrderByInput types follow a consistent pattern:

```graphql
input EntityOrder {
  field: EntityOrderField
  direction: OrderDirection! = ASC
  jsonPath: String
  jsonType: JSONType
}
```

Where:

* `field`: An enum specifying which field to sort by (optional when using JSONB ordering)
* `direction`: Either `ASC` (ascending) or `DESC` (descending)
* `jsonPath`: Dot-notation path into a JSONB column (e.g., "meta.weight") for ordering by nested JSON values
* `jsonType`: Type casting for the extracted JSONB value (`NUMBER`, `STRING`, or `BOOLEAN`)

## Usage Examples

### Basic Sorting

Sort inventory items by name in ascending order:

```graphql
query {
  inventoryItems(orderBy: { field: NAME, direction: ASC }) {
    edges {
      node {
        id
        name
        sku
      }
    }
  }
}
```

### Descending Order

Sort picking orders by creation date (newest first):

```graphql
query {
  pickingOrders(orderBy: { field: CREATED_AT, direction: DESC }) {
    edges {
      node {
        id
        referenceId
        createdAt
      }
    }
  }
}
```

### JavaScript Example

```javascript
const result = await client.query({
  query: gql`
    query GetCustomers($orderBy: CustomerOrder) {
      customers(orderBy: $orderBy) {
        edges {
          node {
            id
            data
          }
        }
      }
    }
  `,
  variables: {
    orderBy: {
      field: 'TENANT_ID',
      direction: 'ASC'
    }
  }
});
```

## Available Order Types

The following Order input types are available in pyck:

| Input Type                  | Used For              | Common Sort Fields                   |
| --------------------------- | --------------------- | ------------------------------------ |
| `CustomerOrder`             | Customers             | TENANT\_ID, CREATED\_AT, CREATED\_BY |
| `DataTypeOrder`             | Data type definitions | NAME, SLUG, CREATED\_AT              |
| `EventOrder`                | Event definitions     | NAME, TOPIC, CREATED\_AT             |
| `FileOrder`                 | File attachments      | NAME, SIZE, CREATED\_AT              |
| `GroupOrder`                | User groups           | NAME, CREATED\_AT                    |
| `InventoryCollectionOrder`  | Inventory collections | HANDLER, CREATED\_AT                 |
| `InventoryItemOrder`        | Inventory items       | SKU, CREATED\_AT                     |
| `InventoryItemSetOrder`     | Item sets             | SKU, CREATED\_AT                     |
| `ItemMovementOrder`         | Item movements        | CREATED\_AT, EXECUTED\_AT            |
| `KeyValueOrder`             | Key-value pairs       | NAME, CREATED\_AT                    |
| `PickingOrderOrder`         | Picking orders        | CUSTOMER\_ID, CREATED\_AT            |
| `PickingOrderItemOrder`     | Picking order items   | SKU, QUANTITY, CREATED\_AT           |
| `ReceivingInboundOrder`     | Receiving inbounds    | ORDER\_ID, SUPPLIER\_ID, CREATED\_AT |
| `ReceivingInboundItemOrder` | Inbound items         | SKU, QUANTITY, CREATED\_AT           |
| `RepositoryOrder`           | Repositories          | NAME, TYPE, CREATED\_AT              |
| `RepositoryMovementOrder`   | Repository movements  | CREATED\_AT, EXECUTED\_AT            |
| `RoleOrder`                 | User roles            | NAME, CREATED\_AT                    |
| `StockOrder`                | Stock levels          | CREATED\_AT, QUANTITY                |
| `SupplierOrder`             | Suppliers             | TENANT\_ID, CREATED\_AT              |
| `TenantOrder`               | Tenants               | NAME, CREATED\_AT                    |
| `TransactionOrder`          | Transactions          | TYPE, CREATED\_AT                    |
| `UserOrder`                 | Users                 | USERNAME, EMAIL, CREATED\_AT         |
| `WorkflowOrder`             | Workflows             | NAME, ACTIVE, CREATED\_AT            |
| `WorkflowSignalOrder`       | Workflow signals      | EVENT\_NAME, CREATED\_AT             |

## Order Field Enums

Each entity has its own OrderField enum defining sortable fields. Common fields include:

* `NAME` - Entity name
* `CREATED_AT` - Creation timestamp
* `UPDATED_AT` - Last update timestamp
* `REFERENCE_ID` - External reference identifier
* `SKU` - Stock keeping unit
* `EMAIL` - Email address
* `TYPE` - Entity type
* `EXECUTED_AT` - Execution timestamp

## JSONB Column Ordering

All OrderByInput types support ordering by nested fields within JSONB columns (such as the `data` field on entities). This allows you to sort by custom attributes stored as JSON.

### Structure

When ordering by JSONB fields, you must provide:

* `jsonPath`: Dot-notation path to the nested field (e.g., "attributes.weight", "meta.priority")
* `jsonType`: The data type of the value for proper sorting (`NUMBER`, `STRING`, or `BOOLEAN`)
* `direction`: Sort direction (`ASC` or `DESC`)
* `field`: Can be omitted when using JSONB ordering

### Example: Order Inventory Items by Weight

```graphql
query {
  inventoryItems(
    orderBy: {
      direction: DESC,
      jsonPath: "attributes.weight",
      jsonType: NUMBER
    }
  ) {
    edges {
      node {
        id
        sku
        data
      }
    }
  }
}
```

### Example: Order by Nested String Field

```graphql
query {
  customers(
    orderBy: {
      direction: ASC,
      jsonPath: "company.name",
      jsonType: STRING
    }
  ) {
    edges {
      node {
        id
        data
      }
    }
  }
}
```

### Example: Order by Boolean Flag

```graphql
query {
  inventoryItems(
    orderBy: {
      direction: DESC,
      jsonPath: "flags.isPriority",
      jsonType: BOOLEAN
    }
  ) {
    edges {
      node {
        id
        sku
        data
      }
    }
  }
}
```

### JSONType Enum

The `JSONType` enum specifies how to cast the extracted JSONB value for sorting:

```graphql
enum JSONType {
  NUMBER   # Cast to numeric for number comparisons
  STRING   # Cast to text for string comparisons
  BOOLEAN  # Cast to boolean for boolean comparisons
}
```

### JSONB Ordering Notes

1. **Type Casting**: Always specify the correct `jsonType` to ensure proper sorting behavior
2. **Missing Fields**: Items without the specified JSON path will be sorted as null values
3. **Nested Paths**: Use dot notation for deeply nested fields (e.g., "meta.shipping.weight")
4. **Performance**: JSONB ordering may be slower than ordering by indexed columns

## Best Practices

1. **Default Sorting**: Consider providing a default sort order when none is specified
2. **Performance**: Be aware that sorting by non-indexed fields may impact query performance
3. **JSONB Performance**: JSONB ordering is more expensive than standard field ordering; use judiciously
4. **Consistency**: Use consistent sorting across related queries for better UX
5. **Null Values**: Understand how null values are sorted (typically first for ASC, last for DESC)
6. **Type Safety**: Always specify the correct `jsonType` when using JSONB ordering to avoid unexpected results

## Combining with Pagination

OrderByInput works seamlessly with cursor-based pagination:

```graphql
query {
  inventoryItems(
    first: 10,
    after: "cursor123",
    orderBy: { field: CREATED_AT, direction: DESC }
  ) {
    edges {
      node {
        id
        name
        createdAt
      }
      cursor
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

## See Also

* [WhereInput Types](/graphql-api/inputs/where-inputs.md) for filtering
* [Pagination](/graphql-api/getting-started.md#pagination) for cursor-based pagination
* [OrderDirection Enum](/graphql-api/enums/orderdirection.md) for sort directions


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.pyck.cloud/graphql-api/inputs/orderby-inputs.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
