$ ./guess_the_languageSQL & Databases
SQL & Databases · medium · #46

What is prev on the row with id 1?

-- t(id, x): (1,10), (2,20), (3,30)
SELECT id,
  LAG(x) OVER (ORDER BY id) AS prev
FROM t;
  1. 20
  2. Error
  3. 10
  4. NULL
LAG reads the previous row; the first row has none, so it returns NULL unless a default is given.
Play SQL & Databases ▸