Inspecting Distances and Similarity Scores in pgvector

Introduction: Why Look at Distances and Similarity Scores?

Now that you have learned how to run nearest neighbor queries using different distance metrics in pgvector, it is important to go a step further and understand the actual numbers behind those results. In the previous lesson, you saw how to retrieve the most similar products to a given embedding, but the queries only showed you the product IDs and names, ordered by similarity. While this is useful, sometimes you need to see the raw distance or similarity scores themselves. These scores can help you understand how close or far apart items are in the embedding space, set thresholds for filtering results, or debug your search system.

In this lesson, you will learn how to modify your queries to display these distance and similarity values directly in your results. This will give you more insight into how your vector search is working and help you make better decisions about which products to show or recommend.

Viewing Raw L2 (Euclidean) Distance Values in SQL

Let’s start by looking at how to view the actual L2 (Euclidean) distance values in your search results. As a reminder, the <-> operator in pgvector is used to calculate the Euclidean distance between two vectors. In the previous lesson, you used this operator to order your results, but you did not display the distance values themselves.

To include the distance in your output, you can add an extra column to your SELECT statement. Here is an example query that shows the product_id, product_name, and the L2 distance from your query embedding:

SQL
SELECT product_id, product_name, embedding <-> ${QUERY_EMBEDDING} AS distance
FROM products
ORDER BY distance
LIMIT 10;

In this query, ${QUERY_EMBEDDING} should be replaced with the embedding vector you want to compare against. The embedding <-> ${QUERY_EMBEDDING} part calculates the Euclidean distance between each product’s embedding and your query embedding, and the result is shown in a column called distance. The results are ordered so that the products with the smallest distance (i.e., most similar) appear first.

For example, your output might look like this:

product_idproduct_namedistance
1Wireless Mouse0.231
7Bluetooth Mouse0.245
12Ergonomic Mouse0.260
23USB Mouse0.275
34Gaming Mouse0.290

Here, you can see not only which products are most similar to your query but also how close they are in the embedding space. A smaller distance means a higher similarity.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal