postgres optimization and query facilities

Comparing joins and subqueries

Comparing transient tables and queries

Analyzing query optimizer

Table partitioning

Partitioning: splitting what is logically one large table into smaller physical pieces.

Window functions

SELECT year, ROW_NUMBER() OVER (ORDER BY year DESC) AS seq_num
FROM -- ...
-- year | seq_num
-- 1999 | 1
-- 1999 | 2
-- 1998 | 3
-- 1997 | 4

SELECT year, ROW_NUMBER() OVER (PARTITION BY year DESC) AS seq_num
FROM -- ...
-- year | seq_num
-- 1999 | 1
-- 1999 | 2
-- 1998 | 1
-- 1997 | 1

SELECT gender, year, champion,
    LAG(champion) OVER (PARTITION BY gender ORDER BY year DESC)
    AS last_champion
FROM -- ...
-- gender | year | champion | last_champion
-- male   | 1990 |  CZE     |  null
-- male   | 1990 |  NOR     |  CZE
-- female | 1990 |  NOR     |  null
-- female | 1990 |  GYE     |  NOR

SELECT SUM(medals) OVER (PARTITION BY country)
SELECT COUNT(medals) OVER (PARTITION BY country)
SELECT AVG(medals) OVER (PARTITION BY country)

Fetching with offsets and frames

Example

SELECT
    year,
    medals,
    MAX(medals) OVER (
        ORDER BY year ASC
    ) AS max_medals,
    MAX(medals) OVER (
        ORDER BY year ASC
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS max_medals_thus_far