---
url: /runcobo/guide/query-recipes.md
description: >-
  Common crsql query patterns — optional filters, joins, nested loading,
  aggregates, partial updates and transactions.
---

# Query Recipes

Patterns for the queries most applications need. Each one builds on the blog from [Database Access](/guide/database): a query in `db/queries/`, then `bin/cobo generate`, then a call from an action. The SQL uses PostgreSQL syntax; adapt it to your engine's dialect on [MySQL or SQLite](/guide/database#mysql-and-sqlite).

## Optional filters

A list endpoint with optional filters uses nullable parameters (`sqlc.narg`) where `NULL` means "don't filter":

```sql [db/queries/posts.sql]
-- name: SearchPosts :many
SELECT id, author_id, title, status
FROM posts
WHERE (sqlc.narg(author_id)::bigint IS NULL OR author_id = sqlc.narg(author_id))
  AND (sqlc.narg(status)::text IS NULL OR status = sqlc.narg(status))
  AND (sqlc.narg(query)::text IS NULL OR title ILIKE '%' || sqlc.narg(query) || '%')
ORDER BY id DESC
LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset);
```

The `::bigint` / `::text` casts tell sqlc each parameter's type; using the same name twice reuses one parameter. The generated method takes nilable arguments, so optional contract fields pass straight through:

```crystal
class Posts::ListPostsContract < RequestValidation::Contract
  schema do
    optional :author_id, Int64
    optional :status, String, allowed_values: ["draft", "published"]
    optional :q, String, filled: true
    optional :page, Int32
  end
end

class Posts::ListPosts < Blog::BaseAction
  get "/posts"

  call do
    input = validate(ListPostsContract)
    page = Runcobo::Pagination.new(input.page, 20)
    posts = store.search_posts(author_id: input.author_id, status: input.status, query: input.q,
      row_limit: page.per_page, row_offset: page.offset.to_i32)
    render_json(posts.map { |post| {id: post.id, title: post.title, status: post.status} })
  end
end
```

`/posts`, `/posts?status=published` and `/posts?author_id=3&q=crystal` all run this one query.

## Related rows: a JOIN

`sqlc.embed(table)` returns a table's columns as a nested struct:

```sql
-- name: ListPostsWithAuthor :many
SELECT sqlc.embed(posts), sqlc.embed(authors)
FROM posts
JOIN authors ON authors.id = posts.author_id
ORDER BY posts.id;
```

```crystal
store.list_posts_with_author.each do |row|
  post = row.posts.not_nil!
  author = row.authors.not_nil!
  # post.title, author.name
end
```

The embedded fields are typed nilable because the generator can't always tell inner from outer joins; after an inner `JOIN` they're always present. A one-to-many join returns the parent once per child.

## Related rows: one query per level

To attach each author's posts without repeating the author on every row, load the posts for all authors at once and group them:

```sql
-- name: ListAuthors :many
SELECT id, name, bio FROM authors ORDER BY id;

-- name: ListPostsByAuthors :many
SELECT id, author_id, title, status
FROM posts
WHERE author_id = ANY(sqlc.arg(author_ids)::bigint[])
ORDER BY id;
```

```crystal
authors = store.list_authors
posts_by_author = store.list_posts_by_authors(author_ids: authors.map(&.id)).group_by(&.author_id)

render_json(authors.map { |author|
  titles = posts_by_author[author.id]?.try(&.map(&.title)) || [] of String
  {id: author.id, name: author.name, posts: titles}
})
```

Two queries however many authors — what Active Record calls eager loading. `ANY(...)` also accepts an empty array.

## Counts and aggregates

```sql
-- name: CountPostsPerAuthor :many
SELECT authors.id, authors.name, count(posts.id) AS post_count
FROM authors
LEFT JOIN posts ON posts.author_id = authors.id
GROUP BY authors.id, authors.name
ORDER BY authors.id;
```

`row.post_count` is an `Int64`.

## Partial updates

