Skip to content

Database: Query Builder ​

Introduction ​

DB.Table is Laravel's query builder: it works on table and column names, for queries where a model is not worth it or does not fit (reports with joins and grouping, pivot tables, framework tables such as jobs). For everyday work, models and their LINQ-based Query<T> are type-checked and fire model events.

Every value is sent as a query parameter, and table and column names are quoted for the active database, so the same code runs on SQLite, PostgreSQL, MySQL, and SQL Server.

Running Database Queries ​

Retrieving All Rows From a Table ​

Get returns each row as a dictionary keyed by column name (case-insensitive), or as objects of your own class:

csharp
var users = await DB.Table("users").Get();
foreach (var user in users) Console.WriteLine(user["name"]);

public class UserRow { public long Id { get; set; } public string Name { get; set; } = ""; }
List<UserRow> rows = await DB.Table("users").Get<UserRow>();   // columns matched by name (snake_case or PascalCase)

Use DB.Connection("mysql").Table(...) for another connection.

Retrieving a Single Row or Column ​

csharp
var user = await DB.Table("users").Where("name", "John").First();   // null when nothing matches
var byId = await DB.Table("users").Find(3);                         // by the "id" column
var email = await DB.Table("users").Where("name", "John").Value("email");

List<object?> titles = await DB.Table("posts").Pluck("title");
Dictionary<object, object?> byKey = await DB.Table("posts").Pluck("title", "id");   // id → title

Chunking Results ​

Chunk reads the rows in pages, so a large table is never loaded at once. Like Laravel, it needs an order; return false to stop:

csharp
await DB.Table("users").OrderBy("id").Chunk(100, async users =>
{
    foreach (var user in users) await Process(user);
    return true;
});

When the callback updates or deletes the rows it reads, page offsets shift; use ChunkById, which continues after the last id instead:

csharp
await DB.Table("users").Where("active", false).ChunkById(100, async users =>
{
    await DB.Table("users").WhereIn("id", users.Select(u => u["id"])).Update(new { active = true });
    return true;
});

Paginate and SimplePaginate work on DB.Table queries too, see Pagination.

Aggregates ​

csharp
long count = await DB.Table("users").Count();
object? max = await DB.Table("orders").Max("price");
object? min = await DB.Table("orders").Min("price");
decimal sum = await DB.Table("orders").Where("finalized", true).Sum("price");
decimal? avg = await DB.Table("orders").Avg("price");

if (await DB.Table("orders").Where("finalized", true).Exists()) { ... }
if (await DB.Table("orders").Where("finalized", true).DoesntExist()) { ... }

With GroupBy or Distinct, Count counts the result rows.

Select Statements ​

csharp
var users = await DB.Table("users").Select("name", "email as user_email").Get();
var distinct = await DB.Table("users").Select("country").Distinct().Get();

var query = DB.Table("users").Select("name");
var withAge = await query.AddSelect("age").Get();

"table.column", "table.*", and "column as alias" are quoted correctly.

Raw Expressions ​

DB.Raw inserts SQL as is, in Select, OrderBy, GroupBy, and Having:

csharp
var counts = await DB.Table("users")
    .Select(DB.Raw("COUNT(*) AS user_count"), "status")
    .Where("status", "<>", 1)
    .GroupBy("status")
    .Get();

WhereRaw, OrWhereRaw, and HavingRaw take SQL with ? placeholders for values:

csharp
var orders = await DB.Table("orders").WhereRaw("price > IF(state = 'TX', ?, 100)", 200).Get();

WARNING

Raw expressions are not escaped. Never put user input in them; pass it as a ? binding.

Joins ​

csharp
var users = await DB.Table("users")
    .Join("contacts", "users.id", "=", "contacts.user_id")
    .Join("orders", "users.id", "=", "orders.user_id")
    .Select("users.*", "contacts.phone", "orders.price")
    .Get();

var withPosts = await DB.Table("users").LeftJoin("posts", "users.id", "=", "posts.user_id").Get();

RightJoin and CrossJoin(table) are available too.

Where Clauses ​

csharp
var users = await DB.Table("users")
    .Where("votes", ">=", 100)
    .Where("subscribed", true)        // "=" by default
    .Where("name", "like", "T%")
    .Get();

The operators are =, !=, <>, <, >, <=, >=, like, and not like. Comparing with null writes IS NULL / IS NOT NULL.

Or Where Clauses ​

csharp
var users = await DB.Table("users").Where("votes", ">", 100).OrWhere("name", "John").Get();

Logical Grouping ​

Pass a callback to put conditions in parentheses:

csharp
// select * from users where name = 'John' and (votes > 100 or title = 'Admin')
var users = await DB.Table("users")
    .Where("name", "John")
    .Where(q => q.Where("votes", ">", 100).OrWhere("title", "Admin"))
    .Get();

Additional Where Clauses ​

