In my Ktor project, I am fetching train stats from the Train Table. The query I am using responds in 200ms, whereas all of my other queries take only 90ms.
Is there a way to optimize this query?
override suspend fun getMarkerStats(): TrainStats? {
return try {
dbFactory.dbQuery {
val data = Trains.selectAll()
val totalTrains = data.count { it[MapTrains.numb] != "" }
val lateTrains = data.count { it[MapTrains.late] }
val onTimeTrains =
data.count { !it[MapTrains.late] && !it[MapTrains.cancelled] && !it[MapTrains.diverted] }
val cancelledTrains = data.count { it[MapTrains.cancelled] }
val divertedTrains = data.count { it[MapTrains.diverted] }
TrainStats(
running = totalTrains,
late = lateTrains,
onTime = onTimeTrains,
cancelled = cancelledTrains,
diverted = divertedTrains,
trainCount = totalTrains
)
}
} catch (e: Exception) {
println("Error retrieving marker stats: ${e.message}")
null
}
}
I could not find way to get all data I need in one SQL query.