79622047

Date: 2025-05-14 18:11:33
Score: 0.5
Natty:
Report link
  1. This works as expected because PostgreSQL evaluates each random() call independently during execution.

  2. Here, both random() calls in the SELECT list return the same value because PostgreSQL optimizes the query by evaluating the random() expressions once. When you add ORDER BY random(), the query executor pre-evaluates the SELECT list expressions. This optimization causes both random() calls to return the same value.

  3. In this case, the subquery (select random()) is treated as a stable expression. PostgreSQL evaluates it once and reuses the result for efficiency. This is called "subquery caching".

  4. This produces different values because the reference to the outer query column g forces PostgreSQL to re-evaluate the subquery for each row. Even though g - g is always 0, the presence of the outer reference prevents optimization

Reasons:
  • Long answer (-0.5):
  • No code block (0.5):
  • Low reputation (0.5):
Posted by: dkaustubh