---
title: Define tables
description: Declare the tables each luna keeps, with their column types, defaults, primary keys, indexes and single-row tables.
related:
  - /data/read-and-write-rows
  - /data/change-a-schema
  - /sdk/table
---

A luna's memory does not survive sleep, so anything it must keep goes in its tables. You declare them once on the luna type, and every luna of that type gets its own copy in its own SQLite database.

## Declare a table

The `schema` option of [`defineLuna`](/sdk/define-luna) maps each table's name to a [`table()`](/sdk/table). This `List` keeps its items in a table named `items`.

```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(),
      done: t.bool().default(false),
      due: t.timestamp().optional(),
    }),
  },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      return ctx.db.items.insert({ text });
    }),
  }),
});
```

Each luna of the type has its own `items`. The list named `groceries` never sees the rows of the list named `chores`. Handlers reach the table as [`ctx.db.items`](/sdk/db), which [Read and write rows](/data/read-and-write-rows) covers.

## Pick column types

Each column is a builder from [`t`](/sdk/t). The builder sets what the column stores and what a read gives back.

| Builder | Stores |
| --- | --- |
| `t.id()` | An integer key that Luna assigns on insert |
| `t.string()` | Text |
| `t.int()` | A whole number |
| `t.float()` | A number |
| `t.bool()` | `true` or `false` |
| `t.timestamp()` | Milliseconds since the Unix epoch, as a number |
| `t.uuid()` | A UUID, as text |
| `t.enum(["a", "b"])` | One of the listed strings |
| `t.json()` | Any JSON value, read back parsed |
| `t.bytes()` | Binary data, written as base64 text or a `Uint8Array` and read back as base64 text |
| `t.vector(dims)` | Numbers for similarity search, covered in [Search vectors](/data/search-vectors) |
| `t.blobRef(bucket)` | The path of a file in a bucket, covered in [Store files](/files-and-code/store-files) |

`t.array()` and `t.object()` cannot be columns. A deploy of such a table fails with an error that ends `arrays and objects can't be columns; use t.json()`. Store those values in a `t.json()` column.

## Make a column optional or give it a default

A column is required unless you say otherwise. Add `.optional()` to let it hold `null`, or `.default(value)` to fill it in when an insert leaves it out.

```ts luna/lunas/list.ts {4-5}
items: table({
  id: t.id(),
  text: t.string(),
  done: t.bool().default(false),
  due: t.timestamp().optional(),
}),
```

An insert may leave out the optional, defaulted and `t.id()` columns. `ctx.db.items.insert({ text })` stores `done` as `false` and `due` as `null`, and TypeScript rejects an insert that leaves out `text`.

## Choose a primary key

`t.id()` makes its column the primary key. Luna assigns each new row a number of its own, and `insert` returns it.

Without `t.id()`, name the key columns in `primaryKey`. A key of several columns lists them all.

```ts luna/lunas/board.ts
members: table(
  { user: t.string(), role: t.enum(["owner", "editor"]) },
  { primaryKey: ["user"] },
),
votes: table(
  { card: t.int(), user: t.string(), up: t.bool() },
  { primaryKey: ["card", "user"] },
),
```

The key lets you read one row with `get` and write with `upsert`. A table with neither `t.id()` nor `primaryKey` has no key to look rows up by, and both methods throw on it.

## Add indexes and unique columns

An index lets a read that filters or sorts on its columns find rows without reading the whole table. List them in `indexes`, and add `unique: true` to refuse two rows with the same values.

```ts luna/lunas/board.ts
cards: table(
  { id: t.id(), slug: t.string().unique(), lane: t.string() },
  { indexes: [{ columns: ["lane"] }] },
),
```

`.unique()` is the same rule on a single column. A write that breaks it throws, and the handler fails unless it catches the error.

An index is named `<table>_<columns>` unless you give it a `name`. Index names and table names share one set per luna type, so no two may match.

## Keep one row with singleRow

Some data is one record per luna, such as a board's settings. `singleRow: true` makes a table that holds at most one row, with no primary key.

```ts luna/lunas/board.ts
settings: table(
  { title: t.string(), color: t.string().default("blue") },
  { singleRow: true },
),
```

A single-row table has its own methods: `get()`, `set(row)`, `update(columns)` and `clear()`. `update` returns `false` when there is no row yet, so set it the first time.

```ts luna/lunas/board.ts
rename: h({ args: { title: t.string() } }, (ctx, { title }) => {
  if (!ctx.db.settings.update({ title })) ctx.db.settings.set({ title });
}),
```

`set` replaces the whole row. Columns it leaves out go back to their default or to `null`.

## Add search, location and graph indexes

Three more table options build an index Luna keeps in step with the rows.

| Option | Does |
| --- | --- |
| `search` | Full-text search over text columns, in [Search text](/data/search-text) |
| `spatial` | Rows inside a box or near a point, in [Search by location](/data/search-by-location) |
| `graph` | Rows as edges to walk, in [Walk a graph](/data/walk-a-graph) |

## Name tables and columns

A table needs at least one column. Names that start with `_luna_` are reserved for tables and columns, and table names that start with `sqlite_` are reserved too.

Names are compared without case. Two tables, or two columns of one table, that differ only in case are refused.

## Next steps

- [Read and write rows](/data/read-and-write-rows) finds, adds and changes rows in these tables.
- [Change a schema](/data/change-a-schema) shows what happens to existing lunas when you change a table.
- [table](/sdk/table) lists every option of `table()`.
