// window reference

SQL Oracle KEEP DENSE_RANK

KEEP (DENSE_RANK FIRST/LAST ORDER BY ...) keeps only the tie-winning rows of a group and aggregates over them: arg_min/arg_max as a first-class clause.

카테고리
창
Returns
type of the aggregate
In this category
76 of 79

구문

MAX(salary) KEEP (DENSE_RANK FIRST ORDER BY hire_date) OVER (PARTITION BY g)

엔진 지원

엔진Support메모
SQL Server Not built in no equivalent; ROW_NUMBER = 1 in a CTE
PostgreSQL Not built in no equivalent; DISTINCT ON or ROW_NUMBER
MySQL Not built in no equivalent; ROW_NUMBER in a CTE
SQLite Not built in no equivalent; ROW_NUMBER in a CTE
Oracle 예 Oracle-only clause, aggregate and analytic forms

예시

Oracle

-- salary of the earliest and latest hire per department
SELECT department,
       MAX(salary) KEEP (DENSE_RANK FIRST ORDER BY hire_date) AS veteran_salary,
       MAX(salary) KEEP (DENSE_RANK LAST ORDER BY hire_date) AS newest_salary
FROM employees
GROUP BY department;

Any engine

-- portable equivalent of the first column (ties broken arbitrarily)
SELECT department, salary AS veteran_salary
FROM (
  SELECT department, salary,
         ROW_NUMBER() OVER (PARTITION BY department ORDER BY hire_date) AS rn
  FROM employees
) t
WHERE rn = 1;

알아 두면 좋은 정보

  • The aggregate inside KEEP supplies the value: MAX(salary) KEEP (DENSE_RANK FIRST ORDER BY hire_date) is 'the salary of the earliest hire', FIRST_VALUE without keeping rows, and it composes with GROUP BY.
  • DENSE_RANK is mandatory wording (KEEP FIRST/LAST alone is invalid). When several rows tie for first, all of them feed the outer aggregate, so MAX and MIN can return different answers; that is how ties are made explicit.
  • Elsewhere, FIRST_VALUE(salary) OVER (PARTITION BY department ORDER BY hire_date) gives the same value on every row, or ROW_NUMBER() = 1 in a CTE gives one row per group. PostgreSQL can also use DISTINCT ON.

Questions about KEEP DENSE_RANK

What is Oracle's equivalent of arg_min?

MAX(value) KEEP (DENSE_RANK FIRST ORDER BY sort_col): the value that goes with the smallest sort key. FIRST_VALUE answers the same over a window; KEEP also works in plain GROUP BY queries.

Why DENSE_RANK and not RANK in the KEEP clause?

Syntax, not semantics: the clause is defined as KEEP (DENSE_RANK FIRST|LAST ORDER BY ...). Both behave the same here: the tie rows all participate in the outer aggregate.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.