I have the following SQL:
select code, distance from places;
The output is below:
CODE DISTANCE LOCATION
You did not say your DBMS. The following solutions are for SQL Server.
WITH D AS (
SELECT code, distance, location,
Row_Number() OVER (PARTITION BY code ORDER BY distance) Seq
FROM places
)
SELECT *
FROM D
WHERE Seq = 1
If you have a table with unique Codes, and an index in your Places table on [Code, Distance] then a CROSS APPLY solution could be better:
SELECT
X.*
FROM
Codes C
CROSS APPLY (
SELECT TOP 1 *
FROM Places P
WHERE C.Code = P.Code
ORDER BY P.Distance
) X
I cannot work on a solution for mysql unti much later.
P.S. You cannot rely on insertion order. Do not try!