Schemas, Types & Indexes

24+ built-in types, constraints, hybrid row/columnar storage, BM25, HNSW, R-Tree, and blind indexes.

3 min read SpydQL & Data Modeling

SpydDB enforces strong static typing on declared fields while optionally permitting flexible JSON metadata via schemaless collections and structured json / composite / array types.

Scalar, Document & Specialized Data Types#

CategoryTypesNotes
Unsigned Integersu8, u16, u32, u64Full 64-bit unsigned range preserved natively across binary SPD2 and tagged JSON
Signed Integersi8, i16, i32, i64Two's-complement exact signed integers
Floating Pointf32, f64IEEE-754 single and double precision
Fixed-Precisiondecimal(precision, scale)Arbitrary exact financial arithmetic (scale <= 38, backed by 128-bit mantissa)
BooleanboolStrict true / false (distinct from null)
Strings & Textstring(max_len), textBounded UTF-8 string or unbounded UTF-8 text (collation supported)
BinarybytesRaw arbitrary byte sequences
Date & Timetimestamp, dateMicrosecond-precision UTC timestamp and calendar date
IdentifiersuuidCanonical 16-byte / hyphenated UUID
Document & Semi-Structuredjson, hstore, xmlNested JSON documents, string key/value maps, XML values
Vector & Spatialvector(dim), sparse_vector, multi_vector(dim), geo_point, geo_polygonDense Float32 embeddings, learned SPLADE sparse vectors, ColBERT multi-vector token matrices, WGS84 points ({lat, lng}), and GeoJSON polygons
Network & Bitsinet, cidr, macaddr, bit(n), varbit(n) / bit varying(n)IP addresses, prefixes, MAC addresses, fixed & variable-length bit strings
Rangesint4range, int8range, daterange, tsrangeHalf-open / closed continuous integer, date, and timestamp intervals
Structuredenum("a", ...), { k: type }, T[] / T[][]Enum variants, named or inline composites, multi-dimensional arrays (max nesting 8)

For deep usage and query examples across every specialized type, see Rich & Specialized Data Types.

Creating Collections#

A collection definition specifies fields, constraints, storage layout (store column for), inline indexes, foreign keys, and optional partitioning:

spydql
create collection if not exists users {
  id: u64 primary auto_increment,
  email: string(160) unique not null,
  name: string(80) not null,
  ssn: string(20) encrypted,
  balance: decimal(12, 2) default cast("0.00" as decimal(12, 2)),
  active: bool not null default true,
  tags: string(32)[],
  created_at: timestamp default now(),

  index by_name on name asc,
  unique index by_ssn on (ssn) using blind
}

Field Modifiers#

  • primary — declares the primary key field
  • auto_increment — monotonic ID allocation on insert when omitted
  • not null / nullable — explicit NULL policy (nullable unless constrained)
  • unique — enforces uniqueness (use using blind on encrypted fields)
  • default <expr> — computed default expression (such as now(), literal values, or cast(...))
  • check (<expr>) — row-level check invariant enforced at commit
  • encrypted — field-level AES-256-GCM-SIV envelope encryption (bound to collection, field, and tenant)
  • collation <name> — custom collation order for string comparisons/sorting

Hybrid Row + Columnar & Schemaless Declarations#

Combine OLTP primary-key lookups with analytical columnar storage on hot analytical fields, or allow dynamic JSON documents:

spydql
-- Hybrid OLTP + Columnar storage layout
create collection telemetry_events {
  id: u64 primary auto_increment,
  ts: timestamp not null,
  service: string(80) not null,
  status_code: u16 not null,
  latency_ms: f64 not null,
  payload: json,
  store column for (ts, service, status_code, latency_ms)
}

-- Schemaless document collection (flexible extra fields accessible via `document` / `json_text`)
create collection event_docs {
  id: u64 primary,
  title: text,
  schemaless
}

Foreign Keys & Exclusion Constraints#

