

# Sort key, binning, and hash functions

Use these functions to compute values that help you sort and group rows, such as one sort key for several columns, the bounds of equal-width bins, or a hash. For more information about cryptographic hash functions, such as `sha256`, see [Blob and bitstring functions in DuckDB](duckdb-functions-binary.md).

## `create_sort_key` function
<a name="athena-duckdb-functions-utility-create-sort-key"></a>

Encodes one or more values, each with its own sort order, into one key. Comparing two keys with `<` or `>`, or sorting by the key, gives the same order as an `ORDER BY` clause with the same values and sort orders.

Use `create_sort_key` when you need the order of several columns as one value, for example as the second argument of `arg_min` or `arg_max`.

### Syntax
<a name="athena-duckdb-functions-utility-create-sort-key-syntax"></a>

```sql
create_sort_key({{value}}, {{sort_order}}
    [, {{value}}, {{sort_order}}, ...])
```

### Arguments
<a name="athena-duckdb-functions-utility-create-sort-key-arguments"></a>

The `create_sort_key` function takes the following arguments:

**{{value}}**  
A value to sort by, of any data type.

**{{sort\_order}}**  
The sort direction and the position of `NULL` values for the `value` before it. It must be a constant `VARCHAR` value: `ASC` or `DESC`, followed by `NULLS FIRST` or `NULLS LAST`, for example `'DESC NULLS LAST'`. Case does not matter.

### Return type
<a name="athena-duckdb-functions-utility-create-sort-key-return-type"></a>

`BLOB`. When the key is short enough to fit in 8 bytes, the result is a `BIGINT` instead. For example, a single `INTEGER`, `DATE`, or `BOOLEAN` value gives a `BIGINT`, but a single `BIGINT`, `DOUBLE`, or `TIMESTAMP` value gives a `BLOB`. A key that includes a `VARCHAR` value is also a `BLOB`.

### Examples
<a name="athena-duckdb-functions-utility-create-sort-key-examples"></a>

The following SQL query compares the keys for two strings, first in ascending order and then in descending order.

```sql
SELECT
    create_sort_key(
        'apple', 'ASC NULLS LAST'
    ) < create_sort_key('banana', 'ASC NULLS LAST') AS ascending,
    create_sort_key(
        'apple', 'DESC NULLS LAST'
    ) < create_sort_key('banana', 'DESC NULLS LAST') AS descending
```

The query returns the following result.


| ascending | descending | 
| --- | --- | 
| `true` | `false` | 

The following SQL query sorts rows by score from highest to lowest, with `NULL` scores last, and then by name.

```sql
SELECT name, score
FROM (VALUES
    ('carol', 7),
    ('alice', 9),
    ('bob', 7),
    ('dave', NULL)
) AS t(name, score)
ORDER BY create_sort_key(
    score, 'DESC NULLS LAST', name, 'ASC NULLS LAST'
)
```

The query returns the following results.


| name | score | 
| --- | --- | 
| `alice` | `9` | 
| `bob` | `7` | 
| `carol` | `7` | 
| `dave` | `NULL` | 

The following SQL query uses a key as the second argument of `arg_min` to return the name with the highest score. When two names have the same score, `arg_min` returns the one that comes first in alphabetical order.

```sql
SELECT
    arg_min(
        name,
        create_sort_key(
            score, 'DESC NULLS LAST', name,
            'ASC NULLS LAST'
        )
    ) AS result
FROM (VALUES
    ('carol', 7),
    ('alice', 9),
    ('bob', 9),
    ('dave', NULL)
) AS t(name, score)
```

The query returns the following result.


| result | 
| --- | 
| `alice` | 

### Considerations
<a name="athena-duckdb-functions-utility-create-sort-key-considerations"></a>

Every sort order must include `NULLS FIRST` or `NULLS LAST`. A sort order of only `'ASC'` or `'DESC'` makes the query fail.

Compare only keys that you build from the same data types and sort orders. A key of one data type, such as `BIGINT`, cannot be compared with a key of another, such as `BLOB`, and the query fails.

## `equi_width_bins` function
<a name="athena-duckdb-functions-utility-equi-width-bins"></a>

Divides the range from `min` to `max` into `bin_count` bins of equal width, and returns a list that holds the upper bound of each bin, in ascending order. When `nice_rounding` is `false`, the last bound equals `max`. When it is `true`, the function moves the bounds to round values, such as multiples of `5` or `20`. If any argument is `NULL`, the result is `NULL`.

