Skip to content

Querying

github-actions[bot] edited this page Sep 2, 2026 · 10 revisions

Querying

db.Table<T>() returns an IQueryable<T>. You can chain standard LINQ methods on it and call one of the terminal methods to run the query.

The framework keeps the SQL close to the shape of the LINQ query you wrote. It introduces a subquery when a LINQ operation needs a SQL query boundary, such as composition after a set operation or filtering on a window value. When a method cannot be translated safely, the framework throws a clear NotSupportedException instead.

Get All Records

var books = await db.Table<Book>().ToListAsync();

Filter with Where

var cheap = await db.Table<Book>()
    .Where(b => b.Price < 20)
    .ToListAsync();

var byAuthor = await db.Table<Book>()
    .Where(b => b.AuthorId == 3 && b.InStock)
    .ToListAsync();

Mix AND and OR with WhereBuilder

Chained Where calls always combine with AND. WhereBuilder collects And and Or calls on a small builder and emits one WHERE clause with just the active predicates.

The common case is a filter object with several nullable fields. Each field is added to the builder only when it is set:

public class BookFilter
{
    public string? Title { get; set; }
    public decimal? MinPrice { get; set; }
    public decimal? MaxPrice { get; set; }
    public string[]? SearchTerms { get; set; }
}

var matches = await db.Table<Book>()
    .WhereBuilder(f =>
    {
        if (filter.Title != null)    f.And(b => b.Title == filter.Title);
        if (filter.MinPrice != null) f.And(b => b.Price >= filter.MinPrice);
        if (filter.MaxPrice != null) f.And(b => b.Price <= filter.MaxPrice);
        if (filter.SearchTerms is { Length: > 0 })
        {
            f.And(g =>
            {
                foreach (string term in filter.SearchTerms)
                {
                    g.Or(b => b.Title.Contains(term));
                }
            });
        }
    })
    .ToListAsync();

The inner g => ... is a sub-builder. It builds a group of OR-combined predicates that becomes one operand at the outer level, so the generated SQL ends up as WHERE title_match AND price_min AND price_max AND (term1 OR term2 OR ...). A sub-builder can contain another sub-builder if you need deeper nesting.

Project with Select

var titles = await db.Table<Book>()
    .Select(b => b.Title)
    .ToListAsync();

var summaries = await db.Table<Book>()
    .Select(b => new { b.Title, b.Price })
    .ToListAsync();

You can project into a named type as well:

public class BookSummary
{
    public string Title { get; set; } = "";
    public decimal Price { get; set; }
}

var summaries = await db.Table<Book>()
    .Select(b => new BookSummary { Title = b.Title, Price = b.Price })
    .ToListAsync();

Sort

var sorted = await db.Table<Book>()
    .OrderBy(b => b.Price)
    .ToListAsync();

var sortedDesc = await db.Table<Book>()
    .OrderByDescending(b => b.PublishedAt)
    .ToListAsync();

Chain ThenBy or ThenByDescending for multiple sort columns:

var sorted = await db.Table<Book>()
    .OrderBy(b => b.Genre)
    .ThenByDescending(b => b.Price)
    .ToListAsync();

Pass a SQLiteNullsOrder to control where nulls land, which emits NULLS FIRST or NULLS LAST. Requires SQLite 3.30 or newer.

var sorted = await db.Table<Book>()
    .OrderBy(b => b.PublishedAt, SQLiteNullsOrder.Last)
    .ThenByDescending(b => b.Price, SQLiteNullsOrder.First)
    .ToListAsync();

Pagination

int page = 2;
int pageSize = 10;

var results = await db.Table<Book>()
    .OrderBy(b => b.Title)
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync();

Distinct

var genres = await db.Table<Book>()
    .Select(b => b.Genre)
    .Distinct()
    .ToListAsync();

Set Operations

Concat, Union, Intersect and Except combine compatible queries. You can continue filtering, projecting, grouping, sorting or applying scalar operations to the combined result.

var ids = db.Table<CurrentBook>().Select(b => b.Id)
    .Concat(db.Table<ArchivedBook>().Select(b => b.Id));

var recentIds = await ids
    .Where(id => id >= minimumId)
    .Order()
    .ToListAsync();

int count = await ids.CountAsync();

Get a Single Record

// Throws if no match
var book = await db.Table<Book>().FirstAsync(b => b.Id == 1);

// Returns null if no match
var book = await db.Table<Book>().FirstOrDefaultAsync(b => b.Id == 1);

// Throws if more than one match
var book = await db.Table<Book>().SingleAsync(b => b.Isbn == "978-0132350884");

// Returns null if no match, throws if more than one
var book = await db.Table<Book>().SingleOrDefaultAsync(b => b.Isbn == "978-0132350884");

Count

int total = await db.Table<Book>().CountAsync();

int cheapCount = await db.Table<Book>().CountAsync(b => b.Price < 20);

Any and All

bool hasBooks = await db.Table<Book>().AnyAsync();

bool hasExpensive = await db.Table<Book>().AnyAsync(b => b.Price > 100);

bool allInStock = await db.Table<Book>().AllAsync(b => b.InStock);

Contains

var ids = new List<int> { 1, 2, 3 };

var books = await db.Table<Book>()
    .Where(b => ids.Contains(b.Id))
    .ToListAsync();

Captured collections also support Any and Count predicates that compare local values with row columns, plus Contains after a local Where:

var ranges = new[] { new { Min = 10m, Max = 20m }, new { Min = 40m, Max = 50m } };

var books = await db.Table<Book>()
    .Where(b => ranges.Any(r => b.Price >= r.Min && b.Price <= r.Max))
    .ToListAsync();

var selected = await db.Table<Book>()
    .Where(b => ids.Where(id => id > 1).Contains(b.Id))
    .ToListAsync();

Other Collection Types

var array = await db.Table<Book>().ToArrayAsync();

var set = await db.Table<Book>()
    .Select(b => b.Genre)
    .ToHashSetAsync();

var dict = await db.Table<Book>()
    .ToDictionaryAsync(b => b.Id, b => b.Title);

Chaining

These common server-translated methods can be chained together:

var results = await db.Table<Book>()
    .Where(b => b.InStock && b.Price < 50)
    .OrderBy(b => b.Title)
    .Skip(1)
    .Take(5)
    .Select(b => new { b.Title, b.Price })
    .ToListAsync();

Global Query Filters

Register a predicate on the options builder and the framework injects it into every query against that entity, so the filter is not repeated on each call site.

SQLiteOptions options = new SQLiteOptionsBuilder("app.db")
    .AddQueryFilter<Book>(b => !b.IsDeleted)
    .Build();

To opt out for a single query, call IgnoreQueryFilters(). See the Query Filters page for interface registrations, exactly where filters apply, plus the soft delete and multi-tenancy patterns.

Clone this wiki locally