PostgreSQL using [`cube`](https://www.postgresql.org/docs/current/static/cube.html) ==== Using PostgreSQL this becomes pretty easy with [the `cube` extension which I explained on your other question](http://dba.stackexchange.com/a/163915/2639).. Sample data. CREATE TABLE foo AS SELECT * FROM ( VALUES (1, cube(ARRAY[5 , 19, 42, 12, 16]) ), (2, cube(ARRAY[3 , 23, 38, 15, 12]) ), (3, cube(ARRAY[14, 21, 32, 33, 1 ]) ), (4, cube(ARRAY[12, 29, 21, 24, 5 ]) ) ) AS t(id, c); Finding distance... SELECT id, c, c2, cube_distance(c,c2), rank() OVER (ORDER BY cube_distance(c,c2)) FROM foo CROSS JOIN ( SELECT cube(ARRAY[4,20,40,14,15]) ) AS t(c2) ORDER BY cube_distance(c, c2); Outputs. id | c | c2 | cube_distance | rank ----+---------------------+---------------------+------------------+------ 1 | (5, 19, 42, 12, 16) | (4, 20, 40, 14, 15) | 3.3166247903554 | 1 2 | (3, 23, 38, 15, 12) | (4, 20, 40, 14, 15) | 4.89897948556636 | 2 4 | (12, 29, 21, 24, 5) | (4, 20, 40, 14, 15) | 26.5706605111728 | 3 3 | (14, 21, 32, 33, 1) | (4, 20, 40, 14, 15) | 26.8700576850888 | 4