Bun’s built-in SQLite driver (bun:sqlite) is a fast, zero-dependency SQLite interface built directly into the Bun runtime. It uses SQLite’s C library via Bun’s native bindings, making it significantly faster than the Node.js better-sqlite3 package. UUID v7 as a primary key in Bun SQLite combines the simplicity of string storage with chronological sort order. See UUID in SQLite for the storage format comparison.

Setup

bun add uuid
import { Database } from 'bun:sqlite';
import { v7 as uuidv7 } from 'uuid';

const db = new Database('app.db');

Schema: UUID v7 TEXT primary key

db.run(`
  CREATE TABLE IF NOT EXISTS orders (
    id         TEXT    PRIMARY KEY,  -- UUID v7, 36 chars, lexicographic sort = time order
    customer   TEXT    NOT NULL,
    total      REAL    NOT NULL,
    created_at TEXT    NOT NULL DEFAULT (datetime('now'))
  )
`);

SQLite’s TEXT affinity stores UUID strings as 36-character strings. Lexicographic comparison (ORDER BY id) produces chronological order for UUID v7 — 018f... < 018g... matches time order because UUID v7’s first 12 hex chars are a Unix millisecond timestamp. See Lexicographical Order.

Insert with UUID v7

const insertOrder = db.prepare(
  'INSERT INTO orders (id, customer, total) VALUES ($id, $customer, $total)'
);

function createOrder(customer: string, total: number) {
  const id = uuidv7();
  insertOrder.run({ $id: id, $customer: customer, $total: total });
  return id;
}

bun:sqlite’s prepared statements use $name parameter syntax — binding UUID strings is zero-copy in the native layer.

Cursor pagination with UUID v7

const listOrders = db.prepare<
  { id: string; customer: string; total: number },
  [string, number]
>(
  'SELECT id, customer, total FROM orders WHERE id > ? ORDER BY id LIMIT ?'
);

const listOrdersFirst = db.prepare<
  { id: string; customer: string; total: number },
  [number]
>(
  'SELECT id, customer, total FROM orders ORDER BY id LIMIT ?'
);

function getOrders(cursor?: string, limit = 20) {
  const rows = cursor
    ? listOrders.all(cursor, limit)
    : listOrdersFirst.all(limit);

  const nextCursor = rows.length === limit ? rows[rows.length - 1].id : null;
  return { rows, nextCursor };
}

See UUID v7 for Cursor Pagination.

BLOB storage (compact, 16 bytes)

function uuidToBlob(uuid: string): Buffer {
  return Buffer.from(uuid.replace(/-/g, ''), 'hex');
}

function blobToUuid(blob: Buffer): string {
  const hex = blob.toString('hex');
  return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`;
}

db.run(`
  CREATE TABLE IF NOT EXISTS events (
    id   BLOB PRIMARY KEY,  -- 16 bytes — 2.25× smaller than TEXT
    type TEXT NOT NULL
  )
`);

const id = uuidv7();
db.run('INSERT INTO events (id, type) VALUES (?, ?)', [uuidToBlob(id), 'ORDER_PLACED']);

// Note: BLOB ORDER BY is byte-order — UUID v7 bytes are big-endian, so
// lexicographic byte order matches time order for BLOB too

Drizzle ORM with Bun SQLite

import { drizzle } from 'drizzle-orm/bun-sqlite';
import { Database } from 'bun:sqlite';
import { sqliteTable, text, real } from 'drizzle-orm/sqlite-core';
import { v7 as uuidv7 } from 'uuid';
import { gt } from 'drizzle-orm';

const sqlite = new Database('app.db');
const db = drizzle(sqlite);

const orders = sqliteTable('orders', {
  id:       text('id').primaryKey().$defaultFn(() => uuidv7()),
  customer: text('customer').notNull(),
  total:    real('total').notNull(),
});

// Insert — UUID v7 generated by $defaultFn before INSERT
const [order] = await db.insert(orders)
  .values({ customer: 'Alice', total: 99.99 })
  .returning();

// Paginate
const page = await db.select().from(orders)
  .where(gt(orders.id, cursor))
  .orderBy(orders.id)
  .limit(20);

See UUID in Drizzle ORM for the full migration setup.

Further reading

External references

Frequently asked questions

Should I store UUIDs as TEXT or BLOB in Bun SQLite?

TEXT (36 chars) is simpler — UUID v7 sorts correctly as a string in SQLite's lexicographic ORDER BY. BLOB (16 bytes) is 2.25× more compact but requires conversion on every read and write, and loses the natural sort order. For most Bun applications, TEXT is the correct choice. See UUID in SQLite for the full storage comparison.

Does Bun's SQLite support UUID v7 natively?

SQLite has no built-in UUID function. Generate UUID v7 in your Bun application with Bun.randomUUIDv7() (if available) or import the uuid npm package — Bun is npm-compatible. Bind the UUID string directly to SQLite queries using bun:sqlite's parameter binding.

Can I use UUID v7 with Drizzle ORM and Bun SQLite?

Yes. Drizzle ORM supports bun:sqlite as a driver with drizzle-orm/bun-sqlite. Define your schema with text('id').primaryKey().$defaultFn(() => uuidv7()) and Drizzle generates the UUID v7 in JavaScript before the INSERT. See UUID in Drizzle ORM.