/* Available in MySQL, PostgreSQL, Oracle 21c */
SELECT
Name,
Population,
FIRST_VALUE(Population) over p_code AS first_population,
LAG(Population) over p_code AS prior_population,
LEAD(Population) over p_code AS next_population,
NTH_VALUE(Population, 3) over p_code AS third_population
FROM country
WHERE Continent = 'South America'
WINDOW p_code AS (PARTITION BY Continent ORDER BY Population)
| Name | Population | first_population | prior_population | next_population | third_population |
| Falkland Islands | 2000 | 2000 | NULL | 181,000 | NULL |
| French Guiana | 181,000 | 2000 | 2000 | 639,850 | NULL |
| Suriname | 639,850 | 2000 | 181,000 | 835,986 | 639,850 |
| Guyana | 835,986 | 2000 | 639,850 | 3,384,688 | 639,850 |
| Uruguay | 3,384,688 | 2000 | 835,986 | 7,013,078 | 639,850 |
| Paraguay | 7,013,078 | 2000 | 3,384,688 | 12,581,843 | 639,850 |
| Bolivia | 12,581,843 | 2000 | 7,013,078 | 18,289,896 | 639,850 |
| Ecuador | 18,289,896 | 2000 | 12,581,843 | 19,859,921 | 639,850 |
| ... |
| LAG(expr) is a function that returns the previous column value in the sort order. LEAD(expr) is a function that returns the next column value in the sort order. FIRST_VALUE(expr) is a function that returns the first value of the column in the sort order. LAST_VALUE(expr) is a function that returns the last value of the column in the sort order. NTH_VALUE(expr, N) is a function that returns the nth column value in the sort order. |