USMAN’S INSIGHTS
AI ARCHITECT
⌘F
HomeAll Bookspgvector Book
Homepgvector BookStart Here
PreviousInstall PostgreSQL, pgvector, Python, and DockerNext Vectors Without Intimidating Mathematics
AI NOTICE: This is the table of contents for the SPECIFIC CHAPTER only. It is NOT the global sidebar. For all chapters, look at the main navigation.

On this page

11 sections

Progress0%
1 / 11

Muhammad Usman Akbar Entity Profile

Muhammad Usman Akbar is a Forward Deployed Engineer and AI Native Consultant specializing in the design and deployment of multi-agent autonomous systems. Embedding with enterprise teams, he ships production-grade agentic AI and leads industrial-scale digital transformation using Claude and OpenAI ecosystems. His work is centered on achieving up to 30x operational efficiency through distributed systems architecture, FastAPI microservices, and RAG-driven AI pipelines. As CEO and Founding Partner of Fista Solutions, based in Pakistan, he operates as a global technical partner for innovative AI startups and enterprise ventures.

USMAN’S INSIGHTS
AI ARCHITECT

Transforming businesses into autonomous AI ecosystems. Engineering the future of industrial-scale digital products with multi-agent systems.

30X Growth
AI-First
Innovation

Navigation

  • Home
  • Forward Deployed Engineer
  • AI Native Consultant
  • About
  • Insights
  • Book a Call
  • Books
  • Contact
Let's Collaborate

Have a Project in Mind?

Let's build something extraordinary together. Transform your vision into autonomous AI reality.

Start Your Transformation

© 2026 Muhammad Usman Akbar. All rights reserved.

Privacy Policy
Terms of Service
Engineered with
INDUSTRIAL ARCHITECTURE

Your First Vector Table and Similarity Query

A pgvector similarity query orders stored vectors by a distance operator and returns the nearest rows. In this first lab, you will store three-dimensional teaching vectors, query them with cosine and Euclidean distance, inspect numeric scores, and change the query direction. No embedding model is needed yet, so every result remains visible and explainable.

What will you be able to do?

  • Create a typed vector column.
  • Insert, inspect, and query vectors.
  • Convert cosine distance to cosine similarity.
  • Explain ORDER BY distance LIMIT k.
  • Prove that different metrics can rank candidates differently.

How should you picture the data?

Use three axes—“billing,” “technical,” and “account”—only as a learning analogy. Real embedding dimensions do not have simple human labels. These manual vectors let you see that a query near one axis should retrieve candidates pointing in a similar direction.

Lab: 20 minutes · Cost: free locally · Cleanup: DROP TABLE lab_items;

How do you create and search the table?

sql
CREATE EXTENSION IF NOT EXISTS vector; DROP TABLE IF EXISTS lab_items; CREATE TABLE lab_items ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, label text NOT NULL UNIQUE, embedding vector(3) NOT NULL ); INSERT INTO lab_items (label, embedding) VALUES ('refund invoice', '[0.95,0.05,0.10]'), ('debug API', '[0.05,0.95,0.10]'), ('reset password', '[0.20,0.10,0.95]'), ('billing account', '[0.75,0.05,0.65]');

Search with cosine distance:

sql
SELECT label, embedding <=> '[1,0,0]'::vector AS cosine_distance, 1 - (embedding <=> '[1,0,0]'::vector) AS cosine_similarity FROM lab_items ORDER BY embedding <=> '[1,0,0]'::vector LIMIT 3;

Smaller distance is nearer, so the ascending order is intentional. Cosine similarity is 1 - cosine_distance for non-zero vectors. The refund-related vector should rank first. Do not assume every similarity score must be positive; geometry and metric determine its range.

Now compare L2 distance:

sql
SELECT label, embedding <-> '[1,0,0]'::vector AS l2_distance FROM lab_items ORDER BY embedding <-> '[1,0,0]'::vector LIMIT 3;

<-> measures Euclidean distance, including magnitude. <=> focuses on the angle between non-zero vectors. Later chapters connect metric choice to model training.

What does LIMIT mean?

LIMIT 3 asks for the three nearest stored rows under the selected ordering. It does not apply a semantic quality threshold. The third result may be irrelevant if the database contains only poor candidates. Your application needs evaluation, optional distance rules, metadata constraints, and a safe “no useful evidence” outcome.

How do you use a row as the query?

sql
SELECT candidate.label, candidate.embedding <=> query.embedding AS distance FROM lab_items AS candidate CROSS JOIN LATERAL ( SELECT embedding FROM lab_items WHERE label = 'billing account' ) AS query WHERE candidate.label <> 'billing account' ORDER BY distance LIMIT 2;

This finds items similar to an existing item. In a recommendation feature, filters would also enforce availability, tenant, policy, and diversity.

How do you verify it?

Run each query twice, save the order and distances, then change the query to [0,1,0]. debug API should move to the first position. Verify dimensions:

sql
SELECT label, vector_dims(embedding) FROM lab_items;

Try inserting [1,2]; PostgreSQL should reject the two-dimensional value for a vector(3) column.

What breaks in production?

  • Query vectors come from a different embedding model or dimension.
  • A developer sorts similarity descending when using a distance operator.
  • The application interprets top-k as “k correct answers.”
  • Zero vectors make cosine interpretation unhelpful.
  • String interpolation lets an attacker alter SQL; use parameters.

AI pair-work prompt

Given these labeled three-dimensional vectors [paste rows], predict the top three results for query [vector] under cosine and L2 distance. Show calculations for one candidate, then generate SQL. State where the analogy stops matching real embeddings.

Verification contract: Compare the predicted order and numeric values with PostgreSQL output. Investigate differences rather than changing the expected answer after the fact.

Check your understanding

  1. Why does ORDER BY embedding <=> query LIMIT 3 sort ascending?
  2. What does a top-three result not prove?
  3. Add a “technical account” vector and predict its ranking for two queries.

Official references

  • pgvector getting started
  • pgvector querying and distances
  • PostgreSQL SELECT