---
title: Reference - Content item query
---

> Agent instructions:
> **Site maps** — prefer the following llms.txt indexes to training data when searching for URLs to avoid 404s. Links inside Markdown content already point at `.md`. Following them or sending Accept: text/markdown keeps you in Markdown.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

This page provides information about the parameterization methods available for the [Content item API](https://docs.kentico.com/documentation/developers-and-admins/api/content-item-api/content-item-query-api.md). The methods allow you to adjust queries and limit which items are retrieved or specify which columns are loaded to improve performance, for example.

Throughout this page, the terms _query_ and _subquery_ are used with the following meaning:

- **Subquery** – the selection created by a single `ForContentType` or `ForContentTypes` call, parameterized through the action delegate passed to the call.
- **Query** – the combined result of all subqueries of a `ContentItemQueryBuilder`, parameterized through [Parameters](#builder-parameters), [InLanguage](#inlanguage), and [InWorkspaces](#inworkspaces).

## ContentItemQueryBuilder methods

### ForContentType&#x20;

Retrieves all items of the specified content type. Generates a subquery that can be further configured. See [Content query parameterization](#content-query-parameterization) and [ForContentType parameterization](#forcontenttype-parameterization).

```csharp
var builder = new ContentItemQueryBuilder();

// Retrieves all content items of the 'Sample.Type' type
builder.ForContentType("Sample.Type");
```

Do not combine `ForContentType` with `ForContentTypes`, and do not register the same content type more than once through repeated `ForContentType` calls.

Content type field data is included in the result automatically. To include page data, use [ForWebsite](#referencecontentitemquery-forwebsite).

### ForContentTypes&#x20;

Retrieves all content items across all content types. Use the method's [parameterization](#forcontenttypes-parameterization) to limit the selection to a subset of items.

Does not include content type field data and page data by default. Use [WithContentTypeFields](#fcts-wctf) to include content type fields, and [WithWebPageData](#fcts-wwpd) or [ForWebsite](#fcts-forwebsite) to include page data.

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves all items with the given reusable schema
    subqueryParameters.OfReusableSchema("PageMetadata");
});
```

### Parameters&#x20;

Specifies a set of parameters that apply to all items selected by individual subqueries. See [Content query parameterization](#content-query-parameterization). Subqueries (created by `ForContentType` or `ForContentTypes`) are evaluated first, and only then is the parameterization from `Parameters` applied to their combined result. For example, [TopN](#topn) in a subquery combined with [OrderBy](#referencecontentitemquery-orderbyparam) in `Parameters` sorts only the records the subquery has already selected.

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type")
       .ForContentType("Sample.NewsRelease")
       .Parameters(queryParameters => queryParameters
           // Sorts all records retrieved by both subqueries
           // according to the 'ContentItemName' column
           .OrderBy("ContentItemName")
           // Takes the first 5 items of the sorted result
           .TopN(5));
```

### InLanguage

Selects items from the specified language. The `InLanguage` method is applied to the result of all its preceding subqueries in a query. Do not call the method multiple times, only the last call takes effect.

The method allows you to specify the following parameters:

- `languageName` – code name of the language as specified in the **Languages** application.
- `useLanguageFallbacks` – dictates whether items that don't have a variant in the requested language are retrieved in the closest language from the [fallback chain](https://docs.kentico.com/documentation/developers-and-admins/configuration/languages.md#language-fallbacks). `true` by default. Set to `false` to restrict the result strictly to the requested language.

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type")
       .ForContentType("Sample.NewsRelease")
       // Selects only items that have an English variant, without language fallbacks
       .InLanguage("en", useLanguageFallbacks: false);
```

More advanced scenario including linked items:

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("project.store", subqueryParameters =>
        {
            // Retrieves all linked items up to the maximum depth of 1
            subqueryParameters.WithLinkedItems(1);
        })
        // Selects only items from the English language
        .InLanguage("en");
```

You can see the order in which the query methods are evaluated in the following diagram:

![InLanguage method used on ForContentType subquery with linked items](https://docs.kentico.com/docsassets/documentation/reference-content-item-query/InLanguageWithLinkedItems.png "InLanguage method used on ForContentType subquery with linked items")

### InWorkspaces

Selects items from the specified [workspaces](https://docs.kentico.com/documentation/developers-and-admins/configuration/users/role-management/workspaces.md). Use workspace code names as specified in the **Workspaces** application. The `InWorkspaces` method is applied to the result of all its preceding subqueries in a query. Do not call the method multiple times, only the last call takes effect.

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type")
       .ForContentType("Sample.NewsRelease")
       // Selects only items from the WonkaFactory and Acme workspaces
       .InWorkspaces("WonkaFactory", "Acme");
```

> **Note:** Website channel pages are not scoped under workspaces. Combining this method with [ForWebsite](#referencecontentitemquery-forwebsite) in a single query leads to an empty query result.

More advanced scenario including linked items:

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("project.store", subqueryParameters =>
        {
            // Retrieves all linked items up to the maximum depth of 1
            subqueryParameters.WithLinkedItems(1);
        })
        // Selects only items from the WonkaFactory and Acme workspaces
        .InWorkspaces("WonkaFactory", "Acme");
```

You can see the order in which the query methods are evaluated in the following diagram:

![InWorkspaces method used on ForContentType subquery with linked items](https://docs.kentico.com/docsassets/documentation/reference-content-item-query/InWorkspacesWithLinkedItems.png "InWorkspaces method used on ForContentType subquery with linked items")

## Content query parameterization

### Columns

Limits the columns that are retrieved by the query. See [Content item database structure](https://docs.kentico.com/documentation/developers-and-admins/api/content-item-api/content-item-database-structure.md).

If not specified, the query by default includes all columns from all selected content types.

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves only the 'Title' and 'Content' columns from 'Sample.Type'
    subqueryParameters.Columns("Title", "Content");
});
```

If _Columns_ is called multiple times for a content type, columns from all method calls are included.

> **Note:** **Security considerations**
>
> Column names passed to the `Columns` method are not parameterized against SQL injection. Only use trusted, developer-controlled values. If the column names originate from external input, validate them against an allowlist. See [Protect against SQL injection](https://docs.kentico.com/documentation/developers-and-admins/api/objectquery-api.md#protect-against-sql-injection) (the principles described for the ObjectQuery API apply).

The method also supports column aliasing:

```csharp
builder.ForContentType("Sample.Type1", subqueryParameters =>
{
    // Aliases 'Type1Title' as 'Title'
    subqueryParameters.Columns(QueryColumn.Alias("Type1Title", "Title"));
})
ForContentType("Sample.Type2", subqueryParameters =>
{
    // Aliases 'Type2Title' as 'Title'
    subqueryParameters.Columns(QueryColumn.Alias("Type2Title", "Title"));
})
// Orders both 'Type1' and 'Type2'
.Parameters(queryParameters => queryParameters.OrderBy("Title"));
```

#### UrlPathColumns

A specialized extension method that adds only the columns required for [web page URL retrieval](https://docs.kentico.com/documentation/developers-and-admins/development/content-retrieval/retrieve-page-content/retrieve-page-urls.md). This method helps optimize performance when you need only URL-related data.

When used with [ForContentType](#forcontenttype-parameterization), call the method inside the subquery parameterization action:

```csharp title="UrlPathColumns usage" highlight="7"
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Page", subqueryParameters =>
{
    // Retrieves only columns required for URL path generation
    subqueryParameters.ForWebsite("SampleChannel")
                      .UrlPathColumns();
});
```

When used with [ForContentTypes](#forcontenttypes-parameterization), call the method on the query-level `Parameters`:

```csharp title="UrlPathColumns usage" highlight="6"
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes( /* subquery parameters... */)
       .Parameters(queryParameters =>
          // Retrieves only columns required for URL path generation
          queryParameters.UrlPathColumns()
       );
```

`UrlPathColumns` must be used in conjunction with `ForWebsite` or `WithWebPageData`. It automatically includes all columns required by the system to correctly resolve page URLs.

You can combine `UrlPathColumns` with additional `Columns` calls if you need URL columns in addition to other fields:

```csharp title="UrlPathColumns usage" highlight="7-8"
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Page", subqueryParameters =>
{
    // Retrieves URL path columns plus the Title field
    subqueryParameters.ForWebsite("SampleChannel")
                     .UrlPathColumns()
                     .Columns("Title");
});
```

### Offset

Offsets the records by the specified `index` (zero-based) and takes the next `X` items specified by `fetch`.

Must be used together with [OrderBy](#referencecontentitemquery-orderbyparam), otherwise the pagination is not applied (as the system cannot guarantee a deterministic ordering of the returned results).

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Takes the next 5 items starting from the 11th
    subqueryParameters.Offset(10, 5);
    subqueryParameters.OrderBy("ContentItemName");
});
```

Configure `Offset` at either the subquery level or the query level ([Parameters](#builder-parameters)), not both, and do not combine it with [TopN](#topn) in the same query.

### IncludeTotalCount

Ensures that every retrieved item stores the total number of items, regardless of pagination applied by _Offset_.

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Includes the total number of items
    subqueryParameters.IncludeTotalCount()
    // Takes the next 5 items starting from the 11th
    subqueryParameters.Offset(10, 5);
    subqueryParameters.OrderBy("ContentItemName");
});
```

After executing the query, use `GetTotalCount` on an item in the result to get the total number of items.

```csharp
var items = await queryExecutor.GetResult(builder, item => item);
int? totalItemCount = items.First().GetTotalCount();
```

Configure `IncludeTotalCount` at either the subquery level or the query level ([Parameters](#builder-parameters)), not both.

### TopN

Limits the number of records fetched from the database.

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Takes the first 5 results from the selection
    subqueryParameters.TopN(5);
});
```

Do not combine `TopN` with [Offset](#offset) in the same query – they are two different ways to limit records and are not designed to be used together.

### OrderBy

Allows ordering of the results based on the value of a specified column.

```csharp
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // By default, items in the specified columns are sorted in ascending order
    subqueryParameters.OrderBy("ContentItemName");

    // You can parameterize the behavior by providing an instance of 'CMS.DataEngine.OrderByColumn'
    subqueryParameters.OrderBy(new OrderByColumn("ContentItemName", OrderDirection.Descending));
});
```

> **Note:** **Security considerations**
>
> ORDER BY string expressions are not parameterized against SQL injection. Only use trusted, developer-controlled values. If ordering values originate from external input, validate them against an allowlist. See [Protect against SQL injection](https://docs.kentico.com/documentation/developers-and-admins/api/objectquery-api.md#protect-against-sql-injection) (the principles described for the ObjectQuery API apply).

### Where

Inserts an [SQL WHERE](https://learn.microsoft.com/en-us/sql/t-sql/queries/where-transact-sql) clause into the query.

```csharp title="WhereTrue"
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves items that have the 'ShowInBanner' property set to true
    subqueryParameters.Where(where => where.WhereTrue("ShowInBanner"));
});
```

```csharp title="WhereLike"
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Multiple where operations are implicitly joined by AND
    subqueryParameters.Where(where => where.WhereLike("ColumnA", "value")
                                        .WhereLike("ColumnB", "value"));

    // OR has to be specified explicitly
    subqueryParameters.Where(where => where.WhereLike("ColumnA", "value")
                                        .Or()
                                        .WhereLike("ColumnB", "value"));
});
```

```csharp title="WhereStartsWith"
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves items whose name starts with with 'Apple'  
    subqueryParameters.Where(where => where.WhereStartsWith("ContentItemName", "Apple"));
});
```

> **Info:** The set of available `Where`extensions matches the expressivity of the SQL WHERE syntax. This page provides examples of only a few of the available methods.

> **Note:** **Security considerations**
>
> The `value` parameters (right-hand operands) in WHERE methods are automatically parameterized against SQL injection. However, `columnName` parameters (left-hand operands) are not parameterized. Only use trusted, developer-controlled values for column names. If column names originate from external input, validate them against an allowlist. See [Protect against SQL injection](https://docs.kentico.com/documentation/developers-and-admins/api/objectquery-api.md#protect-against-sql-injection) (the principles described for the ObjectQuery API apply).

### WhereContainsTags

Limits the query to content items that contain the [specified tags](https://docs.kentico.com/documentation/developers-and-admins/configuration/taxonomies.md).

```csharp title="WhereContainsTags"
// A collection of tags, e.g., obtained from a Tag selector
IEnumerable<Guid> tagIdentifiers;

var builder = new ContentItemQueryBuilder()
    .ForContentType(
        "Some.Type",
        subqueryParameters =>
            // Retrieves items with the specified tags
            subqueryParameters.Where(where =>
                where.WhereContainsTags("SomeTaxonomy", tagIdentifiers))
    ).InLanguage("en");
```

```csharp title="WhereContainsTags"
// A collection of tags, e.g., obtained from a Tag selector
IEnumerable<Guid> tagIdentifiers;
var tagCollection = await TagCollection.Create(tagIdentifiers);

var builder = new ContentItemQueryBuilder()
    .ForContentType(
        ArticlePage.CONTENT_TYPE_NAME,
        subqueryParameters =>
            // Retrieves items with the specified tags and any child tags
            subqueryParameters.Where(where =>
                where.WhereContainsTags("SomeTaxonomy", tagCollection))
    ).InLanguage("en");
```

## ForContentType parameterization

Methods described in this section can only be called from within subqueries generated by a `ContentItemBuilder.ForContentType` call.

### ForWebsite&#x20;

Configures the subquery to retrieve only pages from a specified [website channel](https://docs.kentico.com/documentation/developers-and-admins/configuration/website-channel-management.md) (no reusable content items are retrieved). It can only be called once per subquery. To retrieve both pages and reusable content items in a single query, use the `ForContentTypes` with [WithWebPageData](#fcts-wwpd) instead.

The `ForWebsite` method allows you to specify the following parameters:

- `websiteChannelName` (required) – code name of the website channel from which the pages are retrieved.
- `pathMatch` (optional) – a parameter of type `PathMatch` used to limit the retrieved pages only to a certain section of the website's content tree. The parameter also accepts an array of `PathMatch` objects if you need to combine multiple path conditions, e.g., `new[] { PathMatch.Children("/Articles"), PathMatch.SkipSection("/Articles/Coffee") }`.
- `includeUrlPath` (optional) – indicates if the URL path should be included in the retrieved data. `true` by default.

```csharp title="ForWebsite"
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves pages from the specified website channel
    subqueryParameters.ForWebsite(
                            websiteChannelName: "DancingGoatPages",
                            pathMatch: PathMatch.Children("/Articles"),
                            includeUrlPath: true);
});
```

See [Retrieve page content](https://docs.kentico.com/documentation/developers-and-admins/development/content-retrieval/retrieve-page-content.md) for general guidance about retrieving page content, including the recommended [ContentRetriever API](https://docs.kentico.com/documentation/developers-and-admins/api/content-item-api/content-retriever-api.md).

`ForWebsite` makes page-specific fields available in the result, such as the URL, tree path, and identifiers like `WebPageItemID` and `WebPageItemGUID`. Without it, these fields are not included, and referencing them in `Where`, `Columns`, or `OrderBy` results in an invalid query.

### WithLinkedItems&#x20;

Configures the subquery to include [linked content items](https://docs.kentico.com/documentation/business-users/content-hub/content-items.md#link-content-items) recursively up to the specified depth.

```csharp title="WithLinkedItems"
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves all linked items up to the maximum depth of 2
    subqueryParameters.WithLinkedItems(2);
});
```

If the collection includes web page items and you want to use web page specific data (such as URL and tree path), specify the `IncludeWebPageData` option.

```csharp title="IncludeWebPageData usage"
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    // Retrieves all linked items up to the maximum depth of 2
    // including web page data of linked web page items
    subqueryParameters
        .WithLinkedItems(2, options => options.IncludeWebPageData());
});
```

To see how the query result is bound to a model class, check out [WithLinkedItems mapping](#referencecontentitemquery-withlinkeditemsmap).

### Linking&#x20;

Retrieves all content items of the type specified in `ForContentType` that reference any of the content items from the provided collection in the given field. Enables loading data on-demand (lazily).

```csharp title="Linking"
var builder = new ContentItemQueryBuilder();

// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
    // Retrieves all content items of 'project.staff' type that reference any
    // of the items in 'managersCollection' from their 'ManagerField' field
    subqueryParameters.Linking("ManagerField", managersCollection);
});
```

Use at most one linking method per subquery (repeated calls are not supported). A subquery cannot combine `Linking` with `LinkedFrom` – it can retrieve links in only one direction.

For more information see [Linking details](#referencecontentitemquery-linking).

### LinkedFrom&#x20;

Retrieves content items of the type specified in `ForContentType` that are linked from the given field of items in the provided collection with the given content type. Enables loading data on-demand (lazily).

```csharp title="LinkedFrom"
var builder = new ContentItemQueryBuilder();

// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
    // Items are retrieved for a collection of
    // 'project.store' items - 'storesCollection' - and the field 'StaffField'
    subqueryParameters.LinkedFrom("project.store", "StaffField", storesCollection);
});
```

For more information see [LinkedFrom details](#referencecontentitemquery-linkedfrom).

### LinkedFromSchemaField

Retrieves all content items of the type specified in `ForContentType` that are linked from a collection of items via a [reusable schema field](https://docs.kentico.com/documentation/developers-and-admins/development/content-types/reusable-field-schemas.md).

```csharp title="LinkedFromSchemaField usage example"
var builder = new ContentItemQueryBuilder();

builder.ForContentType("Sample.Type", subqueryParameters =>
{
    subqueryParameters.LinkedFromSchemaField("SchemaFieldCodeName", contentItems);
});
```

For more information see [LinkedFromSchemaField details](#fct-linkedfromschemafield).

### SetUrlLanguageBehavior

Defines the behavior for the language slug of URL paths when web pages are retrieved in a fallback language. This method is relevant when requesting multilingual content ([InLanguage](#inlanguage)) and [retrieving page URL](https://docs.kentico.com/documentation/developers-and-admins/development/content-retrieval/retrieve-page-content/retrieve-page-urls.md) information (e.g., through methods like [GetUrl()](https://docs.kentico.com/documentation/developers-and-admins/development/content-retrieval/retrieve-page-content/retrieve-page-urls.md), often with [ForWebsite](#referencecontentitemquery-forwebsite) or [WithWebPageData](#fcts-wwpd)).

It accepts a `UrlLanguageBehavior` enum value:

- `UrlLanguageBehavior.UseRequestedLanguage` – When a page is served in a  [fallback language](https://docs.kentico.com/documentation/developers-and-admins/configuration/languages.md#language-fallbacks), its URL path is generated based on the language originally requested by the `InLanguage` method. For instance, if Spanish is requested and an English page is returned as a fallback, the URL path will still be structured as if it were a Spanish page (e.g., using URL prefixes as configured in the [Languages](https://docs.kentico.com/documentation/developers-and-admins/configuration/languages.md#set-up-a-new-language) application).
- `UrlLanguageBehavior.UseFallbackLanguage` (Default) – When a page is served in a fallback language, its URL path is generated based on the language of the actual fallback content. In the example below, the URL path would be structured as an English page.

```csharp title="Using SetUrlLanguageBehavior" highlight="7"
// Assume 'builder' is an initialized ContentItemQueryBuilder

// Within ForContentType configuration:
builder.ForContentType("Sample.PageType", subqueryParameters =>
{
    subqueryParameters.ForWebsite("MyWebsiteChannel")
                      .SetUrlLanguageBehavior(UrlLanguageBehavior.UseRequestedLanguage)
})
// Requesting multilingual content
.InLanguage("spanish");

// After executing the query:
IEnumerable<SamplePageType> pages = await executor.GetMappedWebPageResult<SamplePageType>(builder);
foreach (var page in pages)
{
    // If 'page' is an English fallback for a Spanish request, 
    // its url will be in the format:
    //
    // '/<spanishLanguageName>/my-page-slug'
    //
    // due to 'UseRequestedLanguage'.
    WebPageUrl url = page.GetUrl();
}
```

## ForContentTypes parameterization

Methods described in this section can only be called from within subqueries generated by a `ContentItemBuilder.ForContentTypes` call.

### OfContentType

Selects items with the specified content types.

```csharp title="Retrieve based on content type"
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{  
    // Retrieves items of the 'Acme.Article', 'Acme.Blog' content types
    subqueryParameters.OfContentType("Acme.Article", "Acme.Blog");
});
```

Do not combine `OfContentType` with `OfReusableSchema` in the same subquery.

### OfReusableSchema

Selects items with the specified [reusable field schema](https://docs.kentico.com/documentation/developers-and-admins/development/content-types/reusable-field-schemas.md).

```csharp title="Retrieve based on reusable field schema"
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{  
    // Retrieves items with the 'PageMetadata' reusable field schema
    subqueryParameters.OfReusableSchema("PageMetadata");
});
```

Call `OfReusableSchema` only once per subquery (repeated calls are not supported), and do not combine it with `OfContentType`.

### ForWebsite&#x20;

Provides multiple overloads that can:

- select all pages in the system
- select pages based on their ID, GUID, or code names
- select pages from specific [website channels](https://docs.kentico.com/documentation/developers-and-admins/configuration/website-channel-management.md) and paths

```csharp title="Retrieve web page items"
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Calls are mutually exclusive
    // Shown to demonstrate available overloads

    // Retrieves all pages in the system
    subqueryParameters.ForWebsite();

    // Retrieves pages with the provided GUIDs
    // (e.g., from the 'Page selector' component)
    subqueryParameters.ForWebsite(webPageGuids);

    // Retrieves all pages under the 'Acme' channel and 'Articles' page path
    subqueryParameters.ForWebsite(
            websiteChannelName: "Acme",
            pathMatch: PathMatch.Children("/Articles"));
});
```

Each overload also provides the optional `includeUrlPath` path parameter. `true` by default, it indicates whether web page URL data should be included in the query.

`ForWebsite` includes page-specific fields (such as URL and tree path) in the result and limits the result to page content types. It cannot be called more than once per subquery, and cannot be combined with [WithWebPageData](#fcts-wwpd) in the same subquery (both include page data). If you want to retrieve pages and reusable content items in a single query, use `WithWebPageData` instead.

Page-specific fields, such as the page URL, tree path, page order, and identifiers like `WebPageItemID` and `WebPageItemGUID`, become available once the query includes page data. Referencing them in [Columns](#columns), [Where](#where), or [OrderBy](#referencecontentitemquery-orderbyparam) without including page data results in an invalid query. The following example retrieves pages of a specific content type and filters them by their `WebPageItemID`:

```csharp title="Filter pages by WebPageItemID"
// A collection of page identifiers
IEnumerable<int> webPageItemIds;

var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    subqueryParameters.OfContentType("Acme.ArticlePage")
                      // Includes page data (do not also call WithWebPageData)
                      .ForWebsite()
                      .WithContentTypeFields();
})
  .Parameters(queryParameters =>
      queryParameters.Where(where =>
          // Keeps only pages whose 'WebPageItemID' is in the 'webPageItemIds' collection
          where.WhereIn(nameof(WebPageFields.WebPageItemID), webPageItemIds)));
```

### WithContentTypeFields&#x20;

By default, the result returned by `ForContentTypes` contains content item metadata (_CMS\_ContentItem_ table [Content item database structure](https://docs.kentico.com/documentation/developers-and-admins/api/content-item-api/content-item-database-structure.md#content-items)) and [reusable field schema](https://docs.kentico.com/documentation/developers-and-admins/development/content-types/reusable-field-schemas.md) data. `WithContentTypeFields` also adds [content type-specific fields](https://docs.kentico.com/documentation/developers-and-admins/development/content-types.md#add-fields) to the result.

You must call `WithContentTypeFields` to reference content type-specific fields in [Columns](#columns), [Where](#where), or [OrderBy](#referencecontentitemquery-orderbyparam). Referencing such fields without it produces an invalid query.

```csharp title="WithContentTypeFields example"
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves items with the 'PageMetadata' reusable field schema
    // and includes content-type specific fields in the result
    subqueryParameters.OfReusableSchema("PageMetadata")
                      .WithContentTypeFields();
});
```

### WithWebPageData&#x20;

By default, the result returned by `ForContentTypes` contains content item metadata (_CMS\_ContentItem_ table [Content item database structure](https://docs.kentico.com/documentation/developers-and-admins/api/content-item-api/content-item-database-structure.md#content-items)) and [reusable field schema](https://docs.kentico.com/documentation/developers-and-admins/development/content-types/reusable-field-schemas.md) data. `WithWebPageData` also adds website content-specific fields (such as URL and tree path) to the result.

```csharp title="WithWebPageData example"
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves items with the 'PageMetadata' reusable field schema
    // and includes web page specific fields in the result
    subqueryParameters.OfReusableSchema("PageMetadata")
                      .WithWebPageData();
});
```

> **Note:** `WithWebPageData` includes page fields without limiting the result to page content types, so a single query can return a mix of pages and reusable content items. Do not call it more than once per subquery, and do not combine it with [ForWebsite](#fcts-forwebsite) in the same subquery – both include page data, which results in an invalid query.

### WithLinkedItems

Configures the subquery to include [linked content items](https://docs.kentico.com/documentation/business-users/content-hub/content-items.md#link-content-items) recursively up to the specified depth. The parameterization behaves identically to its alternative in [ForContentType](#referencecontentitemquery-withlinkeditems).

```csharp title="WithLinkedItems usage"
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves all linked items up to the maximum depth of 2
    subqueryParameters
        .OfContentType(Article.CONTENT_TYPE_NAME)
        .WithLinkedItems(2);
});
```

If the collection of linked items contains web page items, you need to specify the `IncludeWebPageData` option to include web page specific data (such as URL and tree path) of the web page items:

```csharp title="IncludeWebPageData usage"
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves all linked items up to the maximum depth of 2
    // including web page data of linked web page items
    subqueryParameters
        .OfContentType(Article.CONTENT_TYPE_NAME)
        .WithLinkedItems(2, options => options.IncludeWebPageData());
});
```

To see how the query result is bound to a model class, check out [WithLinkedItems mapping](#referencecontentitemquery-withlinkeditemsmap).

### Linking

The method behaves identically to [ForContentType.Linking](#referencecontentitemquery-forcontenttypelinking), with the following exceptions:

- You need to specify the name of the content type whose items you want to retrieve, in addition to the field used to link the items. This is necessary to prevent ambiguities in case the searched content types contain identical field names.
- The usage is limited to one `Linking` call for each `ForContentTypes` subquery, and cannot be combined with `LinkedFrom` or `LinkedFromSchemaField` (a subquery retrieves links in only one direction).

```csharp title="ForContentTypes.Linking usage"
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(subqueryParameters =>
{
    // Retrieves items of the 'project.staff' type that link to
    // any of the content items in 'managersCollection' via their 'ManagerField' field
    subqueryParameters.Linking("project.staff", "ManagerField", managersCollection);
});
```

For more information see [Linking details](#referencecontentitemquery-linking).

### LinkedFrom

The behavior is identical to [ForContentType.LinkedFrom](#referencecontentitemquery-forcontenttypelinkedfrom), with the only difference being that you cannot chain multiple calls within a single subquery. It also cannot be combined with `Linking` or `LinkingSchemaField` in the same subquery.

For more information see [LinkedFrom details](#referencecontentitemquery-linkedfrom).

### LinkingSchemaField

Retrieves all content items that link to a collection of items via the specified [reusable schema field](https://docs.kentico.com/documentation/developers-and-admins/development/content-types/reusable-field-schemas.md). [LinkedFromSchemaField](#fct-linkedfromschemafield) complements this method by retrieving links from the opposite direction.

Use at most one linking method per subquery (repeated calls are not supported), and do not combine `LinkingSchemaField` with `LinkedFrom` or `LinkedFromSchemaField` in the same subquery.

```csharp title="LinkingSchemaField method usage"
var imageIdentifiers = new List<int>() { 1, 2, 3 };

var builder = new ContentItemQueryBuilder().ForContentTypes(subqueryParameters =>
{
    subqueryParameters.LinkingSchemaField("ProductImage", imageIdentifiers);
});
```

For more information see [LinkingSchemaField details](#fct-linkingschemafield).

### LinkedFromSchemaField

Retrieves all content items that are linked from a collection of items via a [reusable schema field](https://docs.kentico.com/documentation/developers-and-admins/development/content-types/reusable-field-schemas.md). [LinkingSchemaField](#fct-linkingschemafield) complements this method by retrieving links from the opposite direction.

Use at most one linking method per subquery (repeated calls are not supported), and do not combine `LinkedFromSchemaField` with `Linking` or `LinkingSchemaField` in the same subquery.

```csharp title="LinkedFromSchemaField method usage"
var builder = new ContentItemQueryBuilder().ForContentTypes(subqueryParameters =>
{
    subqueryParameters.LinkedFromSchemaField("ProductImage", productIdentifiers);
});
```

For more information see [LinkedFromSchemaField details](#fct-linkedfromschemafield).

### InSmartFolder

Retrieves content items that fulfill the filter conditions of the specified [smart folder](https://docs.kentico.com/documentation/business-users/content-hub/content-hub-folders.md#smart-folders). This allows content editors to control which items are retrieved directly in the _Content hub_ UI, without needing to adjust the code.

The smart folder can be specified by its ID, GUID, or code name. You can get the smart folder GUID from a field using the [Smart folder selector](https://docs.kentico.com/documentation/developers-and-admins/customization/extend-the-administration-interface/ui-form-components/reference-admin-ui-form-components.md#smart-folder-selector) UI form component. You can also find the identifiers of smart folders in the _Content hub_ application – expand the menu actions of a folder and select _Properties_.

```csharp title="InSmartFolder method usage"
var builder = new ContentItemQueryBuilder();

// Retrieves content items from the specified smart folder
builder.ForContentTypes(subqueryParameters => subqueryParameters.InSmartFolder(smartFolderGuid));
```

The `InSmartFolder` parameterization causes the subquery to return an **empty result** if the specified smart folder:

- Doesn't exist
- Doesn't have dynamic content delivery enabled
- Has invalid filter conditions (for example if a tag saved in the _Taxonomy_ filter option was later deleted)

The following scenarios are unsupported and result in an exception:

- Using multiple `InSmartFolder` calls for a single subquery
- Combining `InSmartFolder` with `ForWebsite`parameterization (smart folders are only supported for reusable content items, not pages)

If you need to ensure that only items of one specific content type are retrieved (regardless of the smart folder's filter condition), add `OfContentType` to the parameterization.

```csharp title="InSmartFolder usage for a specific content type"
var builder = new ContentItemQueryBuilder();

// Retrieves items of one specific content type from a smart folder
builder.ForContentTypes(subqueryParameters =>
{
    subqueryParameters.InSmartFolder(smartFolderGuid)
                      .OfContentType("Sample.Type");
});
```

### SetUrlLanguageBehavior

Defines the behavior for the language of URL paths when web pages are retrieved in a fallback language. This method is particularly relevant when using [InLanguage](#inlanguage) and retrieving page URL information (e.g., through methods like [GetUrl()](https://docs.kentico.com/documentation/developers-and-admins/development/content-retrieval/retrieve-page-content/retrieve-page-urls.md) after ensuring necessary columns are loaded, often with [ForWebsite](#referencecontentitemquery-forwebsite) or [WithWebPageData](#fcts-wwpd)).

It accepts a `UrlLanguageBehavior` enum value:

- `UrlLanguageBehavior.UseRequestedLanguage` – When a page is served in a [fallback language](https://docs.kentico.com/documentation/developers-and-admins/configuration/languages.md#language-fallbacks), its URL path is generated based on the language originally requested by the `InLanguage` method. For instance, if Spanish is requested and an English page is returned as a fallback, the URL path will still be structured as if it were a Spanish page (e.g., using URL prefixes as configured in the [Languages](https://docs.kentico.com/documentation/developers-and-admins/configuration/languages.md#set-up-a-new-language) application).
- `UrlLanguageBehavior.UseFallbackLanguage` (Default) – When a page is served in a fallback language, its URL path is generated based on the language of the actual fallback content. In the example below, the URL path would be structured as an English page.

```csharp title="Using SetUrlLanguageBehavior" highlight="7"
var builder = new ContentItemQueryBuilder();

builder.ForContentTypes(subqueryParameters =>
{
    subqueryParameters.ForWebsite("MyWebsiteChannel") // Retrieves pages, including their page data
                      .SetUrlLanguageBehavior(UrlLanguageBehavior.UseRequestedLanguage)
})
.InLanguage("spanish"); // Requesting content in Spanish

// After executing the query:
IEnumerable<SamplePageType> pages = await executor.GetMappedWebPageResult<SamplePageType>(builder);
foreach (var page in pages)
{
    // If 'page' is an English fallback for a Spanish request, 
    // its url will be in the format:
    //
    // '/<spanishLanguageName>/my-page-slug'
    //
    // due to 'UseRequestedLanguage'.
    WebPageUrl url = page.GetUrl();

}
```

### Where conditions

Where parameterization can be added to a query containing `ForContentTypes` subqueries using [Parameters](#builder-parameters).

```csharp title="Adding Where conditions"
var builder = new ContentItemQueryBuilder();
builder.ForContentTypes(subqueryParameters =>
{
    // ...
}).Parameters(queryParameters =>
{
    queryParameters.Where(where => where) //...
});
```

> **Note:** **Security considerations**
>
> The `value` parameters (right-hand operands) in WHERE conditions are automatically parameterized against SQL injection. However, `columnName` parameters (left-hand operands) are not parameterized. Only use trusted, developer-controlled values for column names. If column names originate from external input, validate them against an allowlist. See [Protect against SQL injection](https://docs.kentico.com/documentation/developers-and-admins/api/objectquery-api.md#protect-against-sql-injection) (the principles described for the ObjectQuery API apply).

## Method details

Methods described in this section can only be called from within subqueries generated by a `ContentItemBuilder.ForContentTypes` call or a `ContentItemBuilder.ForContentType` call.

### WithLinkedItems&#x20;

`IContentQueryExecutor.GetMappedResult`, `IContentQueryExecutor.GetMappedWebPageResult`, or using the provided `IContentQueryModelTypeMapper` automatically binds the linked content item hierarchy to the specified model.

```csharp
IEnumerable<ModelClass> data =
            queryExecutor.GetMappedResult<ModelClass>(builder);
```

When mapping the data manually, use `GetLinkedItems` on the result to get the next level of references. This can be repeated up until the specified recursion level.

```csharp
var data = queryExecutor.GetResult<ContentItemDto>(builder, resultSelector);

private ContentItemDto resultSelector(IContentQueryDataContainer itemData)
{
    var item = new ContentItemDto
    {
        Title = itemData.GetValue<string>("Title"),
        Text = itemData.GetValue<string>("Text"),

        // Retrieves first-level linked items from the 'Author' field
        AuthorName = itemData.GetLinkedItems("Author").First()
                                .GetValue<string>("Name");

        // Retrieves second-level linked items from the 'Author' field
        AuthorProfileBlurb = 
            itemData.GetLinkedItems("Author").First()
                    .GetLinkedItems("Profile").First()
                    .GetValue<string>("ProfileBlurb");
    };

    return item;
}
```

### Linking&#x20;

Retrieves all content items which reference any of the content items from the provided collection in the specified field. Enables loading data on-demand (lazily).

The following diagram illustrates the behavior on a simple content model:

![Linking usage visualization](https://docs.kentico.com/docsassets/documentation/reference-content-item-query/LinkingBasic.jpg "Linking usage visualization")

> **Note:** Combining this method with [LinkedFrom](#referencecontentitemquery-linkedfrom) in a single subquery is not supported.

The method can also be used together with `WithLinkedItems`. For example:

```csharp title="Linking and WithLinkedItems"
var builder = new ContentItemQueryBuilder();

// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{
    // Retrieves all items of 'project.staff' type that reference any of the
    // items in 'managersCollection' from their 'ManagerField' together with
    // all second-level references for the selected 'project.staff' items
    subqueryParameters.Linking("ManagerField", managersCollection)
                    .WithLinkedItems(2);
});
```

![Linking usage visualization](https://docs.kentico.com/docsassets/documentation/reference-content-item-query/LinkingCombined.jpg "Linking usage visualization")

The collection of items for which to retrieve references must implement the `IContentItemIdentifier` interface. The interface ensures fields required by each data model that wants to leverage this method.  The fields must be bound to the model during model binding within `ContentQueryExecutor.GetResult`.

[Generated content type classes](https://docs.kentico.com/documentation/developers-and-admins/api/generate-code-files-for-system-objects.md) already implement `IContentItemIdentifier` via the `SystemFields` property. The following approach applies for custom model classes.

```csharp title="IContentItemIdentifier fields in custom model classes"
var data = queryExecutor.GetResult<ContentItemDto>(builder, resultSelector);

ManagerDto resultSelector(IContentQueryDataContainer itemData)
{
    var item = new ManagerDto
    {
        // Binds fields required by 'Linking'
        ContentItemID = itemData.ContentItemID,
        ContentItemLanguageID = itemData.ContentItemDataContentLanguageID,
        // other fields...
    };

    return item;
}

// Example custom model class binding content items of the 'Manager' content type
class ManagerDto : IContentItemIdentifier
{
    public int ContentItemID { get; }
    public int ContentLanguageID { get; }
    public IEnumerable<ContentItemReference> PictureField { get; }
    public IEnumerable<ContentItemReference> AwardsField { get; }
}
```

### LinkedFrom&#x20;

Retrieves content items of a specific type linked from the given field in the provided collection. Enables loading data on-demand (lazily).

The following diagram illustrates the behavior on a simple content model. Red arrows trace query evaluation:

![LinkedFrom usage visualization](https://docs.kentico.com/docsassets/documentation/reference-content-item-query/LinkedFromBasic.jpg "LinkedFrom usage visualization")

> **Note:** Combining this method with [Linking](#referencecontentitemquery-linking) in a single subquery is not supported.

The method can also be used together with `WithLinkedItems`. For example:

```csharp title="Linked from and WithLinkedItems"
var builder = new ContentItemQueryBuilder();

// Retrieves items of the 'project.staff' content type
builder.ForContentType("project.staff", subqueryParameters =>
{  
    // Items are retrieved for a collection of 'project.store' items and the field 'StaffField'
    // together with all first-level references for the selected 'project.staff' items
    subqueryParameters.LinkedFrom("project.store", "StaffField", storesCollection)
                        .WithLinkedItems(1);
});
```

![LinkedFrom usage visualization](https://docs.kentico.com/docsassets/documentation/reference-content-item-query/LinkedFromCombined.jpg "LinkedFrom usage visualization")

The collection of items for which to retrieve references must implement the `IContentItemIdentifier` interface. The interface ensures fields required by each data model that wants to leverage this method. The fields must be bound to the model during model binding within `ContentQueryExecutor.GetResult`.

[Generated content type classes](https://docs.kentico.com/documentation/developers-and-admins/api/generate-code-files-for-system-objects.md) by default implement `IContentItemIdentifier` via the `SystemFields` property. The following approach applies for custom model classes.

```csharp title="IContentItemIdentifier fields in custom model classes"
var data = queryExecutor.GetResult<ContentItemDto>(builder, resultSelector);

StoreDto resultSelector(IContentQueryDataContainer itemData)
{
    var item = new StoreDto
    {
        // Binds fields required by `LinkedFrom`
        ContentItemID = itemData.ContentItemID,
        ContentItemLanguageID = itemData.ContentItemDataContentLanguageID,
        // other fields...
    };

    return item;
}

// Example custom model class binding content items of the 'Store' content type
class StoreDto : IContentItemIdentifier
{
    public int ContentItemID { get; }
    public int ContentLanguageID { get; }
    public IEnumerable<ContentItemReference> StaffField { get; }
    public IEnumerable<ContentItemReference> ReferenceField { get; }
    public IEnumerable<ContentItemReference> FaqField { get; }
}
```

### LinkingSchemaField&#x20;

This method can only be called from within subqueries generated by a `ContentItemBuilder.ForContentTypes` call.

Retrieves all content items that link to a collection of items via the specified [reusable schema field](https://docs.kentico.com/documentation/developers-and-admins/development/content-types/reusable-field-schemas.md). [LinkedFromSchemaField](#fct-linkedfromschemafield) complements this method by retrieving links from the opposite direction.

See the following diagram for an illustration of the method's behavior on a simplified content model. The subquery retrieves all content items that link to the images from `imageIdentifiers` via the _ProductImage_ reusable schema field. Red arrows trace the subquery evaluation:

![LinkinkSchemaField method demonstration](https://docs.kentico.com/docsassets/documentation/reference-content-item-query/LinkingSchemaFields.png "LinkinkSchemaField method demonstration")

In the diagram above, the method is called with the following parameters:

- `"ProductImage"` – the code name of a field that belongs to a reusable field schema. Reusable schema field code names must be unique across the system, it's therefore sufficient to target fields directly.
- `imageIdentifiers` – IDs of content items with the _Image_ content type.

### LinkedFromSchemaField&#x20;

Retrieves all content items that are linked from a collection of items via a [reusable schema field](https://docs.kentico.com/documentation/developers-and-admins/development/content-types/reusable-field-schemas.md). [LinkingSchemaField](#fct-linkingschemafield) complements this method by retrieving links from the opposite direction.

See the following diagram for an illustration of the method's behavior on a simplified content model. The subquery retrieves all _Image_ content items that are linked from `productIdentifiers` via the _ProductImage_ reusable schema field. Red arrows trace the subquery evaluation:

![LinkedFromSchemaField method demonstration](https://docs.kentico.com/docsassets/documentation/reference-content-item-query/LinkedFromSchemaFields.png "LinkedFromSchemaField method demonstration")

In the diagram above, the method is called with the following parameters:

- `"ProductImage"` – the code name of a field that belongs to a reusable field schema. Reusable schema field code names are unique and can be targeted directly without specifying the corresponding schema.
- `productIdentifiers` – a collection of content items from content types using the _ProductFields_ reusable field schema.

> **Info:** The collection of items for which to retrieve references must implement the `IContentItemIdentifier` interface. The interface ensures fields required by each data model that wants to leverage this method.
>
> [Generated content type classes](https://docs.kentico.com/documentation/developers-and-admins/api/generate-code-files-for-system-objects.md) by default implement `IContentItemIdentifier` via the `SystemFields` property.

## IContentQueryExecutor configuration

Apart from configuring the query itself, you can also fine tune its execution. You can do so by setting the properties of the `ContentQueryExecutionOptions` attribute and providing it to the `IContentQueryExecutor` interface.

| Property              | Description                                                                                                                                                                                                              |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `ForPreview`          | If set to _true_, the query executor retrieves the queried items in their latest available version, regardless of their workflow state. Otherwise, the latest published version is retrieved.<br>Default value: _false_. |
| `IncludeSecuredItems` | If set to _true_, the query executor retrieves all items according to the query, including secured items. Otherwise, only items that are not secured are included in the query.<br>Default value: _false_.               |

The [ContentRetriever API](https://docs.kentico.com/documentation/developers-and-admins/api/content-item-api/content-retriever-api.md) exposes equivalent settings through its parameter objects. For examples of how these settings affect data retrieval, see [Page security configuration](https://docs.kentico.com/documentation/developers-and-admins/development/content-retrieval/retrieve-page-content.md#page-security-configuration) and [Retrieve pages for preview](https://docs.kentico.com/documentation/developers-and-admins/development/content-retrieval/retrieve-page-content.md#retrieve-pages-for-preview).
