← Back to SQL, page 24

sql-0476 · Medium mid

Write the idea behind a 'trending posts' query that favours recent likes over old ones.

Score each post by its interactions weighted by recency, for example likes in the last 24 hours or a decaying sum where each like counts as exp(-age / half_life). Compute scores periodically into a table indexed by score, because calculating decay over all likes on every request is expensive.

Full answer

Simple window-based score:

text
SELECT post_id, COUNT(*) AS recent_likes
FROM likes WHERE created_at >= now() - interval '24 hours'
GROUP BY post_id ORDER BY recent_likes DESC LIMIT 50;

A decay score smooths the cliff at 24 hours:

text
score = SUM(power(0.5, extract(epoch FROM now() - created_at) / 21600))   -- 6-hour half-life

Alternatively, the common 'gravity' formula divides total points by (age in hours + 2) raised to a power, so newer posts rise faster.

Implementation:

  • A job every few minutes recomputes scores for posts with recent activity into trending(post_id, score, computed_at) with an index on score.
  • Only posts with activity in the last few days need recomputing.
  • Guard against manipulation: count distinct users, weight new accounts lower.

The exact formula is a product decision; the database part is efficient incremental aggregation. The SQL shown is illustrative and was not run here.

Key points

  • Weight interactions by recency
  • Window counts or decaying sums
  • Precompute scores periodically
  • Recompute only active posts
  • Count distinct users to resist gaming

Common mistakes

  • Recomputing decay over all history on each request
  • Counting raw likes without recency

Follow-ups

  • How would you personalise trending?
  • How would you choose the half-life?

Tips

  • Explain the half-life idea