Lably
Skip to content

Window function (SQL)

Function over multiple rows in SQL

  • 6 min read
  • 4 chapters

Related on Lably

Through SQL, Aggregate function and MySQL

Example

As an example, here is a query which uses a window function to compare the salary of each employee with the average salary of their department (example from the PostgreSQL documentation):

<span id="mwHQ"></span><span class="k" id="mwHg">SELECT</span><span class="w" id="mwHw"> </span><span class="n" id="mwIA">depname</span><span class="p" id="mwIQ">,</span><span class="w" id="mwIg"> </span><span class="n" id="mwIw">empno</span><span class="p" id="mwJA">,</span><span class="w" id="mwJQ"> </span><span class="n" id="mwJg">salary</span><span class="p" id="mwJw">,</span><span class="w" id="mwKA"> </span><span class="n" id="mwKQ">avg</span><span class="p" id="mwKg">(</span><span class="n" id="mwKw">salary</span><span class="p" id="mwLA">)</span><span class="w" id="mwLQ"> </span><span class="k" id="mwLg">OVER</span><span class="w" id="mwLw"> </span><span class="p" id="mwMA">(</span><span class="k" id="mwMQ">PARTITION</span><span class="w" id="mwMg"> </span><span class="k" id="mwMw">BY</span><span class="w" id="mwNA"> </span><span class="n" id="mwNQ">depname</span><span class="p" id="mwNg">)</span><span class="w" id="mwNw"> </span><span class="k" id="mwOA">FROM</span><span class="w" id="mwOQ"> </span><span class="n" id="mwOg">empsalary</span><span class="p" id="mwOw">;</span>

Output:

depname | empno | salary | avg ----------+-------+--------+---------------------- develop | 11 | 5200 | 5020.0000000000000000 develop | 7 | 4200 | 5020.0000000000000000 develop | 9 | 4500 | 5020.0000000000000000 develop | 8 | 6000 | 5020.0000000000000000 develop | 10 | 5200 | 5020.0000000000000000 personnel | 5 | 3500 | 3700.0000000000000000 personnel | 2 | 3900 | 3700.0000000000000000 sales | 3 | 4800 | 4866.6666666666666667 sales | 1 | 5000 | 4866.6666666666666667 sales | 4 | 4800 | 4866.6666666666666667 (10 rows)

The PARTITION BY clause groups rows into partitions, and the function is applied to each partition separately. If the PARTITION BY clause is omitted (such as with an empty OVER() clause), then the entire result set is treated as a single partition. For this query, the average salary reported would be the average taken over all rows.

Window functions are evaluated after aggregation (after the GROUP BY clause and non-window aggregate functions, for example).

Sign in to keep reading

3 more chapters are free with a Lably account.

More in Computing and communication