csharp
.WhereIn("id", new[] { 1, 2, 3 })        // an empty list matches nothing
.WhereNotIn("id", ids)
.WhereNull("deleted_at")
.WhereNotNull("email_verified_at")
.WhereBetween("votes", 1, 100)
.WhereNotBetween("votes", 1, 100)
.WhereColumn("updated_at", ">", "created_at")

Each has an Or... variant (OrWhereIn, OrWhereNull, ...).

Vector Similarity Clauses ​

On PostgreSQL with pgvector, vector columns (see t.Vector) can be searched by cosine similarity. The vector is always a bound parameter:

csharp
var matches = await DB.Table("documents")
    .SelectVectorDistance("embedding", vector)                   // adds a "distance" column
    .WhereVectorSimilarTo("embedding", vector, minSimilarity: 0.4) // also orders nearest first
    .Limit(10)
    .Get();

.WhereVectorDistanceLessThan("embedding", vector, 0.3)
.OrderByVectorDistance("embedding", vector)

Other databases throw NotSupportedException. The AI SDK adds overloads that take a search string and embed it, and VectorMath helpers for ranking in memory.

Ordering, Grouping, Limit and Offset ​

csharp
.OrderBy("name")                 // ascending
.OrderByDesc("created_at")
.Latest()                        // newest first by created_at (or Latest("published_at"))
.Oldest()
.InRandomOrder()

.GroupBy("account_id", "status")
.Having("account_id", ">", 100)
.HavingRaw("SUM(price) > ?", 2500)

.Skip(10).Take(5)                // or Offset(10).Limit(5)
.ForPage(3, 15)                  // page 3, 15 per page

Limit and offset are written for each database (LIMIT/OFFSET, or OFFSET ... FETCH on SQL Server).

Insert Statements ​

csharp
await DB.Table("users").Insert(new { email = "kayla@example.com", votes = 0 });

await DB.Table("users").Insert(new[]   // several rows in one statement
{
    new { email = "picard@example.com", votes = 0 },
    new { email = "janeway@example.com", votes = 0 },
});

long id = await DB.Table("users").InsertGetId(new { email = "john@example.com", votes = 0 });

Values may be anonymous objects or dictionaries. Rows that leave out a column insert NULL there.

Upserts ​

Upsert inserts rows, or updates them when a row with the same unique columns already exists. The unique columns need a unique index:

csharp
await DB.Table("flights").Upsert(
    new[]
    {
        new { departure = "Oakland", destination = "San Diego", price = 99 },
        new { departure = "Chicago", destination = "New York", price = 150 },
    },
    uniqueBy: ["departure", "destination"],
    update: ["price"]);   // default: every column except uniqueBy

It uses ON CONFLICT (SQLite, PostgreSQL), ON DUPLICATE KEY UPDATE (MySQL), or MERGE (SQL Server).

Update Statements ​

csharp
var affected = await DB.Table("users").Where("id", 1).Update(new { votes = 1 });

Increment and Decrement ​

csharp
await DB.Table("users").Increment("votes");
await DB.Table("users").Increment("votes", 5);
await DB.Table("users").Decrement("votes", 5);
await DB.Table("users").Where("id", 1).Increment("votes", 1, new { name = "John" });   // and set other columns

Delete Statements ​

csharp
await DB.Table("users").Where("votes", ">", 100).Delete();
await DB.Table("users").Truncate();   // every row

WARNING

Update and Delete without a Where affect the whole table.

DB.Table queries go straight to the database. They do not fire model events, set timestamps, or respect soft deletes.

Debugging ​

ToSql() returns the SQL a query would run, with {0}, {1}, ... for its bindings:

csharp
var (sql, bindings) = DB.Table("users").Where("votes", ">", 100).ToSql();

Model Queries ​

Most queries in a DotBlaze app go through models instead. Model<T>.Query() (or any static starter such as Where) returns a Query<T> that wraps EF Core's IQueryable<T>, so conditions are ordinary C# lambdas:

csharp
var books = await Book.Where(b => b.Price < 20)
    .OrderByDesc(b => b.Price)
    .Take(10)
    .Get();

See Retrieving Models for the full list of methods, mass updates for Update/Delete on a model query, and AsQueryable() for anything EF Core supports that Query<T> does not wrap.

Complete Example: Read-Only Post Report ​

After creating the blog schema and some posts, add:

csharp
// app/Commands/PostReport.cs
using DotBlaze;

namespace Blog.Commands;

public class PostReport : Command
{
    public override string Signature => "demo:post-report";
    public override async Task<int> Handle()
    {
        var rows = await DB.Table("posts")
            .Select("id", "title", "user_id")
            .OrderBy("id").Limit(10).Get();
        foreach (var row in rows)
            Line($"{row["id"]}: {row["title"]} (author {row["user_id"]})");
        Line($"Rows shown: {rows.Count}");
        return 0;
    }
}

Run dotblaze migrate, then dotblaze demo:post-report. An empty database prints Rows shown: 0; seeded or manually created posts produce up to ten rows. Column names are database names, so use user_id, not UserId. Select fixed application-owned columns; keep user values in bound Where arguments rather than concatenated SQL.