From 2a3292cf0045273801a31cfc57987e662351a899 Mon Sep 17 00:00:00 2001 From: Eugene Klimov Date: Tue, 14 Jul 2020 02:52:40 +0500 Subject: [PATCH] add ORDER BY ... WITH FILL, LIMIT... WITH TIES documentation to RU and EN locale (#12410) * add ORDER BY ... WITH FILL documentation to RU and EN locale Signed-off-by: Slach * Update docs/en/sql-reference/statements/select/limit.md * Update docs/en/sql-reference/statements/select/limit.md * Update docs/ru/sql-reference/statements/select/order-by.md * Update docs/en/sql-reference/statements/select/limit.md * Update docs/en/sql-reference/statements/select/order-by.md * Update docs/en/sql-reference/statements/select/order-by.md * Update docs/en/sql-reference/statements/select/order-by.md * Update docs/en/sql-reference/statements/select/order-by.md * Update docs/en/sql-reference/statements/select/order-by.md * Update docs/ru/sql-reference/statements/select/limit.md Co-authored-by: Ivan Blinkov --- .../sql-reference/statements/select/index.md | 4 +- .../sql-reference/statements/select/limit.md | 44 ++++++ .../statements/select/order-by.md | 126 +++++++++++++++++ .../sql-reference/statements/select/index.md | 4 +- .../sql-reference/statements/select/index.md | 4 +- .../sql-reference/statements/select/index.md | 4 +- .../sql-reference/statements/select/index.md | 4 +- .../sql-reference/statements/select/limit.md | 48 +++++++ .../statements/select/order-by.md | 131 +++++++++++++++++- .../sql-reference/statements/select/index.md | 4 +- 10 files changed, 360 insertions(+), 13 deletions(-) diff --git a/docs/en/sql-reference/statements/select/index.md b/docs/en/sql-reference/statements/select/index.md index f12015325f..496ff0d968 100644 --- a/docs/en/sql-reference/statements/select/index.md +++ b/docs/en/sql-reference/statements/select/index.md @@ -22,9 +22,9 @@ SELECT [DISTINCT] expr_list [WHERE expr] [GROUP BY expr_list] [WITH TOTALS] [HAVING expr] -[ORDER BY expr_list] +[ORDER BY expr_list] [WITH FILL] [FROM expr] [TO expr] [STEP expr] [LIMIT [offset_value, ]n BY columns] -[LIMIT [n, ]m] +[LIMIT [n, ]m] [WITH TIES] [UNION ALL ...] [INTO OUTFILE filename] [FORMAT format] diff --git a/docs/en/sql-reference/statements/select/limit.md b/docs/en/sql-reference/statements/select/limit.md index 3b19f5fae4..616434678a 100644 --- a/docs/en/sql-reference/statements/select/limit.md +++ b/docs/en/sql-reference/statements/select/limit.md @@ -11,3 +11,47 @@ toc_title: LIMIT `n` and `m` must be non-negative integers. If there is no [ORDER BY](../../../sql-reference/statements/select/order-by.md) clause that explicitly sorts results, the choice of rows for the result may be arbitrary and non-deterministic. + +## LIMIT ... WITH TIES modifier {#limit-with-ties} + +When you set `WITH TIES` modifier for `LIMIT n[,m]` and specify `ORDER BY expr_list`, you will get in result first `n` or `n,m` rows and all rows with same `ORDER BY` fields values equal to row at position `n` for `LIMIT n` and `m` for `LIMIT n,m`. + +This modifier also can be combined with [ORDER BY ... WITH FILL modifier](../../../sql-reference/statements/select/order-by.md#orderby-with-fill). + +For example, the following query +```sql +SELECT * FROM ( + SELECT number%50 AS n FROM numbers(100) +) ORDER BY n LIMIT 0,5 +``` + +returns +```text +┌─n─┐ +│ 0 │ +│ 0 │ +│ 1 │ +│ 1 │ +│ 2 │ +└───┘ +``` + +but after apply `WITH TIES` modifier +```sql +SELECT * FROM ( + SELECT number%50 AS n FROM numbers(100) +) ORDER BY n LIMIT 0,5 WITH TIES +``` + +it returns another rows set +```text +┌─n─┐ +│ 0 │ +│ 0 │ +│ 1 │ +│ 1 │ +│ 2 │ +│ 2 │ +└───┘ +``` +cause row number 6 have same value "2" for field `n` as row number 5 diff --git a/docs/en/sql-reference/statements/select/order-by.md b/docs/en/sql-reference/statements/select/order-by.md index 318dd143f9..393f7a00d9 100644 --- a/docs/en/sql-reference/statements/select/order-by.md +++ b/docs/en/sql-reference/statements/select/order-by.md @@ -69,3 +69,129 @@ If there is not enough RAM, it is possible to perform sorting in external memory Running a query may use more memory than `max_bytes_before_external_sort`. For this reason, this setting must have a value significantly smaller than `max_memory_usage`. As an example, if your server has 128 GB of RAM and you need to run a single query, set `max_memory_usage` to 100 GB, and `max_bytes_before_external_sort` to 80 GB. External sorting works much less effectively than sorting in RAM. + +## ORDER BY expr WITH FILL modifier {#orderby-with-fill} + +This modifier also can be combined with [LIMIT ... WITH TIES modifier](../../../sql-reference/statements/select/limit.md#limit-with-ties). + +`WITH FILL` modifier can be set after `ORDER BY expr` with optional `FROM expr`, `TO expr` and `STEP expr` parameters. +All missed values of `expr` column will be filled sequentially and other columns will be filled as defaults. + +Use following syntax for filling multiple columns add `WITH FILL` modifier with optional parameters after each field name in `ORDER BY` section. + +```sql +ORDER BY expr [WITH FILL] [FROM const_expr] [TO const_expr] [STEP const_numeric_expr], ... exprN [WITH FILL] [FROM expr] [TO expr] [STEP numeric_expr] +``` + +`WITH FILL` can be applied only for fields with Numeric (all kind of float, decimal, int) or Date/DateTime types. +When `FROM const_expr` not defined sequence of filling use minimal `expr` field value from `ORDER BY`. +When `TO const_expr` not defined sequence of filling use maximum `expr` field value from `ORDER BY`. +When `STEP const_numeric_expr` defined then `const_numeric_expr` interprets `as is` for numeric types as `days` for Date type and as `seconds` for DateTime type. +When `STEP const_numeric_expr` omitted then sequence of filling use `1.0` for numeric type, `1 day` for Date type and `1 second` for DateTime type. + + +For example, the following query +```sql +SELECT n, source FROM ( + SELECT toFloat32(number % 10) AS n, 'original' AS source + FROM numbers(10) WHERE number % 3 = 1 +) ORDER BY n +``` + +returns +```text +┌─n─┬─source───┐ +│ 1 │ original │ +│ 4 │ original │ +│ 7 │ original │ +└───┴──────────┘ +``` + +but after apply `WITH FILL` modifier +```sql +SELECT n, source FROM ( + SELECT toFloat32(number % 10) AS n, 'original' AS source + FROM numbers(10) WHERE number % 3 = 1 +) ORDER BY n WITH FILL FROM 0 TO 5.51 STEP 0.5 +``` + +returns +```text +┌───n─┬─source───┐ +│ 0 │ │ +│ 0.5 │ │ +│ 1 │ original │ +│ 1.5 │ │ +│ 2 │ │ +│ 2.5 │ │ +│ 3 │ │ +│ 3.5 │ │ +│ 4 │ original │ +│ 4.5 │ │ +│ 5 │ │ +│ 5.5 │ │ +│ 7 │ original │ +└─────┴──────────┘ +``` + +For the case when we have multiple fields `ORDER BY field2 WITH FILL, field1 WITH FILL` order of filling will follow the order of fields in `ORDER BY` clause. + +Example: +```sql +SELECT + toDate((number * 10) * 86400) AS d1, + toDate(number * 86400) AS d2, + 'original' AS source +FROM numbers(10) +WHERE (number % 3) = 1 +ORDER BY + d2 WITH FILL, + d1 WITH FILL STEP 5; +``` + +returns +```text +┌───d1───────┬───d2───────┬─source───┐ +│ 1970-01-11 │ 1970-01-02 │ original │ +│ 0000-00-00 │ 1970-01-03 │ │ +│ 0000-00-00 │ 1970-01-04 │ │ +│ 1970-02-10 │ 1970-01-05 │ original │ +│ 0000-00-00 │ 1970-01-06 │ │ +│ 0000-00-00 │ 1970-01-07 │ │ +│ 1970-03-12 │ 1970-01-08 │ original │ +└────────────┴────────────┴──────────┘ +``` + +Field `d1` doesn't fill and use default value cause we don't have repeated values for `d2` value, and sequence for `d1` can't be properly calculated. + +The following query with a changed field in `ORDER BY` +```sql +SELECT + toDate((number * 10) * 86400) AS d1, + toDate(number * 86400) AS d2, + 'original' AS source +FROM numbers(10) +WHERE (number % 3) = 1 +ORDER BY + d1 WITH FILL STEP 5, + d2 WITH FILL; +``` + +returns +```text +┌───d1───────┬───d2───────┬─source───┐ +│ 1970-01-11 │ 1970-01-02 │ original │ +│ 1970-01-16 │ 0000-00-00 │ │ +│ 1970-01-21 │ 0000-00-00 │ │ +│ 1970-01-26 │ 0000-00-00 │ │ +│ 1970-01-31 │ 0000-00-00 │ │ +│ 1970-02-05 │ 0000-00-00 │ │ +│ 1970-02-10 │ 1970-01-05 │ original │ +│ 1970-02-15 │ 0000-00-00 │ │ +│ 1970-02-20 │ 0000-00-00 │ │ +│ 1970-02-25 │ 0000-00-00 │ │ +│ 1970-03-02 │ 0000-00-00 │ │ +│ 1970-03-07 │ 0000-00-00 │ │ +│ 1970-03-12 │ 1970-01-08 │ original │ +└────────────┴────────────┴──────────┘ +``` diff --git a/docs/es/sql-reference/statements/select/index.md b/docs/es/sql-reference/statements/select/index.md index b002f5b9b4..a5ff9820a2 100644 --- a/docs/es/sql-reference/statements/select/index.md +++ b/docs/es/sql-reference/statements/select/index.md @@ -20,9 +20,9 @@ SELECT [DISTINCT] expr_list [WHERE expr] [GROUP BY expr_list] [WITH TOTALS] [HAVING expr] -[ORDER BY expr_list] +[ORDER BY expr_list] [WITH FILL] [FROM expr] [TO expr] [STEP expr] [LIMIT [offset_value, ]n BY columns] -[LIMIT [n, ]m] +[LIMIT [n, ]m] [WITH TIES] [UNION ALL ...] [INTO OUTFILE filename] [FORMAT format] diff --git a/docs/fa/sql-reference/statements/select/index.md b/docs/fa/sql-reference/statements/select/index.md index 5c7f42d1d4..2ab3fea2ff 100644 --- a/docs/fa/sql-reference/statements/select/index.md +++ b/docs/fa/sql-reference/statements/select/index.md @@ -20,9 +20,9 @@ SELECT [DISTINCT] expr_list [WHERE expr] [GROUP BY expr_list] [WITH TOTALS] [HAVING expr] -[ORDER BY expr_list] +[ORDER BY expr_list] [WITH FILL] [FROM expr] [TO expr] [STEP expr] [LIMIT [offset_value, ]n BY columns] -[LIMIT [n, ]m] +[LIMIT [n, ]m] [WITH TIES] [UNION ALL ...] [INTO OUTFILE filename] [FORMAT format] diff --git a/docs/fr/sql-reference/statements/select/index.md b/docs/fr/sql-reference/statements/select/index.md index b546250a34..5073469e65 100644 --- a/docs/fr/sql-reference/statements/select/index.md +++ b/docs/fr/sql-reference/statements/select/index.md @@ -20,9 +20,9 @@ SELECT [DISTINCT] expr_list [WHERE expr] [GROUP BY expr_list] [WITH TOTALS] [HAVING expr] -[ORDER BY expr_list] +[ORDER BY expr_list] [WITH FILL] [FROM expr] [TO expr] [STEP expr] [LIMIT [offset_value, ]n BY columns] -[LIMIT [n, ]m] +[LIMIT [n, ]m] [WITH TIES] [UNION ALL ...] [INTO OUTFILE filename] [FORMAT format] diff --git a/docs/ru/sql-reference/statements/select/index.md b/docs/ru/sql-reference/statements/select/index.md index 764e5f79ab..b735d37118 100644 --- a/docs/ru/sql-reference/statements/select/index.md +++ b/docs/ru/sql-reference/statements/select/index.md @@ -18,9 +18,9 @@ SELECT [DISTINCT] expr_list [WHERE expr] [GROUP BY expr_list] [WITH TOTALS] [HAVING expr] -[ORDER BY expr_list] +[ORDER BY expr_list] [WITH FILL] [FROM expr] [TO expr] [STEP expr] [LIMIT [offset_value, ]n BY columns] -[LIMIT [n, ]m] +[LIMIT [n, ]m] [WITH TIES] [UNION ALL ...] [INTO OUTFILE filename] [FORMAT format] diff --git a/docs/ru/sql-reference/statements/select/limit.md b/docs/ru/sql-reference/statements/select/limit.md index 5c68c22d54..03b720226f 100644 --- a/docs/ru/sql-reference/statements/select/limit.md +++ b/docs/ru/sql-reference/statements/select/limit.md @@ -1,3 +1,7 @@ +--- +toc_title: LIMIT +--- + # Секция LIMIT {#limit-clause} `LIMIT m` позволяет выбрать из результата первые `m` строк. @@ -7,3 +11,47 @@ `n` и `m` должны быть неотрицательными целыми числами. При отсутствии секции [ORDER BY](order-by.md), однозначно сортирующей результат, результат может быть произвольным и может являться недетерминированным. + +## Модификатор LIMIT ... WITH TIES {#limit-with-ties} + +Когда вы установите модификатор WITH TIES для `LIMIT n[,m]` и указываете `ORDER BY expr_list`, вы получите первые `n` или `n,m` строк и дополнительно все строки с теми же самым значениями полей указанных в `ORDER BY` равными строке на позиции `n` для `LIMIT n` или `m` для `LIMIT n,m`. + +Этот модификатор также может быть скомбинирован с [ORDER BY ... WITH FILL модификатором](../../../sql-reference/statements/select/order-by.md#orderby-with-fill) + +Для примера следующий запрос +```sql +SELECT * FROM ( + SELECT number%50 AS n FROM numbers(100) +) ORDER BY n LIMIT 0,5 +``` + +возвращает +```text +┌─n─┐ +│ 0 │ +│ 0 │ +│ 1 │ +│ 1 │ +│ 2 │ +└───┘ +``` + +но после применения модификатора `WITH TIES` +```sql +SELECT * FROM ( + SELECT number%50 AS n FROM numbers(100) +) ORDER BY n LIMIT 0,5 WITH TIES +``` + +возвращает другой набор строк +```text +┌─n─┐ +│ 0 │ +│ 0 │ +│ 1 │ +│ 1 │ +│ 2 │ +│ 2 │ +└───┘ +``` +поскольку строка на позиции 6 имеет тоже самое значение "2" для поля `n` что и строка на позиции 5 diff --git a/docs/ru/sql-reference/statements/select/order-by.md b/docs/ru/sql-reference/statements/select/order-by.md index 83b704cec8..fa0d609738 100644 --- a/docs/ru/sql-reference/statements/select/order-by.md +++ b/docs/ru/sql-reference/statements/select/order-by.md @@ -1,3 +1,7 @@ +--- +toc_title: ORDER BY +--- + # Секция ORDER BY {#select-order-by} Секция `ORDER BY` содержит список выражений, к каждому из которых также может быть приписано `DESC` или `ASC` (направление сортировки). Если ничего не приписано - это аналогично приписыванию `ASC`. `ASC` - сортировка по возрастанию, `DESC` - сортировка по убыванию. Обозначение направления сортировки действует на одно выражение, а не на весь список. Пример: `ORDER BY Visits DESC, SearchPhrase` @@ -31,7 +35,7 @@ └───┴──────┘ ``` -Выполнение запроса `SELECT * FROM t_null_nan ORDER BY y NULLS FIRST` получить: +Выполните запрос `SELECT * FROM t_null_nan ORDER BY y NULLS FIRST` чтобы получить: ``` text ┌─x─┬────y─┐ @@ -66,3 +70,128 @@ Внешняя сортировка работает существенно менее эффективно, чем сортировка в оперативке. +## Модификатор ORDER BY expr WITH FILL {#orderby-with-fill} + +Этот модификатор также может быть скобинирован с модификатором [LIMIT ... WITH TIES](../../../sql-reference/statements/select/limit.md#limit-with-ties) + +`WITH FILL` модификатор может быть установлен после `ORDER BY expr` с опциональными параметрами `FROM expr`, `TO expr` и `STEP expr`. +Все пропущенные значнеия для колонки `expr` будут заполненые значениями соответсвующими предполагаемой последовательности значений колонки, другие колонки будут заполнены значенями по умолчанию. + +Используйте следующую конструкцию для заполнения нескольких колонок с модификатором `WITH FILL` с необязательными параметрами после каждого имени поля в секции `ORDER BY`. + +```sql +ORDER BY expr [WITH FILL] [FROM const_expr] [TO const_expr] [STEP const_numeric_expr], ... exprN [WITH FILL] [FROM expr] [TO expr] [STEP numeric_expr] +``` + +`WITH FILL` может быть применене только к полям с числовыми (все разновидности float, int, decimal) или временными (все разновидности Date, DateTime) типами. +Когда не определен `FROM const_expr`, последовательность заполнения использует минимальное значение поля `expr` из `ORDER BY`. +Когда не определен `TO const_expr`, последовательность заполнения использует максимальное значение поля `expr` из `ORDER BY`. +Когда `STEP const_numeric_expr` определен, тогда `const_numeric_expr` интерпретируется `как есть` для числовых типов, как `дни` для типа Date и как `секунды` для типа DateTime. +Когда `STEP const_numeric_expr` не указан, тогда используется `1.0` для числовых типов, `1 день` для типа Date и `1 секунда` для типа DateTime. + + +Для примера, следующий запрос +```sql +SELECT n, source FROM ( + SELECT toFloat32(number % 10) AS n, 'original' AS source + FROM numbers(10) WHERE number % 3 = 1 +) ORDER BY n +``` + +возвращает +```text +┌─n─┬─source───┐ +│ 1 │ original │ +│ 4 │ original │ +│ 7 │ original │ +└───┴──────────┘ +``` + +но после применения модификатора `WITH FILL` +```sql +SELECT n, source FROM ( + SELECT toFloat32(number % 10) AS n, 'original' AS source + FROM numbers(10) WHERE number % 3 = 1 +) ORDER BY n WITH FILL FROM 0 TO 5.51 STEP 0.5 +``` + +возвращает +```text +┌───n─┬─source───┐ +│ 0 │ │ +│ 0.5 │ │ +│ 1 │ original │ +│ 1.5 │ │ +│ 2 │ │ +│ 2.5 │ │ +│ 3 │ │ +│ 3.5 │ │ +│ 4 │ original │ +│ 4.5 │ │ +│ 5 │ │ +│ 5.5 │ │ +│ 7 │ original │ +└─────┴──────────┘ +``` + +Для случая когда у нас есть несколько полей `ORDER BY field2 WITH FILL, field1 WITH FILL` порядок заполнения будет следовать порядку полей в секции `ORDER BY`. + +Пример: +```sql +SELECT + toDate((number * 10) * 86400) AS d1, + toDate(number * 86400) AS d2, + 'original' AS source +FROM numbers(10) +WHERE (number % 3) = 1 +ORDER BY + d2 WITH FILL, + d1 WITH FILL STEP 5; +``` + +возвращает +```text +┌───d1───────┬───d2───────┬─source───┐ +│ 1970-01-11 │ 1970-01-02 │ original │ +│ 0000-00-00 │ 1970-01-03 │ │ +│ 0000-00-00 │ 1970-01-04 │ │ +│ 1970-02-10 │ 1970-01-05 │ original │ +│ 0000-00-00 │ 1970-01-06 │ │ +│ 0000-00-00 │ 1970-01-07 │ │ +│ 1970-03-12 │ 1970-01-08 │ original │ +└────────────┴────────────┴──────────┘ +``` + +Поле `d1` не заполняет и используется значение по умолчанию поскольку у нас нет повторяющихся значения для `d2` поэтому мы не можем правильно рассчитать последователность заполнения для`d1`. + +Cледующий запрос (с измененым порядком в ORDER BY) +```sql +SELECT + toDate((number * 10) * 86400) AS d1, + toDate(number * 86400) AS d2, + 'original' AS source +FROM numbers(10) +WHERE (number % 3) = 1 +ORDER BY + d1 WITH FILL STEP 5, + d2 WITH FILL; +``` + +возвращает +```text +┌───d1───────┬───d2───────┬─source───┐ +│ 1970-01-11 │ 1970-01-02 │ original │ +│ 1970-01-16 │ 0000-00-00 │ │ +│ 1970-01-21 │ 0000-00-00 │ │ +│ 1970-01-26 │ 0000-00-00 │ │ +│ 1970-01-31 │ 0000-00-00 │ │ +│ 1970-02-05 │ 0000-00-00 │ │ +│ 1970-02-10 │ 1970-01-05 │ original │ +│ 1970-02-15 │ 0000-00-00 │ │ +│ 1970-02-20 │ 0000-00-00 │ │ +│ 1970-02-25 │ 0000-00-00 │ │ +│ 1970-03-02 │ 0000-00-00 │ │ +│ 1970-03-07 │ 0000-00-00 │ │ +│ 1970-03-12 │ 1970-01-08 │ original │ +└────────────┴────────────┴──────────┘ +``` diff --git a/docs/zh/sql-reference/statements/select/index.md b/docs/zh/sql-reference/statements/select/index.md index de03699045..c246f37481 100644 --- a/docs/zh/sql-reference/statements/select/index.md +++ b/docs/zh/sql-reference/statements/select/index.md @@ -24,9 +24,9 @@ SELECT [DISTINCT] expr_list [WHERE expr] [GROUP BY expr_list] [WITH TOTALS] [HAVING expr] -[ORDER BY expr_list] +[ORDER BY expr_list] [WITH FILL] [FROM expr] [TO expr] [STEP expr] [LIMIT [offset_value, ]n BY columns] -[LIMIT [n, ]m] +[LIMIT [n, ]m] [WITH TIES] [UNION ALL ...] [INTO OUTFILE filename] [FORMAT format] -- GitLab