Introduction
These functions help you find the first or last value in a group of rows, making it easy to pick important data points without extra work.
FIRST_VALUE(column_name) OVER (PARTITION BY partition_column ORDER BY order_column [ROWS BETWEEN ...]) LAST_VALUE(column_name) OVER (PARTITION BY partition_column ORDER BY order_column [ROWS BETWEEN ...])
SELECT FIRST_VALUE(salary) OVER (ORDER BY salary) AS lowest_salary FROM employees;
SELECT department, FIRST_VALUE(employee_name) OVER (PARTITION BY department ORDER BY hire_date) AS first_hired FROM employees;
SELECT department, LAST_VALUE(employee_name) OVER (PARTITION BY department ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_hired FROM employees;
CREATE TABLE employees ( id SERIAL PRIMARY KEY, employee_name TEXT, department TEXT, hire_date DATE, salary INT ); INSERT INTO employees (employee_name, department, hire_date, salary) VALUES ('Alice', 'Sales', '2020-01-15', 50000), ('Bob', 'Sales', '2021-03-10', 52000), ('Charlie', 'HR', '2019-07-01', 48000), ('Diana', 'HR', '2022-05-20', 47000), ('Eve', 'IT', '2021-11-11', 60000); SELECT department, employee_name, hire_date, FIRST_VALUE(employee_name) OVER (PARTITION BY department ORDER BY hire_date) AS first_hired, LAST_VALUE(employee_name) OVER (PARTITION BY department ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_hired FROM employees ORDER BY department, hire_date;
FIRST_VALUE function do in PostgreSQL?score ordered by date using LAST_VALUE in PostgreSQL?ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ensures the entire partition is considered.sales with columns region, month, and revenue, what will this query return?SELECT region, month, revenue, FIRST_VALUE(revenue) OVER (PARTITION BY region ORDER BY month) AS first_rev FROM sales ORDER BY region, month;
first_rev.SELECT employee_id, salary, LAST_VALUE(salary) OVER (ORDER BY employee_id) AS last_sal FROM employees;
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, the last value is not the last row's value.ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to get last sale per customer.Pass the test and this pattern moves unknown