spydql
create collection order_items {
  id: u64 primary auto_increment,
  order_id: u64 not null,
  sku: string(64) not null,
  qty: u32 not null check (qty > 0),

  foreign key fk_order (order_id) references orders (id) on delete restrict on update restrict,
  exclude uniq_order_sku (order_id with =, sku with =)
}

Partitioned & Time-Series Collections#

spydql
create collection metrics_by_day {
  id: u64 primary,
  day_bucket: date not null,
  metric_name: string(80) not null,
  val: f64 not null,
  partition by range (day_bucket) ("2026-01-01", "2026-04-01", "2026-07-01", "2026-10-01")
}

create collection sensor_readings {
  id: u64 primary,
  recorded_at: timestamp not null,
  value: f64 not null,
  timeseries (recorded_at, bucket 1h),
  retention 90d,
  downsample { after 1d : avg per 1h, after 30d : max per 1d }
}

Duration literals in SpydQL are unquoted integers followed by ns, us, ms, s, m, h, d, or w (for example 1h, 7d, 90d).

Schemas, Alteration & Maintenance#

spydql
-- Logical schemas (namespaces)
create schema if not exists analytics
drop schema if exists analytics restrict

-- Evolve collections online without rewriting healthy pages
alter collection users {
  add region: string(32) default "us-east",
  add index idx_users_region on (region),
  rename name to full_name,
  drop legacy_flag
}

-- Empty all rows cleanly or trigger immediate MVCC version GC & compaction
truncate collection scratch_events
maintain

Indexes & Index Types#

SpydDB supports nine transactional index kinds (btree, hash, blind, fulltext, hnsw, sparse, colbert/muvera, rtree, and graph), maintained atomically inside the same WAL/SSI transaction:

spydql
-- 1. Ordered B-Tree index (ascending or descending key direction avoids runtime sorts)
create index idx_orders_created on orders (created_at desc, id desc)

-- 2. Hash equality index (exact equality lookups)
create index idx_sessions_tok on sessions (session_hash) using hash

-- 3. Unique B-Tree index
create unique index idx_users_slug on users (slug)

-- 4. Transactional BM25 full-text index
create index idx_articles_fts on articles (title, body) using fulltext

-- 5. Dense vector similarity index (`using hnsw`)
create index idx_docs_vec on documents (embedding) using hnsw

-- 6. Learned sparse vector inverted index (`using sparse`, SPLADE Block-Max WAND)
create index idx_docs_sparse on documents (splade) using sparse

-- 7. ColBERT multi-vector index (`using colbert` or `using muvera`, MUVERA FDE + exact MaxSim)
create index idx_docs_colbert on documents (token_vecs) using colbert

-- 8. 2D geospatial cell index (`using rtree`; exact cell index for geo_point & geo_polygon)
create index idx_places_geo on places (location) using rtree

-- 7. Keyed HMAC blind index for exact equality on `encrypted` columns
create unique index idx_people_ssn on people (ssn) using blind

-- 8. Bidirectional property-graph adjacency index (outgoing + incoming edges with optional numeric weight)
create index idx_knows_graph on knows (from_id, to_id, weight) using graph

Maintain or remove indexes with:

spydql
reindex index idx_articles_fts on articles
reindex collection articles
drop index if exists idx_articles_fts on articles

Views, Sequences, Custom Types, Triggers & Routines#

spydql
-- Named composite type
create type address as { street: text, city: string(80), zip: string(20) }

-- Sequence & nextval
create sequence invoice_seq
nextval invoice_seq

-- Logical View
create view paid_orders as orders | where status == "paid" | pick id, customer_id, total

-- Materialized View (full or watermark-based incremental refresh)
create materialized view daily_revenue as
  orders | group by date_trunc("day", placed_at) | agg sum(total) as total_rev
refresh materialized view daily_revenue

-- User-defined routines, triggers & custom aggregates
create or replace function normalize_email(raw: text) -> text language spydql as lower(raw)

For full documentation on triggers, procedures, PL/pgSQL, WebAssembly UDFs, table-valued functions, and custom aggregates, see Programmability.