For `PATCH`, an omitted field must be left alone, while an explicit `null` clears it. Contracts tell the two apart with `<field>_present?` ([details](/guide/contracts#missing-vs-null)); pass that flag to the query:

```sql
-- name: UpdateAuthor :one
UPDATE authors SET
  name = CASE WHEN sqlc.arg(name_present)::boolean THEN sqlc.narg(name)::text ELSE name END,
  bio  = CASE WHEN sqlc.arg(bio_present)::boolean  THEN sqlc.narg(bio)::text  ELSE bio  END
WHERE id = sqlc.arg(id)
RETURNING id, name, bio;
```

```crystal [src/actions/authors/update_author_contract.cr]
class Authors::UpdateAuthorContract < RequestValidation::Contract
  schema do
    required :id, Int64                      # from the path
    optional :name, String, filled: true     # from the body
    optional :bio, String, nullable: true
  end
end
```

```crystal [src/actions/authors/update_author.cr]
class Authors::UpdateAuthor < Blog::BaseAction
  patch "/authors/:id"

  call do
    input = validate(UpdateAuthorContract)
    author = store.update_author?(id: input.id,
      name: input.name, name_present: input.name_present?,
      bio: input.bio, bio_present: input.bio_present?)
    if author
      render_json({id: author.id, name: author.name, bio: author.bio})
    else
      render_json({error: "author_not_found"}, status_code: 404)
    end
  end
end
```

One contract covers the whole request: `validate` merges the path parameters with the body, so `id` comes from `/authors/:id`. `{"name":"Ada"}` keeps the bio; `{"bio":null}` clears it.

## Transactions

Group writes that must succeed or fail together in `store.transaction`:

```sql
-- name: CreateAuthor :one
INSERT INTO authors (name) VALUES (sqlc.arg(name))
RETURNING id, name, bio;
```

```crystal
call do
  post = store.transaction do |tx|
    author = tx.create_author(name: input.author_name)
    tx.create_post(author_id: author.id, title: input.title)
  end.not_nil!
  render_json({id: post.id}, status_code: 201)
end
```

Every call on `tx` uses the same connection and commits together; an exception inside the block rolls everything back. Render **after** the block, so a client never sees data that was rolled back.

`transaction` returns the block's value as a nilable type: it's `nil` only if you roll back deliberately with `raise DB::Rollback`. When you don't do that, `.not_nil!` is safe.

To turn a constraint violation into a response, add a `rescue` to the `call` block and check the PostgreSQL error code:

```crystal
call do
  author = store.create_author(name: input.name)
  render_json({id: author.id}, status_code: 201)
rescue error : PQ::PQError
  raise error unless error.field_message(:code) == "23505"   # unique_violation
  render_json({error: "already_exists"}, status_code: 409)
end
```

For `:execrows`, batch inserts and `COPY` bulk import, see the crsql [query guide](https://github.com/shootingfly/sqlc-gen-crystal/blob/main/docs/queries.md). The [crsql example](https://github.com/runcobo/runcobo/tree/main/examples/crsql) in the repository is a complete, tested application.

## Coming from Active Record

crsql works differently from Active Record–style ORMs such as Rails' Active Record or Lucky's Avram: you start from SQL rather than from model classes. If you've used one of those, this is where the familiar pieces went:

| Active Record–style | crsql |
| --- | --- |
| Model class | A generated row struct per query (`GetPostRow`) — data only, no methods |
| `Post.where(...)`, scopes | A named query per access pattern: `store.search_posts(...)` |
| Query builder | [Optional filters](#optional-filters) with nullable parameters |
| Associations, eager loading | A [JOIN](#related-rows-a-join), or [one query per level](#related-rows-one-query-per-level) |
| `save`, `update`, `destroy` | `INSERT`, `UPDATE`, `DELETE` queries, with `RETURNING` when you need the row |
| Validations | [Request contracts](/guide/contracts) for input; database constraints (`NOT NULL`, `UNIQUE`, foreign keys) for data |
| Callbacks | Plain code in the action or a service, called explicitly |
| Lazy loading | None — every query runs exactly where you call it |

**What you gain:** the SQL in `db/queries/` is exactly what runs, so N+1 problems are visible as a query inside a loop. Queries are checked against your migrations when you generate, and every call is checked by the compiler — renaming a column breaks the build, not production. And you can use all of PostgreSQL: CTEs, window functions, `JSONB`, `ON CONFLICT`.

**What it costs:** you write SQL for each operation, including simple CRUD. A query's shape is fixed when you generate — values can vary freely, but a different `ORDER BY` column or set of joins per request means a separate query for each variant. And rows don't link to each other; you load related data explicitly.
