Implementing Filtering and Sorting
1. Defining Filter Input Types
Example: Composable filter
input PostFilter {
AND: [PostFilter!]
OR: [PostFilter!]
NOT: PostFilter
title: StringFilter
status: OrderStatus
createdAt: DateFilter
}
2. Using Comparison Operators
| Operator | Field |
|---|---|
| eq | Equals |
| ne | Not equals |
| gt / gte / lt / lte | Comparison |
| in / nin | Set membership |
3. Using Logical Operators
Example: AND/OR/NOT
{
posts(filter: {
AND: [
{ status: PUBLISHED }
{ OR: [{ title: { contains: "graphql" } }, { tags: { in: ["api"] } }] }
]
}) { id }
}
4. Implementing String Filters
| Operator | Use |
|---|---|
| eq / ne | Exact |
| contains | Substring (LIKE %x%) |
| startsWith / endsWith | Prefix/suffix |
| matches | Regex (use cautiously) |
| caseSensitive | Toggle collation |
5. Implementing Date Filters
Example: Date filter
input DateFilter {
eq: DateTime
gte: DateTime
lte: DateTime
between: [DateTime!] # exactly 2
}
6. Implementing Null Filters
| Operator | Behavior |
|---|---|
| isNull: true | WHERE x IS NULL |
| isNull: false | WHERE x IS NOT NULL |
| eq: null | Avoid — ambiguous in some ORMs |
7. Defining Sort Input Types
Example: Sort input
enum PostSortField { CREATED_AT TITLE LIKES_COUNT }
enum SortDirection { ASC DESC }
input PostOrderBy {
field: PostSortField!
direction: SortDirection! = DESC
}
8. Using Sort Direction
| Direction | SQL |
|---|---|
| ASC | ORDER BY x ASC |
| DESC | ORDER BY x DESC |
| Nulls | NULLS FIRST/LAST option |
9. Implementing Multi-field Sorting
Example: Multi-field sort
{
posts(orderBy: [
{ field: STATUS, direction: ASC }
{ field: CREATED_AT, direction: DESC }
]) { id title }
}
10. Combining Filters and Sorting
| Pattern | Detail |
|---|---|
| filter + orderBy + pagination | Standard list query signature |
| Index alignment | Cover (filter, sort) columns with composite index |
| Stable sort | Append id as final sort key for cursor pagination |