# Filtering, sorting, searching and field selection

> How would you design filtering, sorting, searching and sparse field selection on a list endpoint?

Canonical: https://www.internhack.in/learn/interview/api-design-interview/api-filtering-sorting-fields
Last updated: 2026-11-28

Difficulty: Beginner

## Question

How would you design filtering, sorting, searching and sparse field selection on a list endpoint?

## Answer

Once an endpoint returns a list, clients immediately want to narrow it: only paid orders, only from last week, cheapest first, and just the fields needed for a table. The design goal is to give expressive power without inventing a query language that becomes impossible to secure and document. Think of a restaurant menu with sections: you offer sensible filters, not a way for guests to write SQL.

Filtering is usually done with query parameters that map to fields: GET /orders?status=paid&customer_id=42. For multiple values, pick one convention: status=paid,shipped or repeated status=paid&status=shipped. For ranges, use suffixes or brackets: created_at\[gte\]=2026-09-01&created_at\[lt\]=2026-10-01, or created_after and created_before. Stripe uses bracket operators; many teams prefer simple named params for readability. Whatever you pick, document it and use it everywhere.

Sorting: use a sort parameter with a leading minus for descending, and commas for multiple keys: sort=-created_at,total. Whitelist sortable fields, and make sure they are backed by indexes; allowing sort on arbitrary columns is an easy way to create slow queries. Always include a tiebreaker, such as id, so ordering is deterministic and pagination remains stable.

Searching is different from filtering. Filtering is exact or range matching on structured fields; search is relevance-ranked text matching. Use q=biryani for free text, and route it to a proper index such as Postgres full text search, Elasticsearch or OpenSearch rather than LIKE '%term%' on a big table. Keep the response shape the same.

Field selection, sometimes called sparse fieldsets: fields=id,status,total lets mobile clients trim payloads. Related to that is expansion or embedding: expand=customer,items inlines related resources so that the client avoids extra round trips, as in Stripe's expand parameter. These two features are how REST APIs address over-fetching and under-fetching without going to GraphQL. Watch out for expansion depth, which can cause heavy joins and N+1 queries, so cap it.

Validation and safety: treat all of these parameters as untrusted input. Whitelist filter fields and operators, validate types, return 400 or 422 with a clear error for unknown params rather than silently ignoring them, since silent ignoring gives clients a false impression that the filter worked. Never concatenate values into SQL; use parameterised queries or an ORM. Enforce maximum page size and maximum filter complexity.

Also consider consistency with caching: query strings form part of the cache key, so normalise parameter order when possible. And decide whether filters combine with AND (the usual default) and how to express OR, which most APIs handle with multiple-value params on one field rather than arbitrary boolean logic.

If requirements become very complex, with arbitrary nested filters and dynamic projections, that is a signal to consider GraphQL or a dedicated search endpoint, rather than pushing REST query strings further.

## Code examples

### Filter, sort, fields and expand in one request

```
GET /v1/orders?status=paid,shipped&created_at[gte]=2026-09-01&sort=-created_at,id&fields=id,status,total&expand=customer&limit=20 HTTP/1.1
Host: api.example.com
```

Multi-value filter, range operator, multi-key sort with tiebreaker, sparse fields, and expansion of the customer relation.

### Whitelisting sort fields

```
const SORTABLE = new Set(['created_at', 'total', 'id']);
function parseSort(param = '-created_at') {
  return param.split(',').map((s) => {
    const desc = s.startsWith('-');
    const field = desc ? s.slice(1) : s;
    if (!SORTABLE.has(field)) throw Object.assign(new Error('Unknown sort field: ' + field), { status: 400 });
    return { field, dir: desc ? 'DESC' : 'ASC' };
  });
}
```

Only indexed, allowed columns can be sorted, and unknown ones produce a clear 400.

## Key points

- Whitelist filterable and sortable fields and back them with indexes.
- Search is relevance based and belongs in a search index, not LIKE queries.
- Unknown parameters should fail loudly, not be ignored.
- Sparse fields and expand reduce over and under fetching.
- Always add a tiebreaker to sorts.

## Common follow-up questions

- How do you express OR conditions?
- What are the risks of an expand parameter?
- When would you move to GraphQL instead?

## Interview tips

- Distinguish filter from search; many candidates conflate them.
- Mention indexes; sorting and filtering without them will not survive production.

## Concepts covered

filtering, sorting, field selection, query parameters

Previous: [Pagination: offset vs cursor (keyset) trade-offs](https://www.internhack.in/learn/interview/api-design-interview/api-offset-vs-cursor-pagination) · Next: [API versioning strategies and trade-offs](https://www.internhack.in/learn/interview/api-design-interview/api-versioning) · [All of API Design](https://www.internhack.in/learn/interview/api-design-interview)

## More API Design questions

- [Idempotency keys for payments and retries](https://www.internhack.in/learn/interview/api-design-interview/api-idempotency-keys-payments)
- [Rate limiting: algorithms, headers and 429 handling](https://www.internhack.in/learn/interview/api-design-interview/api-rate-limiting-token-bucket)
- [API keys vs OAuth 2.0 vs JWT: choosing authentication](https://www.internhack.in/learn/interview/api-design-interview/api-authn-keys-oauth-jwt)
- [Access tokens vs refresh tokens and token lifecycle](https://www.internhack.in/learn/interview/api-design-interview/api-access-refresh-tokens)
- [Authorization: RBAC, scopes and object-level checks](https://www.internhack.in/learn/interview/api-design-interview/api-authorization-rbac-scopes)
- [CORS: what it is and how preflight works](https://www.internhack.in/learn/interview/api-design-interview/api-cors)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [API Design](https://www.internhack.in/learn/interview/api-design-interview)
