RANGE
RANGE is a keyword utilized in SQL for declaring a window frame in analytics functions. It instructs the SQL engine to consider rows within a specific range, where the boundaries are dictated by the values of certain columns, for processing the task at hand. This allows computations to occur over dynamic groups of records, rather than on a set, predefined number of rows.
Example
Output
Explanation
In the above example, a range type int4range
is created for storing integer values range in range_table
. A few ranges are inserted into the table. The SELECT query with the WHERE condition value_range @> 11
shows the rows where the range includes the number 11. In this case, only the range ‘[10,15]’ includes the number 11, so it returns that row only.
Example
Output
Explanation
In the given example, RANGE UNBOUNDED PRECEDING
is used within the OVER
clause to divide the employees into two groups based on their salaries. The NTILE(2)
function is used to distribute the employees into two groups. The highest salary range is denoted by 1 and the next highest by 2.
The RANGE UNBOUNDED PRECEDING
clause considers all rows from the start of the partition going back to the row in current processing. Here, it arranges employees in descending order, and divides them into two groups based on their salaries.
Example
Output
Explanation
The SQL code puts products into four groups according to their prices by descending order, using the NTILE
function. It then assigns labels to each range with a CASE
statement. Price range is defined as:
1
: High,2
: Medium High,3
: Medium Low,4
: Low.