Mastering SearchCriteria in Magento 2 | AND/OR Filters, Pagination, Sorting
AI generated
Magento 2 · Service Contracts

Mastering SearchCriteria
AND/OR Filters, Pagination, Sorting

At first glance, SearchCriteria in Magento 2 looks generic and simple. In practice, though, many implementations fail because of FilterGroup logic, wrong assumptions about AND and OR, or repository queries that are more accidental than the result of deliberate query design.

18 min read Repositories Magento 2.4.8

1. What SearchCriteria in Magento 2 actually is

SearchCriteria Magento 2 is the standardized language repositories use to describe list queries. Instead of thinking directly in terms of collections or SQL, you describe filters, filter groups, page size and sorting in a transportable structure. That matters because service contracts should behave consistently not only locally inside a module, but also across APIs, integrations and tests.

The idea is sound, but it is often only half understood. Many developers treat SearchCriteria Magento 2 as a loose collection of filters without properly understanding the semantic structure behind it. That produces queries which appear to run fine but return incorrect results, because AND and OR behave differently than expected, or because pagination becomes unstable.

The core point is: SearchCriteria is not simply a builder for "a few where conditions." It is a deliberately defined query container, both functionally and technically. Developers who accept that write more understandable repository queries and later have to rescue fewer exceptions, collections or edge cases through custom helper constructs.

2. Understanding AND and OR in SearchCriteria correctly

The most common pitfall in SearchCriteria Magento 2 is the logic of filters and groups. Within a FilterGroup, filters are interpreted as OR. Between multiple FilterGroups, AND applies. Mixing this up easily leads to queries that return far more, or far fewer, records than intended.

That sounds abstract, but it is decisive in everyday work. If, for example, you search for products that are active and match either a specific website or a specific type, you have to group the conditions deliberately. Otherwise the query behaves logically differently from the developer's mental model. That is exactly why you should not "click together" SearchCriteria Magento 2, but design it as a boolean structure.


<?php
declare(strict_types=1);

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\FilterGroupBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;

$isActiveFilter = $filterBuilder
    ->setField('is_active')
    ->setConditionType('eq')
    ->setValue(1)
    ->create();

$websiteFilter = $filterBuilder
    ->setField('website_id')
    ->setConditionType('eq')
    ->setValue(1)
    ->create();

$typeFilter = $filterBuilder
    ->setField('type_id')
    ->setConditionType('eq')
    ->setValue('simple')
    ->create();

$orGroup = $filterGroupBuilder->setFilters([$websiteFilter, $typeFilter])->create();
$andGroup = $filterGroupBuilder->setFilters([$isActiveFilter])->create();

$criteria = $searchCriteriaBuilder
    ->setFilterGroups([$andGroup, $orGroup])
    ->create();

This structure means: active AND (website 1 OR type simple). Anyone who blindly puts the same filters into the same group ends up with a different statement. This is exactly where solid query design separates itself from trial-and-error. Good SearchCriteria Magento 2 implementations are readable because the group logic is formulated deliberately.

3. Using pagination and page sizes cleanly

Pagination is often treated as a minor parameter, but it is actually an important part of query quality. SearchCriteria Magento 2 allows a controlled subset via setCurrentPage() and setPageSize(). This is essential for admin listings, API endpoints and integrations, because otherwise data volumes become unnecessarily large, slow or memory-intensive.

The combination with stable sorting matters here. A paginated query without a well-defined sort order can produce unreliable pages when data changes between two calls. Records then appear duplicated or seem to disappear. In stable systems, SearchCriteria Magento 2 is therefore never considered in isolation from page size, but always together with a traceable sort order.


$criteria = $searchCriteriaBuilder
    ->setCurrentPage(2)
    ->setPageSize(50)
    ->create();

Pagination matters from a business perspective too. APIs and backoffice flows should not load more data than the specific step actually needs. Fetching everything "just to be safe" undermines the actual strength of the repository and SearchCriteria approach.

This is especially decisive for synchronizations with external systems. When a connector fetches data page by page, page size, order and change window all have to work together cleanly. Otherwise you get duplicate records, gaps or unnecessarily high load spikes. Good SearchCriteria Magento 2 pagination is therefore not just a UI topic, but part of resilient integration architecture.

4. Controlling sorting deliberately with SortOrder

Sorting in SearchCriteria Magento 2 is more than cosmetics. It affects result stability, usability and, in some cases, performance too. Via SortOrder you can define which field and direction to sort by. The sort order should match the business question while remaining reproducible for paginated results.

This is especially critical for APIs. When an integration partner pulls "the next 100 records," it needs a reliable order. A random or implicit ordering produces follow-on errors that are hard to trace. Good use of SearchCriteria Magento 2 therefore separates filter logic from transport logic: What data do I want? And in what order is it delivered?


<?php
declare(strict_types=1);

use Magento\Framework\Api\SortOrder;
use Magento\Framework\Api\SortOrderBuilder;

$sortOrder = $sortOrderBuilder
    ->setField('created_at')
    ->setDirection(SortOrder::SORT_DESC)
    ->create();