Pass the result as the `bins` argument of `histogram` to count how many values fall into each bin. For more information about `histogram`, see [`histogram` function](duckdb-functions-aggregate-frequency-and-histograms.md#athena-duckdb-functions-aggregate-histogram).

### Syntax
<a name="athena-duckdb-functions-utility-equi-width-bins-syntax"></a>

```sql
equi_width_bins({{min}}, {{max}}, {{bin_count}}, {{nice_rounding}})
```

### Arguments
<a name="athena-duckdb-functions-utility-equi-width-bins-arguments"></a>

The `equi_width_bins` function takes the following arguments:

**{{min}}**  
The lower end of the range, as a number, a `DATE`, or a `TIMESTAMP`.

**{{max}}**  
The upper end of the range, of the same type as `min`. It must not be less than `min`.

**{{bin\_count}}**  
The number of bins to create, as a `BIGINT` value. It must be at least `1` and at most `1000000`.

**{{nice\_rounding}}**  
A flag that controls rounding, as a `BOOLEAN` value. Set it to `true` to move the bounds to round values, such as multiples of `5` or `20`. Rounding can change the number of bins and can make the last bound greater than `max`.

### Return type
<a name="athena-duckdb-functions-utility-equi-width-bins-return-type"></a>

A list whose element type depends on the type of `min` and `max`. For example, the result is `INTEGER[]` for `INTEGER` values, `BIGINT[]` for `BIGINT` values, `DOUBLE[]` for `DECIMAL` or `DOUBLE` values, `DATE[]` for `DATE` values, and `TIMESTAMP[]` for `TIMESTAMP` values.

### Examples
<a name="athena-duckdb-functions-utility-equi-width-bins-examples"></a>

The following SQL query splits the range from `0` to `10` into two bins, with rounding, and returns the upper bound of each bin.

```sql
SELECT equi_width_bins(0, 10, 2, true) AS result
```

The query returns the following result.


| result | 
| --- | 
| `[5, 10]` | 

The following SQL query splits the range from `3` to `97` into five bins, without and with rounding. With rounding, the bounds are multiples of 20, and the last bound is greater than `max`.

```sql
SELECT
    equi_width_bins(3, 97, 5, false) AS exact_bounds,
    equi_width_bins(3, 97, 5, true) AS rounded_bounds
```

The query returns the following result.


| exact\_bounds | rounded\_bounds | 
| --- | --- | 
| `[21, 40, 59, 78, 97]` | `[20, 40, 60, 80, 100]` | 

The following SQL query shows that rounding can change the number of bins. It asks for four bins between `0.0` and `1.0` and returns the number of bounds in each result.

```sql
SELECT
    len(
        equi_width_bins(0.0, 1.0, 4, false)
    ) AS exact_count,
    len(
        equi_width_bins(0.0, 1.0, 4, true)
    ) AS rounded_count
```

The query returns the following result.


| exact\_count | rounded\_count | 
| --- | --- | 
| `4` | `5` | 

The following SQL query passes the bins to `histogram`, which counts the values in each bin. Each map key is the upper bound of a bin, and each map value is the number of values in that bin.

```sql
SELECT
    histogram(
        x, equi_width_bins(0, 100, 4, false)
    ) AS result
FROM (VALUES (5), (30), (55), (60), (99)) AS v(x)
```

The query returns the following result.


| result | 
| --- | 
| `{25=1, 50=1, 75=2, 100=1}` | 

### Considerations
<a name="athena-duckdb-functions-utility-equi-width-bins-considerations"></a>

For integer values, every bound is an integer, so the bins can differ in width. For example, `equi_width_bins(0, 10, 3, false)` returns `[3, 6, 10]`.

With `nice_rounding` set to `true`, the number of bounds can differ from `bin_count`. For example, `equi_width_bins(0, 10, 3, true)` returns two bounds, `[5, 10]`.

If `max` is less than `min`, or `bin_count` is less than `1`, the query fails. If `min` equals `max`, the result has one bound.

## `hash` function
<a name="athena-duckdb-functions-utility-hash"></a>

Returns an unsigned 64-bit hash, as a `UBIGINT`, of the values that you pass. When you pass more than one value, the hash combines all of them. The same input always produces the same hash, so you can use `hash` to compare values or to assign rows to buckets.

`hash` does not provide cryptographic security. For a cryptographic digest, use a function such as `sha256`. For more information about `sha256`, see [`sha256` function](duckdb-functions-binary-hashing.md#athena-duckdb-functions-binary-sha256).

Unlike most functions, `hash` does not return `NULL` for a `NULL` input. It returns a fixed hash value instead.

### Syntax
<a name="athena-duckdb-functions-utility-hash-syntax"></a>

```sql
hash({{value}} [, ...])
```

### Arguments
<a name="athena-duckdb-functions-utility-hash-arguments"></a>

The `hash` function takes the following argument:

**{{value}}**  
One or more values to hash, of any type.

### Return type
<a name="athena-duckdb-functions-utility-hash-return-type"></a>

`UBIGINT`

### Examples
<a name="athena-duckdb-functions-utility-hash-examples"></a>

The following SQL query returns the hash of a string.

```sql
SELECT hash('abc') AS result
```

The query returns the following result.


| result | 
| --- | 
| `1924864467101078684` | 

The following SQL query compares hashes. Equal inputs have equal hashes, and the hash is case-sensitive.

```sql
SELECT
    hash('abc') = hash('abc') AS same_input,
    hash('abc') = hash('ABC') AS different_case
```

The query returns the following result.


| same\_input | different\_case | 
| --- | --- | 
| `true` | `false` | 

The following SQL query shows that the hash of `NULL` is not `NULL`.

```sql
SELECT hash(NULL) IS NULL AS is_null
```

The query returns the following result.


| is\_null | 
| --- | 
| `false` | 