Optimizing thumbnail query with rawSql.

Yes this makes the project dependant on PostgreSql, but ...