# Writing queries

This page covers hand-written SQL queries. Stored procedures: [procedures.md](procedures.md). Reads of generated table models without SQL (`db.findMany`...): [models.md](models.md).

## The three methods

| Method                              | For                                   | Returns                                                  |
| :---------------------------------- | :------------------------------------ | :------------------------------------------------------- |
| ``db.query(sql`...`, options?)``    | `SELECT`, `WITH`, `VALUES`            | Array of rows                                            |
| ``db.queryOne(sql`...`, options?)`` | Reading at most one row               | The row, or `null`. More than one row: `Db2MaxRowsError` |
| ``db.execute(sql`...`, options?)``  | `INSERT`, `UPDATE`, `DELETE`, `MERGE` | Number of affected rows                                  |

A read passed to `execute`, or a write passed to `query`, raises `Db2UsageError` before any network call. A read used by several callers becomes a [named query](#named-queries), called with `db.run`.

Options:

| Option    | Methods | Purpose                                                                                                            |
| :-------- | :------ | :----------------------------------------------------------------------------------------------------------------- |
| `tag`     | all     | Business label shown in the audit trail, for instance `'contract.search'`. A string                                |
| `maxRows` | `query` | Row limit for this call, a positive integer (`0` or `NaN` would reach the driver). Default: `query.defaultMaxRows` |

The options are checked before any network call, like the arguments of the object API: a value of the wrong type, or an option the method does not take (`maxRows` on `queryOne`, a misspelt name), raises `Db2UsageError`.

## Parameters: always `${value}`

```ts
const rows = await db.query(sql`
  SELECT ID, LABEL
  FROM MYSCHEMA.CONTRACT
  WHERE CATEGORY = ${category}
    AND START_DATE >= ${startDate}
  ORDER BY ID
  FETCH FIRST 50 ROWS ONLY
`);
```

Each `${value}` becomes a `?` marker, and the value travels separately. Two reasons never to concatenate a value into the text:

1. **Security**: no SQL injection is possible.
2. **Performance**: Db2 caches the access plan of an exact SQL text. With `?`, every execution shares one plan. With literal values, each value forces a new prepare, which costs mainframe CPU.

### Accepted values

| JavaScript        | Sent to Db2                                                                                          |
| :---------------- | :--------------------------------------------------------------------------------------------------- |
| `string`          | as is                                                                                                |
| `number` (finite) | as is                                                                                                |
| `null`            | `NULL`                                                                                               |
| `bigint`          | string (for `BIGINT` or `DECIMAL`)                                                                   |
| `Buffer`          | binary, described to the driver as `VARBINARY` of its length (`BINARY`, `VARBINARY`, `BLOB` columns) |

A text compared with a column, or written to it, takes the type and length of that column: ibm_db describes each marker so before it binds the value. A text longer than the column is then refused by the driver itself, `SQLSTATE 22001` with SQLCODE -99999 (`VALUE_TOO_LONG`), not answered with no row: `WHERE CODE = ${'ABCDEF'}` on a `CHAR(4)` column fails (observed on Db2 13 for z/OS). Check the length before the query, or give the marker a longer type: `WHERE CODE = CAST(${code} AS VARCHAR(100))`. The object API checks it for you ([models.md](models.md#where)).

ibm_db, given a `Buffer` alone, describes it as character data (`VARCHAR`): Db2 13 for z/OS refuses it where binary is expected (`SQL0301N`, SQLCODE -301, in `CAST(? AS VARBINARY(4))`), and a server that accepted it would read the bytes as text. db2kit therefore sends every `Buffer` as binary, in a query, a write of the object API and an input of a procedure alike, the bytes unchanged.

Refused with an explicit message:

| JavaScript  | Reason                                              | What to do                                                     |
| :---------- | :-------------------------------------------------- | :------------------------------------------------------------- |
| `undefined` | Often a mistake, which would silently become `NULL` | Pass `null` explicitly                                         |
| `boolean`   | Db2 for z/OS has no `BOOLEAN` type                  | Pass the column value (`'Y'`, `'N'`, `1`, `0`)                 |
| `Date`      | Ambiguous time zone                                 | Pass a string `'2026-01-05'` or `'2026-01-05-10.30.00.000000'` |

## Building a query

```ts
// IN list: gives IN (?, ?, ?)
sql`... WHERE BRANCH_CODE IN ${sql.in(codes)}`;

// Optional condition
sql`SELECT ... WHERE CATEGORY = ${category} ${branchCode ? sql`AND BRANCH_CODE = ${branchCode}` : sql.empty}`;

// Dynamic conditions
const conditions = [sql`CATEGORY = ${category}`];
if (active) conditions.push(sql`ACTIVE_FLAG = ${'Y'}`);
sql`SELECT ... WHERE ${sql.join(conditions, ' AND ')}`;
```

`sql.in([])` throws, because `IN ()` is invalid SQL: handle the empty list before the query.

`sql.raw('text')` inserts text without a marker. Reserve it for identifiers chosen by the code, never for a value coming from a user. Every query containing one carries the `RAW_SQL` warning in the audit trail.

## Named queries

A read the object API cannot express (a join, an aggregate, `WITH`, `UNION`) is written once in SQL by someone fluent in it, reviewed (by the DBA for its access path), then called by name like a function, with typed parameters and rows:

```ts
// src/db2/queries/contracts.ts, in the application
import { defineQuery, sql } from 'db2kit';

export interface BranchTotal {
  branchCode: string;
  contracts: number;
  amount: number | null;
}

export const totalsByStatus = defineQuery<{ status: string; from: string }, BranchTotal>({
  name: 'contracts.totalsByStatus',
  sql: ({ status, from }) => sql`
    SELECT BRANCH_CODE, COUNT(*) AS CONTRACTS, SUM(AMOUNT) AS AMOUNT
    FROM MYSCHEMA.CONTRACT
    WHERE STATUS = ${status} AND START_DATE >= ${from}
    GROUP BY BRANCH_CODE
    ORDER BY BRANCH_CODE
    FETCH FIRST 100 ROWS ONLY`,
  columns: { branchCode: 'BRANCH_CODE', contracts: 'CONTRACTS', amount: 'AMOUNT' },
});

// In a service: no SQL, typed parameters and rows.
const totals = await db.run(totalsByStatus, { status: 'A', from: '2026-01-01' });
```

| Key       | Purpose                                                                                                                                                                                                                                  |
| :-------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`    | In the audit trail (`source: 'run:contracts.totalsByStatus'`) and in error messages                                                                                                                                                      |
| `sql`     | Function of the parameters that returns ``sql`...` ``: every value is a marker                                                                                                                                                           |
| `columns` | Each property of a row, and its column in the result as Db2 names it: the column name or its alias, upper case unless the alias is quoted. The result must have exactly these columns: checked at every run, even when no row comes back |
| `maxRows` | Rows read at most, beyond them `Db2MaxRowsError`. Default: `query.defaultMaxRows`                                                                                                                                                        |

- Give both types to `defineQuery`: the parameters (`void` for none, then `db.run(query)`), and the row. TypeScript checks every caller, and that `columns` names every property of the row. The values themselves are not checked at runtime: they come as ibm_db reads them ([Results](#results)).
- A named query is a read: a write is refused before sending. Write data with `execute`, the [object API](models.md#writing) or a stored procedure.
- `db.run(query, params, { tag })` takes a business label. `tx.run` runs it inside a transaction. Like any pure read, it is allowed in read-only mode, and retried once on a new connection when its connection is lost (`query.retryLostReads`).
- A value the `sql` tag refuses (`undefined`, a boolean, a `Date`) stops the call before sending, with the name of the query.
- Keep the named queries together in one folder of the application, one file per domain: a review, or the DBA with the `fingerprint` of the audit trail, sees every SQL text the application sends.

## Results

- **Property names**: the ones returned by Db2, hence upper case (`CUSTOMER_ID`). For another name, use a quoted alias: `CUSTOMER_ID AS "customerId"`.
- **Duplicate columns** (two `ID` in a join): `Db2UsageError`. Give one of them an alias.
- **Typing**: `db.query<MyRow>(...)` types the result. This typing is not checked at runtime.

Type mapping, as produced by `ibm_db`:

| Db2 type              | JS type | Watch out                                                                                                                                              |
| :-------------------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CHAR`, `GRAPHIC`     | string  | Trailing blanks removed (`types.trimChar`)                                                                                                             |
| `VARCHAR`, `CLOB`     | string  |                                                                                                                                                        |
| `SMALLINT`, `INTEGER` | number  |                                                                                                                                                        |
| `BIGINT`              | string  | Precision preserved                                                                                                                                    |
| `DECIMAL`, `NUMERIC`  | number  | Read as a float: exact up to 15 significant digits. Beyond that, read it as a string with a `CAST` to `VARCHAR` (syntax to validate on your subsystem) |
| `DATE`, `TIME`        | string  |                                                                                                                                                        |
| `TIMESTAMP`           | string  | `YYYY-MM-DD HH:MM:SS.ffffff`: microseconds kept, no time zone conversion. Observed on Db2 13 for z/OS                                                  |
| `BLOB`, `BINARY`      | Buffer  |                                                                                                                                                        |
| `NULL`                | null    |                                                                                                                                                        |

### An arithmetic error in the select list reads as null

On Db2 for z/OS, a division by zero or an overflow in the select list of the outermost `SELECT` does not fail the statement: Db2 assigns the null value to that column of that row and returns warning +802 (SQLSTATE `01564` for a division by zero). ibm_db does not pass a warning of a fetch on, so the row arrives with `null`, and neither db2kit nor its audit trail can tell it from a real null. The same expression in a `WHERE`, a `HAVING` or a join condition fails with -802 (SQLSTATE `22012`), a `Db2QueryError` with code `OTHER`.

When a divisor can be zero, say what you want in the SQL, so that a reader sees it: `AMOUNT / NULLIF(COUNT, 0)` for a null on purpose, or a `CASE` that returns the value the application expects. The object API writes no division.

## Performance rules

1. **Always bound the result**: `FETCH FIRST n ROWS ONLY`. `maxRows` protects Node, `FETCH FIRST` protects Db2.
2. **Explicit columns**, never `SELECT *`: less data converted and transferred.
3. **Keyset pagination**, not `OFFSET`. `OFFSET` is expensive (Db2 reads and drops every skipped row), and a pagination query was refused with SQLCODE -4743 under APPLCOMPAT V11R1 on Db2 13 (`COMPATIBILITY_LEVEL`): the compatibility level of the package, not the server version, decides which syntax is accepted:

   ```ts
   sql`SELECT ID, LABEL FROM MYSCHEMA.CONTRACT WHERE CATEGORY = ${category} AND ID > ${lastId}
       ORDER BY ID FETCH FIRST 50 ROWS ONLY`;
   ```

4. **Read without locks** when uncommitted data is acceptable: add `WITH UR` at the end of the query.
5. **No query inside a loop**: the audit trail reports `N_PLUS_ONE`. Group with `IN ${sql.in(ids)}`.
6. **Filter on indexed columns**: when in doubt, ask the DBA for the access path and give them the `fingerprint` from the audit trail.
