# Sorting

## Overview

ViewConnection queries support sorting results by one or more fields. Sorting is specified via the `sort` argument.

## Sort Input Structure

GraphQL

```graphql
sort: [
  {
    field: String!    # Field name to sort by
    mode: SortMode!   # "asc" or "desc"
  }
]
```

## Basic Sorting

Sort by a single field:

GraphQL

```graphql
query {
  orderViewConnection(
    first: 10
    sort: [{ field: "orderDate", mode: "desc" }]
  ) {
    edges {
      node {
        orderId
        orderDate
      }
    }
  }
}
```

## Multi-Field Sorting

Sort by multiple fields (applied in order):

GraphQL

```graphql
query {
  productViewConnection(
    first: 10
    sort: [
      { field: "category", mode: "asc" }
      { field: "sku", mode: "asc" }
    ]
  ) {
    edges {
      node {
        productId
        category
        sku
      }
    }
  }
}
```

## Sort Modes

- `asc` - Ascending order (A-Z, 0-9, oldest to newest)
- `desc` - Descending order (Z-A, 9-0, newest to oldest)

## Sortable Fields

Not all fields support sorting. Field sortability is documented in the reference pages for each collection.

**Common sortable fields:**

- ID fields (`productId`, `orderId`, etc.)
- Date fields (`orderDate`, `createdDate`, etc.)
- Numeric fields (`quantity`, `price`, etc.)
- Text fields (`sku`, `name`, etc.)

## Sorting with Pagination

Combine sorting with pagination for consistent results:

GraphQL

```graphql
query GetOrders($cursor: String) {
  orderViewConnection(
    first: 50
    after: $cursor
    sort: [{ field: "orderDate", mode: "desc" }]
  ) {
    edges {
      node {
        orderId
        orderDate
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```

## Sort Limitations

Some fields may have sorting limitations based on:

- Field parameters (some parameter values disable sorting)
- Database indexes
- Query complexity

These limitations are documented in the field reference pages.

## Best Practices

1. **Always use sorting with pagination** to ensure consistent page boundaries
2. **Sort by unique fields** (like ID) as a tiebreaker for deterministic ordering
3. **Limit number of sort fields** for better performance
4. **Check field documentation** for sorting support before using

## Complete Example

GraphQL

```graphql
query GetRecentOrders {
  orderViewConnection(
    first: 100
    type: ["SALES_ORDER"]
    status: ["OPEN", "IN_PROGRESS"]
    sort: [
      { field: "orderDate", mode: "desc" }
      { field: "orderId", mode: "desc" }
    ]
  ) {
    edges {
      node {
        orderId
        orderDate
        status
        customer {
          name
        }
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
```
