From: bennomeyer (@bennomeyer) <noreply+bennomeyer@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #850: LIMIT clause interferes with ORDER BY on vector distance operations
Date: Wed, 04 Jun 2025 10:06:17 +0000
Message-ID: <gh-pgvector-pgvector-850@github.com> (raw)
## Summary
When using LIMIT with ORDER BY on pgvector distance operations (e.g., embedding <=> ?), the query returns incorrect results that don't respect the distance-based ordering.
## Environment
- pgvector version: 0.7.4
- PostgreSQL version: 17.0
- Database: PostgreSQL with pgvector extension
## Expected Behavior
The query should return the N closest vectors based on the distance calculation, properly ordered from smallest to largest distance.
## Actual Behavior
The query returns incorrect results when LIMIT is used with ORDER BY on vector distance operations. In some cases, it returns 0 results when it should return multiple results, or returns results that are not the closest vectors.
## Reproduction Steps
1. Create a table with vector embeddings:
`CREATE TABLE embeddings (
id SERIAL PRIMARY KEY,
embedding vector(1536)
);`
2. Insert multiple rows with vector data
3. Execute a query with both ORDER BY and LIMIT:
`SELECT id, embedding <=> '[0.1,0.2,...]' as distance
FROM embeddings
ORDER BY embedding <=> '[0.1,0.2,...]'
LIMIT 3;`
4. Compare with the same query without LIMIT:
`SELECT id, embedding <=> '[0.1,0.2,...]' as distance
FROM embeddings
ORDER BY embedding <=> '[0.1,0.2,...]';`
## Observed Issue
- **Without LIMIT**: Returns all rows correctly ordered by distance
- **With LIMIT**: Returns incorrect subset or sometimes 0 results, not respecting the distance-based ordering
## Workaround
Fetch all results without LIMIT and manually limit the results in application code.
## Impact
This bug severely affects vector similarity search applications, as they rely on getting the most similar vectors. Applications may return irrelevant results instead of the closest matches.
## Additional Notes
- The issue appears to be related to query planning where LIMIT is applied before the distance-based ordering
- Various SQL workarounds (subqueries, OFFSET 0, alias ordering) do not resolve the issue
- The bug is reproducible across different vector dimensions and distance operators