Abstracting window clauses

A windowing function allows us to add columns to the result set that have been calculated on the fly. However, what happens quite frequently is that many columns are based on the same window. Putting the same clauses into your queries over and over again is definitely not a good idea, because your queries will be hard to read and therefore hard to maintain.

The WINDOW clause allows developers to predefine a window and use it at various places in the query. Here is how it works:

SELECT country, year, production,        min(production) OVER (w),        max(production) OVER (w) FROM t_oil WHERE country = 'Canada'       AND year BETWEEN 1980       AND 1985 WINDOW w AS (ORDER BY year); country | year | production | min | max --------+-------+------------+------+------ ...

Get Mastering PostgreSQL 10 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.