Optimisation postgres windows query
Following @a_horse_with_no_name's suggestion again, because he's really smart though super, super-resilient to using the Post Your Answer functionality.

SELECT DISTINCT ON(id),
  id,
  views - lead(views) OVER (PARTITION BY id ORDER BY update_date DESC) AS vdiff
FROM (
  SELECT id,
    views,
    update_desc,
    row_number() OVER (PARTITION BY id ORDER BY update_date DESC) AS rn
  FROM videoupdate
) AS t
WHERE rn &lt;=2
ORDER BY id, update_desc DESC;