Skip to main content

pgvector: PostgreSQL Vector Extension for AI Applications

pgvector brings vector similarity search directly into PostgreSQL. Store embeddings as a native column type, create HNSW or IVFFlat indexes for fast ANN search, and combine semantic search with SQL WHERE clauses, JOINs, and transactions — all in your existing database. No new infrastructure, no new operational burden.

✓ Native PostgreSQL extension ✓ HNSW & IVFFlat indexes ✓ SQL JOINs + vector search ✓ Row-level security ✓ Works with Supabase, Neon, RDS
Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →

Installation & Schema Setup

Enable the extension, create a table with a vector column, and set up HNSW indexing.

-- Enable pgvector extension (requires superuser or rds_superuser on RDS)
CREATE EXTENSION IF NOT EXISTS vector;

-- Create a documents table with an embedding column
-- dimension must match your embedding model (OpenAI 3-small = 1536)
CREATE TABLE documents (
    id          BIGSERIAL PRIMARY KEY,
    content     TEXT NOT NULL,
    category    VARCHAR(64),
    user_id     BIGINT REFERENCES users(id),
    created_at  TIMESTAMPTZ DEFAULT NOW(),
    embedding   vector(1536)    -- pgvector column type
);

-- Create HNSW index for fast approximate nearest neighbor search
-- HNSW is recommended over IVFFlat for most use cases (better recall, faster queries)
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);

-- For L2 distance use: vector_l2_ops
-- For inner product use: vector_ip_ops

-- (Alternative) IVFFlat index — faster to build, lower memory, less accurate
-- lists = sqrt(row_count) is a good starting point
CREATE INDEX ON documents USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);

Insert Embeddings & Run Similarity Search

Store OpenAI embeddings and query with cosine distance, combining with SQL filters.

import openai
import psycopg2
import json

oa = openai.OpenAI()
conn = psycopg2.connect("postgresql://user:pass@localhost/mydb")
cur = conn.cursor()

# Generate and store an embedding
def embed(text: str) -> list[float]:
    return oa.embeddings.create(
        model="text-embedding-3-small",
        input=text
    ).data[0].embedding

docs = [
    ("RAG combines retrieval with LLM generation", "ai"),
    ("pgvector adds vector search to PostgreSQL",  "database"),
    ("HNSW is the recommended ANN index type",     "database"),
]

for content, category in docs:
    emb = embed(content)
    cur.execute(
        "INSERT INTO documents (content, category, embedding) VALUES (%s, %s, %s)",
        (content, category, json.dumps(emb))   # psycopg2 auto-converts list to vector
    )
conn.commit()

# Similarity search with cosine distance (<=>)
query_emb = embed("how does retrieval augmented generation work")

cur.execute("""
    SELECT content, category,
           embedding <=> %s::vector AS distance
    FROM documents
    WHERE category = 'ai'           -- SQL filter (pre-filter with HNSW iterative scan)
    ORDER BY distance               -- nearest first
    LIMIT 5
""", (json.dumps(query_emb),))

for row in cur.fetchall():
    print(f"dist={row[2]:.4f} | {row[0]}")

Advanced: SQL JOINs, CTEs & Row-Level Security

pgvector's biggest advantage — combine vector similarity with full SQL capabilities.

