Why not use the native functions [0] of the DB? Presumably they're going to be faster. For example, computing the median of a table `nums` with columns `id` and `num` can be done like this:
WITH ordered_nums AS (
SELECT num, ROW_NUMBER() OVER (ORDER BY num) as rn,
COUNT(*) OVER() as total
FROM nums
)
SELECT AVG(num) as median
FROM ordered_nums
WHERE rn IN (
(total + 1) / 2,
(total + 2) / 2
);
[0]: https://www.sqlite.org/lang_corefunc.html