$criteria = $searchCriteriaBuilder
    ->addSortOrder($sortOrder)
    ->create();

Especially in combination with pagination, the sort order should be unambiguous enough. If multiple records share the same timestamp or status, an additional secondary field can be worthwhile. The goal is not elegance, it is reproducibility.

5. SearchCriteria in repository practice

In practice, SearchCriteria Magento 2 is most valuable when service contracts are designed deliberately. The repository should return a business-meaningful list, not just some technical collection wrapper. Good repositories document which fields are filterable, which condition types are supported and which sort fields work reliably.

It is also worth building recurring criteria centrally. When the same logic is needed in multiple places, it should not be reassembled from scratch in ten different classes. Instead, a small builder or query service can bundle the search logic. That is exactly what keeps SearchCriteria Magento 2 consistent instead of turning into a confusing patchwork across the project.

Another point is expectation management. SearchCriteria is powerful, but not limitless. Very specialized or highly optimized data access sometimes still needs its own collection strategy or a separate read model. As long as that decision is made deliberately, it is no contradiction to the service contract approach, it is good engineering.

Within a team, a small query convention is also worthwhile. Which fields are officially filterable? Which condition types count as supported? What are the standards for default sorting and maximum page size? Rules like these sound minor, but they prevent SearchCriteria Magento 2 from being used differently from module to module, leaving API consumers struggling with inconsistent behavior.

6. Common mistakes

The most common mistake is a wrong understanding of FilterGroups. After that come unclear pagination, missing sorting, and the assumption that every complex business query must automatically flow elegantly through a single SearchCriteria. It is also common for developers to reuse individual filter builders, unintentionally carrying over state along the way.

In code reviews you often see SearchCriteria Magento 2 code that works technically but is unreadable from a business standpoint. Five filters, three groups and two sort orders without descriptive variable names create exactly the kind of maintenance cost that service contracts were meant to reduce. Query code should be as readable as good business logic.

Another mistake is using SearchCriteria where a targeted single query or another read path would actually be a better fit. Standardization is good, but not every problem becomes nicer through the same API. What matters is that SearchCriteria Magento 2 is used deliberately rather than reflexively.

7. SearchCriteria vs. direct Collection

The choice between a repository using SearchCriteria Magento 2 and a direct collection is not purely a matter of style. SearchCriteria is ideal for standardized service contract queries, API usage and reusable filter logic. Direct collections can make sense when a highly specialized internal read path needs special joins, aggregations or optimizations.

Approach Well suited for Limitation
SearchCriteria Standardized list queries across repositories and APIs Not every special query stays elegant or performant this way
Direct Collection Internal edge cases with their own optimization logic Less standardized and harder to abstract externally
Hybrid Repository for standard cases, dedicated read model for exceptions Needs clear boundaries of responsibility

The most important rule remains: repository code should be understandable. If SearchCriteria Magento 2 achieves that, it is the right path. If it tends to obscure the business truth instead, the solution may need a different cut.

Mironsoft

Magento 2 service contracts, repository design and API-oriented module architecture

Ready to make your repository queries finally understandable?

We structure repositories, SearchCriteria builders and read paths so that filter logic, pagination and sorting stay understandable from a business perspective and do not create new side effects with every change.

Filter logic

Modeling AND/OR structures and FilterGroups readably

Pagination

Stabilizing page logic and sorting for APIs and admin flows

Architecture

Cleanly separating repositories, collections and special reads

9. Summary

SearchCriteria Magento 2 is at its strongest when FilterGroups, pagination and sorting are used deliberately and readably. Good repository queries reflect the business question rather than just "somehow fetching data" on a technical level.

The most common problems don't come from the framework itself, but from unclear boolean logic and unstable page results. Anyone who takes SearchCriteria seriously as a query language avoids many hidden bugs and builds cleaner service contracts in the long run.

SearchCriteria Magento 2, the essentials at a glance

Logic

Within a FilterGroup, OR applies; between groups, AND applies.

Pagination

Reliable page results only come with stable sorting.

Sorting

SortOrder is part of query quality, not just a UI concern.

Practice

Centralize recurring search logic and keep repository code readable.

10. FAQ: SearchCriteria in Magento 2

1 What is SearchCriteria in Magento 2?
A standardized query structure for repository lists.
2 How do AND and OR work?
OR within a FilterGroup, AND between multiple groups.
3 Why is this often a problem?
Because the group logic in a developer's head and in the code is often not modeled identically.
4 Why does pagination matter?
Because lists and APIs should only process controlled amounts of data cleanly.
5 Why does pagination need sorting?
So that pages stay reproducible when data changes.
6 When is it better than a Collection?
For standardized service contract and API queries.
7 When does a Collection make sense?
For specialized internal read paths with their own optimization logic.
8 What is the most common mistake?
Unclear FilterGroups and missing stable sorting.
9 Should query logic be centralized?
Yes, recurring search logic belongs in builders or query services.
10 What is the most important review point?
Whether the business search intent is clearly and reproducibly visible in the code.