-- JOIN vector search with user data (pgvector's killer feature)
SELECT
    d.content,
    u.name AS author,
    d.created_at,
    d.embedding <=> query.vec AS similarity_distance
FROM
    documents d
    JOIN users u ON d.user_id = u.id,
    (SELECT %s::vector AS vec) query   -- parameterized query vector
WHERE
    d.created_at > NOW() - INTERVAL '30 days'
    AND d.category IN ('ai', 'database')
ORDER BY
    similarity_distance
LIMIT 10;

-- Row-Level Security for multi-tenant vector search
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON documents
    USING (user_id = current_setting('app.user_id')::bigint);

-- Now every query automatically filters to current user's vectors
-- Perfect for SaaS applications with per-user document stores

-- Tune HNSW search precision vs. speed at query time
SET hnsw.ef_search = 100;   -- default 40; higher = better recall, slower

-- Check index usage
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM documents
ORDER BY embedding <=> '[...]'::vector LIMIT 5;

pgvector vs Dedicated Vector Databases

Feature pgvector Pinecone Qdrant Weaviate
SQL JOINsYes (full SQL)NoNoNo
ACID transactionsYesNoNoNo
Row-level securityYes (Postgres RLS)NamespacesPayload filterMulti-tenancy
Max practical scale~50M vectors100M+100M+100M+
Hybrid searchManual (FTS + vector)LimitedNative sparse+denseBM25 + vector
Ops overheadLow (existing PG)None (managed)Low–mediumLow–medium
Best forExisting PG users, SQL+vectorManaged prodHigh perf self-hostHybrid RAG, SaaS

Frequently Asked Questions

What is pgvector and why use it?▼

pgvector is a PostgreSQL extension that adds a native vector column type and similarity search operators. It lets you store embeddings directly in your existing Postgres database alongside relational data, enabling vector search with full SQL — JOINs, WHERE filters, CTEs, transactions, and RLS (Row Level Security). If you already use PostgreSQL, pgvector is often the fastest path to production vector search.

What is the difference between IVFFlat and HNSW indexes in pgvector?▼

IVFFlat divides vectors into 'lists' (clusters) and searches only the nearest clusters. It has faster build time and lower memory use but requires lists to be set at creation. HNSW (added in pgvector 0.5.0) builds a navigable small world graph — it has better recall (higher accuracy), faster queries, but longer build time and higher memory usage. For most production use cases, HNSW is now the recommended choice.

What distance operators does pgvector support?▼

pgvector provides three operators: <-> for L2 (Euclidean) distance, <#> for negative inner product (use for cosine-normalized vectors or dot product similarity), and <=> for cosine distance. Cosine distance (<=> operator) is most commonly used for text embeddings from OpenAI, Cohere, etc. Your ORDER BY clause should use the same metric your embedding model was trained with.

How many vectors can pgvector handle?▼

pgvector handles millions of vectors well on adequate hardware. The main constraint is that HNSW indexes are loaded into shared_buffers memory during search. For 1M vectors at 1536 dims (float32), the raw data is ~6GB; the HNSW index adds ~2-3x on top. With proper Postgres tuning (work_mem, shared_buffers), 10-50M vectors are feasible on high-memory instances. For 100M+, dedicated vector databases (Qdrant, Milvus) become more cost-efficient.

Can I combine vector search with SQL filters in pgvector?▼

Yes — this is pgvector's primary advantage over dedicated vector databases. You can combine <-> / <=> with any SQL WHERE clause: filter by user_id, date range, status, and then rank by similarity. For best performance with HNSW, apply pre-filters using a WHERE clause rather than post-filtering results — pgvector's iterative index scan will traverse the HNSW graph while respecting your filter.

pgvector vs dedicated vector databases: when to choose each?▼

Choose pgvector when: you already use PostgreSQL, your vector count is under 10-50M, you need SQL JOINs between vectors and relational data, or you want a simpler stack. Choose a dedicated vector DB (Pinecone, Qdrant, Weaviate) when: you need billion-scale search, advanced hybrid search (sparse+dense), managed infrastructure with auto-scaling, or performance-critical low-latency at very high QPS.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

CrewAI Agent Config Generator Embedding Storage Calculator Test Coverage Calculator AI Safety Checklist Generator Jotai Atom Explorer RAG Chunk Size Optimizer CSS Container Query Builder AI Agent Memory Planner AI Hallucination Detector RAG Chunking Calculator LangChain PromptTemplate Builder Neon DB Query Builder SQL ERD Diagram Generator MySQL Query Explainer PostgreSQL EXPLAIN Analyzer GraphQL Fragment Generator Jest Coverage Config Generator Cron Expression Explainer Font Pairing Preview AI Agent Run Cost Tracker RAG Chunking Calculator AI Pipeline DAG Builder AI Rate Limit Calculator Prompt Injection Tester Vibe Coding Prompt Optimizer AI IDE Comparator PostgreSQL Connection String Builder Turso Edge DB Explorer AI Commit Message Generator AI Doc Generator — Pro Tool AI Regex Explainer — Pro Tool AI System Guardian AI Token Cost Calculator LLM Cost Calculator SQL Index Advisor Vitest Configuration Generator Prisma Schema Visualizer AI Prompt Cost Calculator AI Model Comparator Mermaid Diagram Generator Elasticsearch Query Tester mTLS Certificate Chain Builder AI Model Benchmark Comparator SQL Query Formatter Pro JS Prototype Chain Visualizer Database Schema Visualizer OpenAI Token Counter AI Model Context Window Visualizer LLM JSON Schema Builder OpenAI Prompt Tester AI Model Comparison Tool Multi-Agent Orchestration Planner OpenAI Function Calling Generator Token Counter & Cost Estimator AI Model Comparison Table AI API Rate Limit Calculator LLM Prompt Template Builder Database Schema Diff PlanetScale Branch Manager HTTP Headers Analyzer AI Code Review — Pro Tool AI Error Explainer — Pro Tool AI SQL Builder — Pro Tool AI Unit Test Generator — Pro Tool Color Palette Generator Docker Compose Generator JWT Decoder Prompt Template Builder Regex Tester RSA Key Pair Generator UUID v7 Generator SMTP Server Tester Biome Config Generator Terraform Variable Validator Haproxy Config Validator SBOM Generator AI Variable Namer AI PR Description Generator AI JSDoc Generator K8s Resource Limits Calculator LLM Context Window Calculator Regex Flags Explainer OAuth2 Flow Visualizer Prompt Token Estimator Database Index Analyzer Jest Testing Framework Guide Vitest Guide — Vite-native Testing Playwright E2E Testing Guide Core Web Vitals Calculator LLM Prompt Cost Calculator System Prompt Builder SQL to TypeScript Types Database Index Advisor Solana Program ID Generator Multi-Chain Wallet Address Validator LLM System Prompt Analyzer AI Embeddings Dimension Explorer Bezier Curve Editor LLM Benchmark Calculator Token Context Calculator LLM Prompt Caching Calculator AI Prompt Token Estimator AI Context Window Visualizer Embedding Similarity Calculator TypeScript Discriminated Union Builder Core Web Vitals Budget Calculator JWT Decoder & Validator Blockchain Transaction Fee Calculator Database Query Cost Analyzer

Related Articles

Apr 1, 2026 · 12 min read

Vector Database Comparison 2026: Pinecone vs Weaviate vs Qdrant vs Chroma

In-depth comparison of the top vector databases in 2026. Evaluate Pinecone, Weaviate, Qdrant, and Chroma on performance, scalability, filtering, pricing, and self-hosting for production AI applications.

Apr 1, 2026 · 13 min read

Vector Databases Explained: Pinecone vs Weaviate vs Qdrant vs Chroma (2026 Guide)

A complete comparison of the best vector databases in 2026: Pinecone, Weaviate, Qdrant, Chroma, and pgvector. Pricing, code examples, performance benchmarks, and a clear decision framework for AI and LLM applications.

Mar 28, 2026 · 12 min read

Building a RAG Pipeline from Scratch: Embeddings, Vector Databases, and Retrieval

Step-by-step guide to building a production-ready RAG pipeline in Python. Covers embeddings, chunking strategies, Chroma and Pinecone setup, hybrid search, reranking, and evaluation with RAGAS.

Mar 28, 2026 · 14 min read

Building Production RAG Systems with LlamaIndex and Vector Databases 2026

Complete guide to building production-ready RAG systems with LlamaIndex v0.10+. Covers chunking strategies, embedding models, Chroma, Pinecone, Weaviate integration, and advanced retrieval patterns.

Mar 28, 2026 · 18 min read

Building a Production RAG Pipeline: Complete Implementation Guide 2026

A comprehensive guide to building production-ready RAG pipelines in 2026. Covers chunking strategies, embedding models, vector store selection, retrieval techniques, reranking, evaluation with RAGAS/TruLens, and LangChain vs LlamaIndex vs custom implementations.

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →