Skip to content
Advertisement

Find closest match in SQL

Given a table called “Example” as follows;

  • If searching for X,Y,A = returns row 1 (Exact match)
  • If searching for Q,X,A = returns row 3 (Closest match)

I can do this as multiple seperate SQL statements

… if this returns zero rows, then :

… if this returns zero rows, then :

… if this returns zero rows, then :

… etc.

But I would imagine this is going to be very bad for performance. Is there a better way?

Advertisement

Answer

From a performance perspective, you probably want:

The where clause is important if your table has any size to it. It guarantees that at least one column matches — and that should reduces the amount of data needed for sorting.

If you have multiple indexes on the table (see further down), then an exhaustive approach using union all might provide to have better performance. Looking for full matches and matches on 2 out of 3, this looks like:

In particular, this can take advantage of three indexes: (a, b, c), (a, c), and (b, c). Each CTE should be a simple index lookup and it is hard to see how the query could be faster.

It can, of course, be extended to handle singleton matches as well — using the same indexes.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement