This should work for you.
SELECT *
FROM [tableName]
WHERE id IN (SELECT MAX(id) FROM [tableName] GROUP BY code)
If id is AUTO_INCREMENT, there’s no need to worry about the datetime which is far more expensive to compute, as the most recent datetime will also have the highest id.
Update: From a performance standpoint, make sure the id
and code
columns are indexed when dealing with a large number of records. If id
is the primary key, this is built in, but you may need to add a non-clustered index covering code
and id
.