---
title: Read and write rows
description: Find, count, add, change and delete a luna's rows with the typed methods of ctx.db, and page through them.
related:
  - /data/define-tables
  - /data/run-sql
  - /sdk/db
---

A handler needs to find and change rows without building SQL strings by hand. Each table on [`ctx.db`](/sdk/db) has typed methods that run against the luna's own database and return plain objects.

## Add a row

`insert` adds one row and returns its `t.id()` value. The examples on this page use this `List`.

```ts luna/lunas/list.ts
import { defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  visibility: "public",
  key: { id: t.string() },
  schema: {
    items: table({
      id: t.id(),
      text: t.string(),
      qty: t.int().default(1),
      done: t.bool().default(false),
    }),
  },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      const id = ctx.db.items.insert({ text });
      return { id };
    }),
  }),
});
```

The methods are synchronous, with no `await`. No other call's writes land between two lines of your code. `insertMany(rows)` adds several rows in one call.

A handler's input holds the luna's key fields as well as its arguments. Pass a table only the columns you mean to write, as `{ text }` does here.

## Find rows

`find` returns every row that matches, in the order you ask for. `first` returns the first match or `undefined`.

```ts luna/lunas/list.ts
open: h({ query: true }, (ctx) =>
  ctx.db.items.find({
    where: { done: false },
    orderBy: { id: "desc" },
    limit: 50,
  }),
),
```

`get` reads one row by its primary key, such as `ctx.db.items.get(id)`. For a key of several columns, pass the values in the key's order, such as `get([card, user])`, or an object of them.

## Filter with where

A `where` maps columns to conditions, and a row must meet all of them. A plain value matches that value, and `null` matches a column that holds `null`.

| Operator | Matches |
| --- | --- |
| `eq`, `ne` | Equal or not equal |
| `gt`, `gte`, `lt`, `lte` | Greater or less than |
| `in` | Any value in the list. An empty list matches nothing |
| `like` | A SQL `LIKE` pattern, with `%` and `_` |
| `isNull` | `null` with `true`, any other value with `false` |

```ts luna/lunas/list.ts
ctx.db.items.find({
  where: { done: false, text: { like: "%milk%" }, qty: { gte: 2 } },
});
```

A `t.json()` column compares its whole value, so an object there is the value to match. For conditions joined by `OR`, or across tables, use [Run SQL](/data/run-sql).

## Sort and page through rows

`orderBy` takes a column name for ascending order, or an object such as `{ done: "asc", id: "desc" }`. `limit` and `offset` cut the result.

To page without skipping or repeating rows as others are added, pass `startAfter` with the last row's values, one for each `orderBy` column.

```ts luna/lunas/list.ts
page: h({ args: { after: t.int().optional() }, query: true }, (ctx, { after }) =>
  ctx.db.items.find({
    orderBy: "id",
    limit: 20,
    startAfter: after ? [after] : undefined,
  }),
),
```

The app passes the last `id` it received to get the next page. End `orderBy` on a unique column, such as `id`, so that no two rows share a place.

## Count and group rows

`count` returns how many rows match a `where`. `groupBy` counts rows per value of some columns, and can add `sum`, `min` and `max` of others.

```ts luna/lunas/list.ts
totals: h({ query: true }, (ctx) =>
  ctx.db.items.groupBy(["done"], { sum: ["qty"] }),
),
```

Each group comes back as `{ done, count, sum: { qty } }`, largest groups first. `limit` keeps only the largest groups, and `where` filters the rows first.

## Change rows

`update` sets columns on every row that matches its `where`, and returns how many it changed.

```ts luna/lunas/list.ts
check: h(
  { args: { id: t.int() }, errors: { NotFound: t.json() } },
  (ctx, { id }) => {
    const changed = ctx.db.items.update({ where: { id }, set: { done: true } });
    if (changed === 0) ctx.fail("NotFound");
  },
),
```

`upsert` inserts a row, or updates the row with the same primary key. On an update it sets only the columns you pass, and the others keep their values.

```ts luna/lunas/list.ts
put: h({ args: { id: t.int(), text: t.string() } }, (ctx, { id, text }) => {
  ctx.db.items.upsert({ id, text });
}),
```

## Delete rows

`delete` removes every row that matches its `where`, and returns how many it removed.

```ts luna/lunas/list.ts
tidy: h({}, (ctx) => {
  const removed = ctx.db.items.delete({ where: { done: true } });
  return { removed };
}),
```

:::warning
`update` and `delete` without a `where` change or remove every row in the table. A handler that fails undoes its writes, but one that succeeds keeps them.
:::

In Python, the same methods take snake case names, such as `group_by` and `start_after`. [Write lunas in Python](/lunas/write-lunas-in-python) lists the differences.

## Next steps

- [Run SQL](/data/run-sql) covers joins, `OR` and anything the typed methods do not.
- [Search text](/data/search-text) finds rows by the words they contain.
- [ctx.db](/sdk/db) lists every method and option.
