diff --git a/ydb/docs/en/core/concepts/_includes/ttl.md b/ydb/docs/en/core/concepts/_includes/ttl.md index 41b4e373383b..63cc21908fd8 100644 --- a/ydb/docs/en/core/concepts/_includes/ttl.md +++ b/ydb/docs/en/core/concepts/_includes/ttl.md @@ -54,7 +54,7 @@ The *BRO* has the following properties: * Nanoseconds. * You can't specify multiple TTL columns. -* You can't delete the TTL column. However, if this is required, you should first [disable TTL](../../recipes/yql/ttl.md#disable) for the table. +* You can't delete the TTL column. However, if this is required, you should first [disable TTL](../../yql/reference/recipes/ttl.md#disable) for the table. * Only {{ objstorage-name }} is supported as external storage. * The delete action can only be specified for the last tier. @@ -62,6 +62,6 @@ The *BRO* has the following properties: Currently, you can manage TTL settings using: -* [YQL](../../recipes/yql/ttl.md). +* [YQL](../../yql/reference/recipes/ttl.md). * [{{ ydb-short-name }} console client](../../recipes/ydb-cli/ttl.md). * {{ ydb-short-name }} {% if oss %}C++, {% endif %}Go and Python [SDK](../../recipes/ydb-sdk/ttl.md). diff --git a/ydb/docs/en/core/concepts/glossary.md b/ydb/docs/en/core/concepts/glossary.md index b0a382411116..ce6768a917dd 100644 --- a/ydb/docs/en/core/concepts/glossary.md +++ b/ydb/docs/en/core/concepts/glossary.md @@ -233,7 +233,7 @@ A **semaphore** is an object within a [coordination node](#coordination-node) th ### YQL {#yql} -**YQL ({{ ydb-short-name }} Query Language)** is a high-level language for working with the system. It is a dialect of [ANSI SQL](https://en.wikipedia.org/wiki/SQL). There's a lot of content covering YQL, including a [tutorial](../dev/yql-tutorial/index.md), [reference](../yql/reference/syntax/index.md), and [recipes](../recipes/yql/index.md). +**YQL ({{ ydb-short-name }} Query Language)** is a high-level language for working with the system. It is a dialect of [ANSI SQL](https://en.wikipedia.org/wiki/SQL). There's a lot of content covering YQL, including a [tutorial](../dev/yql-tutorial/index.md), [reference](../yql/reference/syntax/index.md), and [recipes](../yql/reference/recipes/index.md). ### Federated queries {#federated-queries} diff --git a/ydb/docs/en/core/recipes/index.md b/ydb/docs/en/core/recipes/index.md index 2b293d0b1a8b..a80ec20c7aa0 100644 --- a/ydb/docs/en/core/recipes/index.md +++ b/ydb/docs/en/core/recipes/index.md @@ -4,4 +4,4 @@ This section of {{ ydb-short-name }} documentation contains ready-to-use recipes * [{#T}](ydb-sdk/index.md) * [{#T}](ydb-cli/index.md) -* [{#T}](yql/index.md) \ No newline at end of file +* [{#T}](../yql/reference/recipes/index.md) diff --git a/ydb/docs/en/core/recipes/toc_p.yaml b/ydb/docs/en/core/recipes/toc_p.yaml index ca1a0901ebec..19bb3ca8a069 100644 --- a/ydb/docs/en/core/recipes/toc_p.yaml +++ b/ydb/docs/en/core/recipes/toc_p.yaml @@ -7,8 +7,8 @@ items: href: ydb-cli/index.md include: mode: link - path: ydb-cli/toc_p.yaml + path: ydb-cli/toc_p.yaml - name: YQL include: mode: link - path: yql/toc_p.yaml \ No newline at end of file + path: ../yql/reference/recipes/toc_i.yaml diff --git a/ydb/docs/en/core/recipes/ydb-cli/ttl.md b/ydb/docs/en/core/recipes/ydb-cli/ttl.md index 9d1b33d6219e..38c2b3a561f7 100644 --- a/ydb/docs/en/core/recipes/ydb-cli/ttl.md +++ b/ydb/docs/en/core/recipes/ydb-cli/ttl.md @@ -20,7 +20,7 @@ $ {{ ydb-cli }} -e -d table ttl set --column modified_at - {% include [OLTP_not_allow_note](../../_includes/not_allow_for_oltp_note.md) %} -To enable data eviction, an [external data source](../../concepts/datamodel/external_data_source.md) object that describes a connection to the external storage is needed. Refer to [YQL recipe](../yql/ttl.md#enable-tiering-on-existing-tables) for examples of creating an external data source. +To enable data eviction, an [external data source](../../concepts/datamodel/external_data_source.md) object that describes a connection to the external storage is needed. Refer to [YQL recipe](../../yql/reference/recipes/ttl.md#enable-tiering-on-existing-tables) for examples of creating an external data source. The example below shows how to enable data eviction by executing a YQL-query from {{ ydb-short-name }} CLI. Rows of the table `mytable` will be moved to the bucket described in the external data source `/Root/s3_cold_data` one hour after the time recorded in the column `created_at` and will be deleted after 24 hours. diff --git a/ydb/docs/en/core/recipes/ydb-sdk/ttl.md b/ydb/docs/en/core/recipes/ydb-sdk/ttl.md index eee688c8f425..6f0e1e9f9d77 100644 --- a/ydb/docs/en/core/recipes/ydb-sdk/ttl.md +++ b/ydb/docs/en/core/recipes/ydb-sdk/ttl.md @@ -84,7 +84,7 @@ The example below shows how to use the `modified_at` column with a numeric type {% include [OLTP_not_allow_note](../../_includes/not_allow_for_oltp_note.md) %} -To enable data eviction, an [external data source](../../concepts/datamodel/external_data_source.md) object that describes a connection to the external storage is needed. Refer to [YQL recipe](../yql/ttl.md#enable-tiering-on-existing-tables) for examples of creating an external data source. +To enable data eviction, an [external data source](../../concepts/datamodel/external_data_source.md) object that describes a connection to the external storage is needed. Refer to [YQL recipe](../../yql/reference/recipes/ttl.md#enable-tiering-on-existing-tables) for examples of creating an external data source. In the following example, rows of the table `mytable` will be moved to the bucket described in the external data source `/Root/s3_cold_data` one hour after the time recorded in the column `created_at` and will be deleted after 24 hours: diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_assets/builtin_groups.svg b/ydb/docs/en/core/yql/reference/_assets/builtin_groups.svg similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_assets/builtin_groups.svg rename to ydb/docs/en/core/yql/reference/_assets/builtin_groups.svg diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/builtin_groups.md b/ydb/docs/en/core/yql/reference/_includes/builtin_groups.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/builtin_groups.md rename to ydb/docs/en/core/yql/reference/_includes/builtin_groups.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/_includes/cast_examples.md b/ydb/docs/en/core/yql/reference/_includes/cast_examples.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/_includes/cast_examples.md rename to ydb/docs/en/core/yql/reference/_includes/cast_examples.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/_includes/decimal_args.md b/ydb/docs/en/core/yql/reference/_includes/decimal_args.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/_includes/decimal_args.md rename to ydb/docs/en/core/yql/reference/_includes/decimal_args.md diff --git a/ydb/docs/en/core/yql/reference/_includes/index/intro.md b/ydb/docs/en/core/yql/reference/_includes/index/intro.md deleted file mode 100644 index b0111c957394..000000000000 --- a/ydb/docs/en/core/yql/reference/_includes/index/intro.md +++ /dev/null @@ -1,18 +0,0 @@ -# YQL - Overview - -*YQL* ({{ ydb-short-name }} Query Language) is a universal declarative query language for {{ ydb-short-name }}, a dialect of SQL. YQL has been natively designed for large distributed databases, and therefore has a number of differences from the SQL standard. - -{{ ydb-short-name }} tools support interfaces for sending YQL queries and receiving their execution results: - -{% include [yql/ui_prompt.md](yql/ui_prompt.md) %} - -- [YDB CLI](../../../../reference/ydb-cli/index.md) -- [YDB SDK](../../../../reference/ydb-sdk/index.md) - -This documentation section contains the YQL reference that includes the sections: - -- [Data types](../../types/index.md) with a description of data types used in YQL -- [Syntax](../../syntax/index.md) with a full list of YQL commands -- [Built-in functions](../../builtins/index.md) with a description of the available built-in functions - -You can also take a tutorial to get familiar with the basic YQL commands, in the [YQL tutorial](../../../../dev/yql-tutorial/index.md) section. diff --git a/ydb/docs/en/core/yql/reference/_includes/index/start.md b/ydb/docs/en/core/yql/reference/_includes/index/start.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/en/core/yql/reference/_includes/index/yql/ui_prompt.md b/ydb/docs/en/core/yql/reference/_includes/index/yql/ui_prompt.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/permissions/permissions_list.md b/ydb/docs/en/core/yql/reference/_includes/permissions_list.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/permissions/permissions_list.md rename to ydb/docs/en/core/yql/reference/_includes/permissions_list.md diff --git a/ydb/docs/en/core/yql/reference/builtins/aggregation.md b/ydb/docs/en/core/yql/reference/builtins/aggregation.md new file mode 100644 index 000000000000..04f3db645ffd --- /dev/null +++ b/ydb/docs/en/core/yql/reference/builtins/aggregation.md @@ -0,0 +1,630 @@ +# Aggregate functions + +## COUNT {#count} + +Counting the number of rows in the table (if `*` or constant is specified as the argument) or non-empty values in a table column (if the column name is specified as an argument). + +Like other aggregate functions, it can be combined with [GROUP BY](../syntax/group_by.md) to get statistics on the parts of the table that correspond to the values in the columns being grouped. {% if select_statement != "SELECT STREAM" %}Use the modifier [DISTINCT](../syntax/group_by.md#distinct) to count distinct values.{% endif %} + +### Examples + +```yql +SELECT COUNT(*) FROM my_table; +``` + +```yql +SELECT key, COUNT(value) FROM my_table GROUP BY key; +``` + +{% if select_statement != "SELECT STREAM" %} + +```yql +SELECT COUNT(DISTINCT value) FROM my_table; +``` + +{% endif %} + +## MIN and MAX {#min-max} + +Minimum or maximum value. + +As an argument, you may use an arbitrary computable expression with a numeric result. + +### Examples + +```yql +SELECT MIN(value), MAX(value) FROM my_table; +``` + +## SUM {#sum} + +Sum of the numbers. + +As an argument, you may use an arbitrary computable expression with a numeric result. + +Integers are automatically expanded to 64 bits to reduce the risk of overflow. + +```yql +SELECT SUM(value) FROM my_table; +``` + +## AVG {#avg} + +Arithmetic average. + +As an argument, you may use an arbitrary computable expression with a numeric result. + +Integer values and time intervals are automatically converted to Double. + +### Examples + +```yql +SELECT AVG(value) FROM my_table; +``` + +## COUNT_IF {#count-if} + +Number of rows for which the expression specified as the argument is true (the expression's calculation result is true). + +The value `NULL` is equated to `false` (if the argument type is `Bool?`). + +The function *does not* do the implicit type casting to Boolean for strings and numbers. + +### Examples + +```yql +SELECT + COUNT_IF(value % 2 == 1) AS odd_count +``` + +{% if select_statement != "SELECT STREAM" %} + +{% note info %} + +To count distinct values in rows meeting the condition, unlike other aggregate functions, you can't use the modifier [DISTINCT](../syntax/group_by.md#distinct) because arguments contain no values. To get this result, use in the subquery the built-in function [IF](basic.md#if) with two arguments (to get `NULL` in else), and apply an outer [COUNT(DISTINCT ...)](#count) to its result. + +{% endnote %} + +{% endif %} + +## SUM_IF and AVG_IF {#sum-if} + +Sum or arithmetic average, but only for the rows that satisfy the condition passed by the second argument. + +Therefore, `SUM_IF(value, condition)` is a slightly shorter notation for `SUM(IF(condition, value))`, same for `AVG`. The argument's data type expansion is similar to the same-name functions without a suffix. + +### Examples + +```yql +SELECT + SUM_IF(value, value % 2 == 1) AS odd_sum, + AVG_IF(value, value % 2 == 1) AS odd_avg, +FROM my_table; +``` + +When you use [aggregation factories](basic.md#aggregationfactory), a `Tuple` containing a value and a predicate is passed as the first [AGGREGATE_BY](#aggregate-by) argument. + +```yql +$sum_if_factory = AggregationFactory("SUM_IF"); +$avg_if_factory = AggregationFactory("AVG_IF"); + +SELECT + AGGREGATE_BY(AsTuple(value, value % 2 == 1), $sum_if_factory) AS odd_sum, + AGGREGATE_BY(AsTuple(value, value % 2 == 1), $avg_if_factory) AS odd_avg +FROM my_table; +``` + +## SOME {#some} + +Get the value for an expression specified as an argument, for one of the table rows. Gives no guarantee of which row is used. It's similar to the [any()]{% if lang == "en" %}(https://clickhouse.tech/docs/en/sql-reference/aggregate-functions/reference/any/){% else %}(https://clickhouse.tech/docs/ru/sql-reference/aggregate-functions/reference/any/){% endif %} function in ClickHouse. + +Because of no guarantee, `SOME` is computationally cheaper than [MIN / MAX](#min-max) often used in similar situations. + +### Examples + +```yql +SELECT + SOME(value) +FROM my_table; +``` + +{% note alert %} + +When the aggregate function `SOME` is called multiple times, it's **not** guaranteed that all the resulting values are taken from the same row of the source table. To get this guarantee, pack the values into any container and pass it to `SOME`. For example, in the case of a structure, you can apply [AsStruct](basic.md#asstruct) + +{% endnote %} + + + +## CountDistinctEstimate, HyperLogLog, and HLL {#countdistinctestimate} + +Approximating the number of unique values using the [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog) algorithm. Logically, it does the same thing as [COUNT(DISTINCT ...)](#count), but runs much faster at the cost of some error. + +Arguments: + +1. Estimated value +2. Accuracy (4 to 18 inclusive, 14 by default). + +By selecting accuracy, you can trade added resource and RAM consumption for decreased error. + +All the three functions are aliases at the moment, but `CountDistinctEstimate` may start using a different algorithm in the future. + +### Examples + +```yql +SELECT + CountDistinctEstimate(my_column) +FROM my_table; +``` + +```yql +SELECT + HyperLogLog(my_column, 4) +FROM my_table; +``` + + + +## AGGREGATE_LIST {#agg-list} + +Get all column values as a list. When combined with `DISTINCT,` it returns only distinct values. The optional second parameter sets the maximum number of values to be returned. A zero limit value means unlimited. + +If you know already that you have few distinct values, use the `AGGREGATE_LIST_DISTINCT` aggregate function to build the same result in memory (that might not be enough for a large number of distinct values). + +The order of elements in the result list depends on the implementation and can't be set externally. To return an ordered list, sort the result, for example, with [ListSort](list.md#listsort). + +To return a list of multiple values from one line, **DO NOT** use the `AGGREGATE_LIST` function several times, but add all the needed values to a container, for example, via [AsList](basic.md#aslist) or [AsTuple](basic.md#astuple), then pass this container to a single `AGGREGATE_LIST` call. + +For example, you can combine it with `DISTINCT` and the function [String::JoinFromList](../udf/list/string.md) (it's an equivalent of `','.join(list)` in Python) to output to a string all the values found in the column after [GROUP BY](../syntax/group_by.md). + +### Examples + +```yql +SELECT + AGGREGATE_LIST( region ), + AGGREGATE_LIST( region, 5 ), + AGGREGATE_LIST( DISTINCT region ), + AGGREGATE_LIST_DISTINCT( region ), + AGGREGATE_LIST_DISTINCT( region, 5 ) +FROM users +``` + +```yql +-- An equivalent of GROUP_CONCAT in MySQL +SELECT + String::JoinFromList(CAST(AGGREGATE_LIST(region, 2) AS List), ",") +FROM users +``` + +These functions also have a short notation: `AGG_LIST` and `AGG_LIST_DISTINCT`. + +{% note alert %} + +Execution is **NOT** lazy, so when you use it, be sure that the list has a reasonable size (about a thousand items or less). To stay on the safe side, better use a second optional numeric argument that limits the number of items in the list. + +{% endnote %} + + + +## MAX_BY and MIN_BY {#max-min-by} + +Return the value of the first argument for the table row where the second argument is minimum/maximum. + +You can optionally specify the third argument N that affects behavior if the table has multiple rows with the same minimum or maximum value: + +* If N is omitted, the value of one of the rows is returned, and the other rows are discarded. +* If N is specified, the list is returned with all values, but their number can't exceed N. All values after the number are discarded. + +When choosing N, we recommend that you don't exceed several hundreds or thousands to avoid issues with the limited memory available on {{ backend_name }} clusters. + +If your task needs absolutely all values, and their number is measured in dozens of thousands or more, then instead of those aggregate functions better use `JOIN` on the source table with a subquery doing `GROUP BY + MIN/MAX` on the desired columns of this table. + +{% note warning "Attention" %} + +If the second argument is always `NULL`, the aggregation result is `NULL`. + +{% endnote %} + +When you use [aggregation factories](basic.md#aggregationfactory), a `Tuple` containing a value and a key is passed as the first [AGGREGATE_BY](#aggregate-by) argument. + +### Examples + +```yql +SELECT + MIN_BY(value, LENGTH(value)), + MAX_BY(value, key, 100) +FROM my_table; +``` + +```yql +$min_by_factory = AggregationFactory("MIN_BY"); +$max_by_factory = AggregationFactory("MAX_BY", 100); + +SELECT + AGGREGATE_BY(AsTuple(value, LENGTH(value)), $min_by_factory), + AGGREGATE_BY(AsTuple(value, key), $max_by_factory) +FROM my_table; +``` + + + +## TOP and BOTTOM {#top-bottom} + +Return a list of the maximum/minimum values of an expression. The first argument is an expression, the second argument limits the number of items. + +### Examples + +```yql +SELECT + TOP(key, 3), + BOTTOM(value, 3) +FROM my_table; +``` + +```yql +$top_factory = AggregationFactory("TOP", 3); +$bottom_factory = AggregationFactory("BOTTOM", 3); + +SELECT + AGGREGATE_BY(key, $top_factory), + AGGREGATE_BY(value, $bottom_factory) +FROM my_table; +``` + +## TOP_BY and BOTTOM_BY {#top-bottom-by} + +Return a list of values of the first argument for the rows containing the maximum/minimum values of the second argument. The third argument limits the number of items in the list. + +When you use [aggregation factories](basic.md#aggregationfactory), a `Tuple` containing a value and a key is passed as the first [AGGREGATE_BY](#aggregate-by) argument. In this case, the limit for the number of items is passed by the second argument at factory creation. + +### Examples + +```yql +SELECT + TOP_BY(value, LENGTH(value), 3), + BOTTOM_BY(value, key, 3) +FROM my_table; +``` + +```yql +$top_by_factory = AggregationFactory("TOP_BY", 3); +$bottom_by_factory = AggregationFactory("BOTTOM_BY", 3); + +SELECT + AGGREGATE_BY(AsTuple(value, LENGTH(value)), $top_by_factory), + AGGREGATE_BY(AsTuple(value, key), $bottom_by_factory) +FROM my_table; +``` + + + +## TOPFREQ and MODE {#topfreq-mode} + +Getting an **approximate** list of the most common values in a column with an estimation of their count. Returns a list of structures with two fields: + +* `Value`: the frequently occurring value that was found. +* `Frequency`: An estimated value occurrence in the table. + +Required argument: the value itself. + +Optional arguments: + +1. For `TOPFREQ`, the desired number of items in the result. `MODE` is an alias to `TOPFREQ` with this argument set to 1. For `TOPFREQ`, this argument is also 1 by default. +2. The number of items in the buffer used: lets you trade memory consumption for accuracy. Default: 100. + +### Examples + +```yql +SELECT + MODE(my_column), + TOPFREQ(my_column, 5, 1000) +FROM my_table; +``` + + + +## STDDEV and VARIANCE {#stddev-variance} + +Standard deviation and variance in a column. Those functions use a [single-pass parallel algorithm](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm), whose result may differ from the more common methods requiring two passes through the data. + +By default, the sample variance and standard deviation are calculated. Several write methods are available: + +* with the `POPULATION` suffix/prefix, for example: `VARIANCE_POPULATION`, `POPULATION_VARIANCE` calculates the variance or standard deviation for the population. +* With the `SAMPLE` suffix/prefix or without a suffix, for example, `VARIANCE_SAMPLE`, `SAMPLE_VARIANCE`, `SAMPLE` calculate sample variance and standard deviation. + +Several abbreviated aliases are also defined, for example, `VARPOP` or `STDDEVSAMP`. + +If all the values passed are `NULL`, it returns `NULL`. + +### Examples + +```yql +SELECT + STDDEV(numeric_column), + VARIANCE(numeric_column) +FROM my_table; +``` + + + +## CORRELATION and COVARIANCE {#correlation-covariance} + +Correlation and covariance between two columns. + +Abbreviated versions are also available: `CORR` or `COVAR`. For covariance, there are also versions with the `SAMPLE`/`POPULATION` suffix that are similar to [VARIANCE](#stddev-variance) above. + +Unlike most other aggregate functions, they don't skip `NULL`, but accept it as 0. + +When you use [aggregation factories](basic.md#aggregationfactory), a `Tuple` containing two values is passed as the first [AGGREGATE_BY](#aggregate-by) argument. + +### Examples + +```yql +SELECT + CORRELATION(numeric_column, another_numeric_column), + COVARIANCE(numeric_column, another_numeric_column) +FROM my_table; +``` + +```yql +$corr_factory = AggregationFactory("CORRELATION"); + +SELECT + AGGREGATE_BY(AsTuple(numeric_column, another_numeric_column), $corr_factory) +FROM my_table; +``` + + + +## PERCENTILE and MEDIAN {#percentile-median} + +Calculating percentiles using the amortized version of the [TDigest](https://github.com/tdunning/t-digest) algorithm. `MEDIAN`: An alias for `PERCENTILE(N, 0.5)`. + +{% note info "Restriction" %} + +The first argument (N) must be a table column name. If you need to bypass this restriction, use a subquery. The restriction is introduced to simplify calculations, since the implementation merges the calls with the same first argument (N) into a single pass. + +{% endnote %} + +```yql +SELECT + MEDIAN(numeric_column), + PERCENTILE(numeric_column, 0.99) +FROM my_table; +``` + + + +## HISTOGRAM {#histogram} + +Plotting an approximate histogram based on a numeric expression with automatic selection of buckets. + +[Auxiliary functions](../udf/list/histogram.md) + +### Basic settings + +You can limit the number of buckets using an optional argument. The default value is 100. Keep in mind that added accuracy costs you more computing resources and may negatively affect the query execution time. In extreme cases, it may affect your query success. + +### Support for weights + +You can specify a "weight" for each value used in the histogram. To do this, pass to the aggregate function the second argument with an expression for calculating the weight. The weight of `1.0` is always used by default. If you use non-standard weights, you may also use the third argument to limit the number of buckets. + +If you pass two arguments, the meaning of the second argument is determined by its type (if it's an integer literal, it limits the number of buckets, otherwise it's used as a weight). + +{% if tech %} + +### Algorithms + +* [Source whitepaper](http://jmlr.org/papers/volume11/ben-haim10a/ben-haim10a.pdf); + +Various modifications of the algorithm are available: + +```yql +AdaptiveDistanceHistogram +AdaptiveWeightHistogram +AdaptiveWardHistogram +BlockWeightHistogram +BlockWardHistogram +``` + +By default, `HISTOGRAM` is a synonym for `AdaptiveWardHistogram`. Both functions are equivalent and interchangeable in all contexts. + +The Distance, Weight, and Ward algorithms differ in the formulas that combine two points into one: + +```c++ + TWeightedValue CalcDistanceQuality(const TWeightedValue& left, const TWeightedValue& right) { + return TWeightedValue(right.first - left.first, left.first); + } + + TWeightedValue CalcWeightQuality(const TWeightedValue& left, const TWeightedValue& right) { + return TWeightedValue(right.second + left.second, left.first); + } + + TWeightedValue CalcWardQuality(const TWeightedValue& left, const TWeightedValue& right) { + const double N1 = left.second; + const double N2 = right.second; + const double mu1 = left.first; + const double mu2 = right.first; + return TWeightedValue(N1 * N2 / (N1 + N2) * (mu1 - mu2) * (mu1 - mu2), left.first); + } +``` + +Difference between Adaptive and Block: + +> Contrary to adaptive histogram, block histogram doesn't rebuild bins after each point is added. Instead, it accumulates points and if the amount of points overflows specified limits, it shrinks all the points at once to produce a histogram. Indeed, there exist two limits and two shrinkage operations: +> +> 1. FastGreedyShrink is fast but coarse. It is used to shrink from upper limit to intermediate limit (override FastGreedyShrink to set specific behaviour). +> 2. SlowShrink is slow, but produces finer histogram. It shrinks from the intermediate limit to the actual number of bins in a manner similar to that in adaptive histogram (set CalcQuality in 34constuctor) +> While FastGreedyShrink is used most of the time, SlowShrink is mostly used for histogram finalization + +{% endif %} + +### If you need an accurate histogram + +1. You can use the aggregate functions described below with fixed bucket grids: [LinearHistogram](#linearhistogram) or [LogarithmicHistogram](#linearhistogram). +2. You can calculate the bucket number for each row and apply to it [GROUP BY](../syntax/group_by.md). + +When you use [aggregation factories](basic.md#aggregationfactory), a `Tuple` containing a value and a weight is passed as the first [AGGREGATE_BY](#aggregate-by) argument. + +### Examples + +```yql +SELECT + HISTOGRAM(numeric_column) +FROM my_table; +``` + +```yql +SELECT + Histogram::Print( + HISTOGRAM(numeric_column, 10), + 50 + ) +FROM my_table; +``` + +```yql +$hist_factory = AggregationFactory("HISTOGRAM"); + +SELECT + AGGREGATE_BY(AsTuple(numeric_column, 1.0), $hist_factory) +FROM my_table; +``` + +## LinearHistogram, LogarithmicHistogram, and LogHistogram {#linearhistogram} + +Plotting a histogram based on an explicitly specified fixed bucket scale. + +Arguments: + +1. Expression used to plot the histogram. All the following arguments are optional. +2. Spacing between the `LinearHistogram` buckets or the logarithm base for `LogarithmicHistogram`/`LogHistogram` (those are aliases). In both cases, the default value is 10. +3. Minimum value. By default, it's minus infinity. +4. Maximum value. By default, it's plus infinity. + +The format of the result is totally similar to [adaptive histograms](#histogram), so you can use the same [set of auxiliary functions](../udf/list/histogram.md). + +If the spread of input values is uncontrollably large, we recommend that you specify the minimum and maximum values to prevent potential failures due to high memory consumption. + +### Examples + +```yql +SELECT + LogarithmicHistogram(numeric_column, 2) +FROM my_table; +``` + + + +## BOOL_AND, BOOL_OR and BOOL_XOR {#bool-and-or-xor} + +### Signature + +```yql +BOOL_AND(Bool?)->Bool? +BOOL_OR(Bool?)->Bool? +BOOL_XOR(Bool?)->Bool? +``` + +Apply the relevant logical operation (`AND`/`OR`/`XOR`) to all values in a Boolean column or expression. + +Unlike most other aggregate functions, these functions **don't skip** `NULL` during aggregation and use the following rules: + +- `true AND null == null` +- `false OR null == null` + +For `BOOL_AND`: + +- If at least one `NULL` value is present, the result is `NULL` regardless of `true` values in the expression. +- If at least one `false` value is present, the result changes to `false` regardless of `NULL` values in the expression. + +For `BOOL_OR`: + +- If at least one `NULL` value is present, the result changes to `NULL` regardless of `false` values in the expression. +- If at least one `true` value is present, the result changes to `true` regardless of `NULL` values in the expression. + +For `BOOL_XOR`: + +- The result is `NULL` if any `NULL` is found. + +Examples of such behavior can be found below. + +To skip `NULL` values during aggregation, use the `MIN`/`MAX` or `BIT_AND`/`BIT_OR`/`BIT_XOR` functions. + +### Examples + +```yql +$data = [ + <|nonNull: true, nonFalse: true, nonTrue: NULL, anyVal: true|>, + <|nonNull: false, nonFalse: NULL, nonTrue: NULL, anyVal: NULL|>, + <|nonNull: false, nonFalse: NULL, nonTrue: false, anyVal: false|>, +]; + +SELECT + BOOL_AND(nonNull) as nonNullAnd, -- false + BOOL_AND(nonFalse) as nonFalseAnd, -- NULL + BOOL_AND(nonTrue) as nonTrueAnd, -- false + BOOL_AND(anyVal) as anyAnd, -- false + BOOL_OR(nonNull) as nonNullOr, -- true + BOOL_OR(nonFalse) as nonFalseOr, -- true + BOOL_OR(nonTrue) as nonTrueOr, -- NULL + BOOL_OR(anyVal) as anyOr, -- true + BOOL_XOR(nonNull) as nonNullXor, -- true + BOOL_XOR(nonFalse) as nonFalseXor, -- NULL + BOOL_XOR(nonTrue) as nonTrueXor, -- NULL + BOOL_XOR(anyVal) as anyXor, -- NULL +FROM AS_TABLE($data); +``` + +## BIT_AND, BIT_OR and BIT_XOR {#bit-and-or-xor} + +Apply the relevant bitwise operation to all values of a numeric column or expression. + +### Examples + +```yql +SELECT + BIT_XOR(unsigned_numeric_value) +FROM my_table; +``` + + + +{% if feature_window_functions %} + + ## SessionStart {#session-start} + +No arguments. It's allowed only if there is [SessionWindow](../syntax/group_by.md#session-window) in [GROUP BY](../syntax/group_by.md) / [PARTITION BY](../syntax/window.md#partition). +Returns the value of the `SessionWindow` key column. If `SessionWindow` has two arguments, it returns the minimum value of the first argument within the group/section. +In the case of the expanded version `SessionWindow`, it returns the value of the second element from the tuple returned by ``, for which the first tuple element is `True`. + + + +{% endif %} + +## AGGREGATE_BY and MULTI_AGGREGATE_BY {#aggregate-by} + +Applying an [aggregation factory](basic.md#aggregationfactory) to all values of a column or expression. The `MULTI_AGGREGATE_BY` function requires that the value of a column or expression has a structure, tuple, or list, and applies the factory to each individual element, placing the result in a container of the same format. If different values of a column or expression contain lists of different length, the resulting list will have the smallest of the source lengths. + +1. Column, `DISTINCT` column or expression. +2. Factory. + +### Examples + +```yql +$count_factory = AggregationFactory("COUNT"); + +SELECT + AGGREGATE_BY(DISTINCT column, $count_factory) as uniq_count +FROM my_table; + +SELECT + MULTI_AGGREGATE_BY(nums, AggregationFactory("count")) as count, + MULTI_AGGREGATE_BY(nums, AggregationFactory("min")) as min, + MULTI_AGGREGATE_BY(nums, AggregationFactory("max")) as max, + MULTI_AGGREGATE_BY(nums, AggregationFactory("avg")) as avg, + MULTI_AGGREGATE_BY(nums, AggregationFactory("percentile", 0.9)) as p90 +FROM my_table; +``` + + diff --git a/ydb/docs/en/core/yql/reference/builtins/basic.md b/ydb/docs/en/core/yql/reference/builtins/basic.md new file mode 100644 index 000000000000..1cf683490feb --- /dev/null +++ b/ydb/docs/en/core/yql/reference/builtins/basic.md @@ -0,0 +1,1336 @@ + +# Basic built-in functions + +Below are the general-purpose functions. For specialized functions, there are separate articles: [aggregate functions](aggregation.md){% if feature_window_functions %}, [window functions](window.md){% endif %}, and functions for [lists](list.md), [dictionaries](dict.md), [structures](struct.md), [data types](types.md){% if feature_codegen %}, and [code generation](codegen.md){% endif %}. + + + +## COALESCE {#coalesce} + +Iterates through the arguments from left to right and returns the first non-empty argument found. To be sure that the result is non-empty (not of an [optional type](../types/optional.md)), the rightmost argument must be of this type (often a literal is used for this). With a single argument, returns this argument unchanged. + +Lets you pass potentially empty values to functions that can't handle them by themselves. + +A short format using the low-priority `??` operator is available (lower than the Boolean operations). You can use the `NVL` alias. + +### Examples + +```yql +SELECT COALESCE( + maybe_empty_column, + "it's empty!" +) FROM my_table; +``` + +```yql +SELECT + maybe_empty_column ?? "it's empty!" +FROM my_table; +``` + +```yql +SELECT NVL( + maybe_empty_column, + "it's empty!" +) FROM my_table; +``` + +All three examples above are equivalent. + + + +## LENGTH {#length} + +Returns the length of the string in bytes. This function is also available under the `LEN` name . + +### Examples + +```yql +SELECT LENGTH("foo"); +``` + +```yql +SELECT LEN("bar"); +``` + +{% note info %} + +To calculate the length of a string in Unicode characters, you can use the function [Unicode::GetLength](../udf/list/unicode.md).

To get the number of elements in the list, use the function [ListLength](list.md#listlength). + +{% endnote %} + + +## SUBSTRING {#substring} + +Returns a substring. + +Required arguments: + +* Source string; +* Position: The offset from the beginning of the string in bytes (integer) or `NULL` meaning "from the beginning". + +Optional arguments: + +* Substring length: The number of bytes starting from the specified position (an integer, or the default `NULL` meaning "up to the end of the source string"). + +Indexing starts from zero. If the specified position and length are beyond the string, returns an empty string. +If the input string is optional, the result is also optional. + +### Examples + +```yql +SELECT SUBSTRING("abcdefg", 3, 1); -- d +``` + +```yql +SELECT SUBSTRING("abcdefg", 3); -- defg +``` + +```yql +SELECT SUBSTRING("abcdefg", NULL, 3); -- abc +``` + + + +## FIND {#find} + +Finding the position of a substring in a string. + +Required arguments: + +* Source string; +* The substring being searched for. + +Optional arguments: + +* A position in bytes to start the search with (an integer or `NULL` by default that means "from the beginning of the source string"). + +Returns the first substring position found or `NULL` (meaning that the desired substring hasn't been found starting from the specified position). + +### Examples + +```yql +SELECT FIND("abcdefg_abcdefg", "abc"); -- 0 +``` + +```yql +SELECT FIND("abcdefg_abcdefg", "abc", 1); -- 8 +``` + +```yql +SELECT FIND("abcdefg_abcdefg", "abc", 9); -- null +``` + +## RFIND {#rfind} + +Reverse finding the position of a substring in a string, from the end to the beginning. + +Required arguments: + +* Source string; +* The substring being searched for. + +Optional arguments: + +* A position in bytes to start the search with (an integer or `NULL` by default, meaning "from the end of the source string"). + +Returns the first substring position found or `NULL` (meaning that the desired substring hasn't been found starting from the specified position). + +### Examples + +```yql +SELECT RFIND("abcdefg_abcdefg", "bcd"); -- 9 +``` + +```yql +SELECT RFIND("abcdefg_abcdefg", "bcd", 8); -- 1 +``` + +```yql +SELECT RFIND("abcdefg_abcdefg", "bcd", 0); -- null +``` + + + +## StartsWith, EndsWith {#starts_ends_with} + +Checking for a prefix or suffix in a string. + +Required arguments: + +* Source string; +* The substring being searched for. + +The arguments can be of the `String` or `Utf8` type and can be optional. + +### Examples + +```yql +SELECT StartsWith("abc_efg", "abc") AND EndsWith("abc_efg", "efg"); -- true +``` + +```yql +SELECT StartsWith("abc_efg", "efg") OR EndsWith("abc_efg", "abc"); -- false +``` + +```yql +SELECT StartsWith("abcd", NULL); -- null +``` + +```yql +SELECT EndsWith(NULL, Utf8("")); -- null +``` + + + +## IF {#if} + +Checks the condition: `IF(condition_expression, then_expression, else_expression)`. + +It's a simplified alternative for [CASE WHEN ... THEN ... ELSE ... END](../syntax/expressions.md#case). + +You may omit the `else_expression` argument. In this case, if the condition is false (`condition_expression` returned `false`), an empty value is returned with the type corresponding to `then_expression` and allowing for `NULL`. Hence, the result will have an [optional data type](../types/optional.md). + +### Examples + +```yql +SELECT + IF(foo > 0, bar, baz) AS bar_or_baz, + IF(foo > 0, foo) AS only_positive_foo +FROM my_table; +``` + + + +## NANVL {#nanvl} + +Replaces the values of `NaN` (not a number) in expressions like `Float`, `Double`, or [Optional](../types/optional.md). + +Arguments: + +1. The expression where you want to make a replacement. +2. The value to replace `NaN`. + +If one of the arguments is `Double`, the result is`Double`, otherwise, it's `Float`. If one of the arguments is `Optional`, then the result is `Optional`. + +### Examples + +```yql +SELECT + NANVL(double_column, 0.0) +FROM my_table; +``` + + + +## Random... {#random} + +Generates a pseudorandom number: + +* `Random()`: A floating point number (Double) from 0 to 1. +* `RandomNumber()`: An integer from the complete Uint64 range. +* `RandomUuid()`: [Uuid version 4](https://tools.ietf.org/html/rfc4122#section-4.4). + +### Signatures + +```yql +Random(T1[, T2, ...])->Double +RandomNumber(T1[, T2, ...])->Uint64 +RandomUuid(T1[, T2, ...])->Uuid +``` + +No arguments are used for random number generation: they are only needed to control the time of the call. A new random number is returned at each call. Therefore: + +{% if ydb_non_deterministic_functions %} + +* If Random is called again within a **same query** and with a same set of arguments does not guarantee getting the same sets of random numbers. The values will be equal if the Random calls fall into the same execution phase. + +{% else %} + +* If Random is called again within a **same query** and with a same set of arguments, the same set of random numbers is returned. Keep in mind that we mean the arguments themselves (i.e., the text between parentheses) rather than their values. + +{% endif %} + +* Calling of Random with the same set of arguments in **different queries** returns different sets of random numbers. + +{% note warning %} + +If Random is used in [named expressions](../syntax/expressions.md#named-nodes), its one-time calculation is not guaranteed. Depending on the optimizers and runtime environment, it can be counted both once and multiple times. To make sure it's only counted once, materialize a named expression into a table. + +{% endnote %} + +Use cases: + +* `SELECT RANDOM(1);`: Get one random value for the entire query and use it multiple times (to get multiple random values, you can pass various constants of any type). +* `SELECT RANDOM(1) FROM table;`: The same random number for each row in the table. +* `SELECT RANDOM(1), RANDOM(2) FROM table;`: Two random numbers for each row of the table, all the numbers in each of the columns are the same. +* `SELECT RANDOM(some_column) FROM table;`: Different random numbers for each row in the table. +* `SELECT RANDOM(some_column), RANDOM(some_column) FROM table;`: Different random numbers for each row of the table, but two identical numbers within the same row. +* `SELECT RANDOM(some_column), RANDOM(some_column + 1) FROM table;` or `SELECT RANDOM(some_column), RANDOM(other_column) FROM table;`: Two columns, with different numbers in both. + +### Examples + +```yql +SELECT + Random(key) -- [0, 1) +FROM my_table; +``` + +```yql +SELECT + RandomNumber(key) -- [0, Max) +FROM my_table; +``` + +```yql +SELECT + RandomUuid(key) -- Uuid version 4 +FROM my_table; +``` + +```yql +SELECT + RANDOM(column) AS rand1, + RANDOM(column) AS rand2, -- same as rand1 + RANDOM(column, 1) AS randAnd1, -- different from rand1/2 + RANDOM(column, 2) AS randAnd2 -- different from randAnd1 +FROM my_table; +``` + + +## CurrentUtc... {#current-utc} + +`CurrentUtcDate()`, `CurrentUtcDatetime()` and `CurrentUtcTimestamp()`: Getting the current date and/or time in UTC. The result data type is specified at the end of the function name. + +The arguments are optional and work same as [RANDOM](#random). + +### Examples + +```yql +SELECT CurrentUtcDate(); +``` + +```yql +SELECT CurrentUtcTimestamp(TableRow()) FROM my_table; +``` + + + +## CurrentTz... {#current-tz} + +`CurrentTzDate()`, `CurrentTzDatetime()`, and `CurrentTzTimestamp()`: Get the current date and/or time in the [IANA time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) specified in the first argument. The result data type is specified at the end of the function name. + +The arguments that follow are optional and work same as [RANDOM](#random). + +### Examples + +```yql +SELECT CurrentTzDate("Europe/Moscow"); +``` + +```yql +SELECT CurrentTzTimestamp("Europe/Moscow", TableRow()) FROM my_table; +``` + +## AddTimezone + +Adding the time zone information to the date/time in UTC. In the result of `SELECT` or after `CAST`, a `String` will be subject to the time zone rules used to calculate the time offset. + +Arguments: + +1. Date: the type is `Date`/`Datetime`/`Timestamp`. +2. [The IANA name of the time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + +Result type: `TzDate`/`TzDatetime`/`TzTimestamp`, depending on the input data type. + +### Examples + +```yql +SELECT AddTimezone(Datetime("2018-02-01T12:00:00Z"), "Europe/Moscow"); +``` + +## RemoveTimezone + +Removing the time zone data and converting the value to date/time in UTC. + +Arguments: + +1. Date: the type is `TzDate`/`TzDatetime`/`TzTimestamp`. + +Result type: `Date`/`Datetime`/`Timestamp`, depending on the input data type. + +### Examples + +```yql +SELECT RemoveTimezone(TzDatetime("2018-02-01T12:00:00,Europe/Moscow")); +``` + + + +## Version {#version} + +`Version()` returns a string describing the current version of the node processing the request. In some cases, such as during rolling upgrades, it might return different strings depending on which node processes the request. It does not accept any arguments. + +### Examples + +```yql +SELECT Version(); +``` + + + +## MAX_OF, MIN_OF, GREATEST, and LEAST {#max-min} + +Returns the minimum or maximum among N arguments. Those functions let you replace the SQL standard statement `CASE WHEN a < b THEN a ELSE b END` that would be too sophisticated for N more than two. + +The argument types must be mutually castable and accept `NULL`. + +`GREATEST` is a synonym for `MAX_OF` and `LEAST` is a synonym for `MIN_OF`. + +### Examples + +```yql +SELECT MIN_OF(1, 2, 3); +``` + + + +## AsTuple, AsStruct, AsList, AsDict, AsSet, AsListStrict, AsDictStrict and AsSetStrict {#as-container} + +Creates containers of the applicable types. For container literals, [operator notation](#containerliteral) is also supported. + +Specifics: + +* The container elements are passed in arguments. Hence, the number of elements in the resulting container is equal to the number of arguments passed, except when the dictionary keys repeat. +* `AsTuple` and `AsStruct` can be called without arguments, and also the arguments can have different types. +* The field names in `AsStruct` are set using `AsStruct(field_value AS field_name)`. +* Creating a list requires at least one argument if you need to output the element types. To create an empty list with the given type of elements, use the function [ListCreate](list.md#listcreate). You can create an empty list as an `AsList()` call without arguments. In this case, this expression will have the `EmptyList` type. +* Creating a dictionary requires at least one argument if you need to output the element types. To create an empty dictionary with the given type of elements, use the function [DictCreate](dict.md#dictcreate). You can create an empty dictionary as an `AsDict()` call without arguments, in this case, this expression will have the `EmptyDict` type. +* Creating a set requires at least one argument if you need to output element types. To create an empty set with the given type of elements, use the function [SetCreate](dict.md#setcreate). You can create an empty set as an `AsSet()` call without arguments, in this case, this expression will have the `EmptySet` type. +* `AsList` outputs the common type of elements in the list. A type error is raised in the case of incompatible types. +* `AsDict` separately outputs the common types for keys and values. A type error is raised in the case of incompatible types. +* `AsSet` outputs common types for keys. A type error is raised in the case of incompatible types. +* `AsListStrict`, `AsDictStrict`, `AsSetStrict` require the same type for their arguments. +* `AsDict` and `AsDictStrict` expect `Tuple` of two elements as arguments (key and value, respectively). If the keys repeat, only the value for the first key remains in the dictionary. +* `AsSet` and `AsSetStrict` expect keys as arguments. + +### Examples + +```yql +SELECT + AsTuple(1, 2, "3") AS `tuple`, + AsStruct( + 1 AS a, + 2 AS b, + "3" AS c + ) AS `struct`, + AsList(1, 2, 3) AS `list`, + AsDict( + AsTuple("a", 1), + AsTuple("b", 2), + AsTuple("c", 3) + ) AS `dict`, + AsSet(1, 2, 3) AS `set` +``` + + + +## Container literals {#containerliteral} + +Some containers support operator notation for their literal values: + +* Tuple: `(value1, value2...)`; +* Structure: `<|name1: value1, name2: value2...|>`; +* List: `[value1, value2,...]`; +* Dictionary: `{key1: value1, key2: value2...}`; +* Set: `{key1, key2...}`. + +In every case, you can use an insignificant trailing comma. For a tuple with one element, this comma is required: `(value1,)`. +For field names in the structure literal, you can use an expression that can be calculated at evaluation time, for example, string literals or identifiers (including those enclosed in backticks). + +For nested lists, use [AsList](#as-container), for nested dictionaries, use [AsDict](#as-container), for nested sets, use [AsSet](#as-container), for nested tuples, use [AsTuple](#as-container), for nested structures, use [AsStruct](#as-container). + +### Examples + +```yql +$name = "computed " || "member name"; +SELECT + (1, 2, "3") AS `tuple`, + <| + `complex member name`: 2.3, + b: 2, + $name: "3", + "inline " || "computed member name": false + |> AS `struct`, + [1, 2, 3] AS `list`, + { + "a": 1, + "b": 2, + "c": 3, + } AS `dict`, + {1, 2, 3} AS `set` +``` + + + +## Variant {#variant} + +`Variant()` creates a variant value over a tuple or structure. + +Arguments: + +* Value +* String with a field name or tuple index +* Variant type + +### Example + +```yql +$var_type = Variant; + +SELECT + Variant(6, "foo", $var_type) as Variant1Value, + Variant(false, "bar", $var_type) as Variant2Value; +``` + +## AsVariant {#asvariant} + +`AsVariant()` creates a value of a [variant over a structure](../types/containers.md) including one field. This value can be implicitly converted to any variant over a structure that has a matching data type for this field name and might include more fields with other names. + +Arguments: + +* Value +* A string with the field name + +### Example + +```yql +SELECT + AsVariant(6, "foo") as VariantValue +``` + +## Visit, VisitOrDefault {#visit} + +Processes the possible values of a variant over a structure or tuple using the provided handler functions for each field/element of the variant. + +### Signature + +```yql +Visit(Variant, K1->R AS key1, K2->R AS key2, ...)->R +Visit(Variant, K1->R, K2->R, ...)->R + +VisitOrDefault(Variant{Flags:AutoMap}, R, [K1->R, [K2->R, ...]])->R +VisitOrDefault(Variant{Flags:AutoMap}, R, [K1->R AS key1, [K2->R AS key2, ...]])->R +``` + +### Arguments + +* For a variant over structure: accepts the variant as the positional argument and named arguments (handlers) corresponding to each field of the variant. +* For a variant over tuple: accepts the variant and handlers for each element of the variant as positional arguments. +* `VisitOrDefault` includes an additional positional argument (on the second place) for the default value, enabling the omission of certain handlers. + +### Example + +```yql +$vartype = Variant; +$handle_num = ($x) -> { return 2 * $x; }; +$handle_flag = ($x) -> { return If($x, 200, 10); }; +$handle_str = ($x) -> { return Unwrap(CAST(LENGTH($x) AS Int32)); }; + +$visitor = ($var) -> { return Visit($var, $handle_num AS num, $handle_flag AS flag, $handle_str AS str); }; +SELECT + $visitor(Variant(5, "num", $vartype)), -- 10 + $visitor(Just(Variant(True, "flag", $vartype))), -- Just(200) + $visitor(Just(Variant("somestr", "str", $vartype))), -- Just(7) + $visitor(Nothing(OptionalType($vartype))), -- Nothing(Optional) + $visitor(NULL) -- NULL +; +``` + +## VariantItem {#variantitem} + +Returns the value of a homogeneous variant (i.e., a variant containing fields/elements of the same type). + +### Signature + +```yql +VariantItem(Variant{Flags:AutoMap})->K +VariantItem(Variant{Flags:AutoMap})->K +``` + +### Example + +```yql +$vartype1 = Variant; +SELECT + VariantItem(Variant(7, "num2", $vartype1)), -- 7 + VariantItem(Just(Variant(5, "num1", $vartype1))), -- Just(5) + VariantItem(Nothing(OptionalType($vartype1))), -- Nothing(Optional) + VariantItem(NULL) -- NULL +; +``` + +## Way {#way} + +Returns an active field (active index) of a variant over a struct (tuple). + +### Signature + +```yql +Way(Variant{Flags:AutoMap})->Utf8 +Way(Variant{Flags:AutoMap})->Uint32 +``` + +### Example + +```yql +$vr = Variant(1, "0", Variant); +$vrs = Variant(1, "a", Variant); +SELECT Way($vr); -- 0 +SELECT Way($vrs); -- "a" +``` + +## DynamicVariant {#dynamic_variant} + +Creates a homogeneous variant instance (i.e. containing fields/elements of the same type), where the variant index or field can be set dynamically. If the index or field name does not exist, `NULL` will be returned. +The inverse function is [VariantItem](#variantitem). + +### Signature + +```yql +DynamicVariant(item:T,index:Uint32?,Variant)->Optional> +DynamicVariant(item:T,index:Utf8?,Variant)->Optional> +``` + +### Example + +```yql +$dt = Int32; +$tvt = Variant<$dt,$dt>; +SELECT ListMap([(10,0u),(20,2u),(30,NULL)],($x)->(DynamicVariant($x.0,$x.1,$tvt))); -- [0: 10,NULL,NULL] + +$dt = Int32; +$svt = Variant; +SELECT ListMap([(10,'x'u),(20,'z'u),(30,NULL)],($x)->(DynamicVariant($x.0,$x.1,$svt))); -- [x: 10,NULL,NULL] + +``` + +## Enum {#enum} + +`Enum()` creates an enumeration value. + +Arguments: + +* A string with the field name +* Enumeration type + +### Example + +```yql +$enum_type = Enum; +SELECT + Enum("Foo", $enum_type) as Enum1Value, + Enum("Bar", $enum_type) as Enum2Value; +``` + +## AsEnum {#asenum} + +`AsEnum()` creates a value of [enumeration](../types/containers.md) including one element. This value can be implicitly cast to any enumeration containing such a name. + +Arguments: + +* A string with the name of an enumeration item + +### Example + +```yql +SELECT + AsEnum("Foo"); +``` + + + +## AsTagged, Untag {#as-tagged} + +Wraps the value in the [Tagged data type](../types/special.md) with the specified tag, preserving the physical data type. `Untag`: The reverse operation. + +Required arguments: + +1. Value of any type. +2. Tag name. + +Returns a copy of the value from the first argument with the specified tag in the data type. + +Examples of use cases: + +* Returns to the client's web interface the media files from BASE64-encoded strings{% if feature_webui %}. Tag support in the YQL Web UI [is described here](../interfaces/web_tagged.md){% endif %}. +{% if feature_mapreduce %}* Prevent passing of invalid values at the boundaries of UDF calls.{% endif %} +* Additional refinements at the level of returned columns types. + + + +{% if feature_bulk_tables %} + +## TablePath {#tablepath} + +Access to the current table name, which might be needed when you use [CONCAT](../syntax/select/concat.md#concat), [RANGE](../syntax/select/concat.md#range), and other related functions. + +No arguments. Returns a string with the full path or an empty string and warning when used in an unsupported context (for example, when working with a subquery or a range of 1000+ tables). + +{% note info %} + +The [TablePath](#tablepath), [TableName](#tablename), and [TableRecordIndex](#tablerecordindex) functions don't support temporary and anonymous tables (they return an empty string or 0 for [TableRecordIndex](#tablerecordindex)). +These functions are calculated when [executing](../syntax/select/index.md#selectexec) projections in `SELECT`, and by that time the current table may already be temporary. +To avoid such a situation, create a subquery for calculating these functions, as shown in the second example below. + +{% endnote %} + +### Examples + +```yql +SELECT TablePath() FROM CONCAT(table_a, table_b); +``` + +```yql +SELECT key, tpath_ AS path FROM (SELECT a.*, TablePath() AS tpath_ FROM RANGE(`my_folder`) AS a) +WHERE key IN $subquery; +``` + +## TableName {#tablename} + +Get the table name based on the table path. You can obtain the path using the [TablePath](#tablepath) function or as the `Path` column when using the table function [FOLDER](../syntax/select/folder.md). + +Optional arguments: + +* Path to the table, `TablePath()` is used by default (see also its limitations). +* Specifying the system ("yt") whose rules are used to determine the table name. You need to specify the system only if [USE](../syntax/use.md) doesn't specify the current cluster. + +### Examples + +```yql +USE cluster; +SELECT TableName() FROM CONCAT(table_a, table_b); +``` + +```yql +SELECT TableName(Path, "yt") FROM cluster.FOLDER(folder_name); +``` + +## TableRecordIndex {#tablerecordindex} + +Access to the current sequence number of a row in the physical source table, **starting from 1** (depends on the storage implementation). + +No arguments. When used in combination with [CONCAT](../syntax/select/concat.md#concat), [RANGE](../syntax/select/concat.md#range) and other similar mechanisms, numbering restarts for each input table. If used in an incorrect context, it returns 0. + +### Example + +```yql +SELECT TableRecordIndex() FROM my_table; +``` + + + +{% endif %} + +## TableRow{% if feature_join %}, JoinTableRow{% endif %} {#tablerow} + +Getting the entire table row as a structure. No arguments{% if feature_join %}. `JoinTableRow` in case of `JOIN` always returns a structure with table prefixes{% endif %}. + +### Example + +```yql +SELECT TableRow() FROM my_table; +``` + + + +{% if feature_mapreduce %} + +## FileContent and FilePath {#file-content-path} + +Both the [console](../interfaces/cli.md) and [web](../interfaces/web.md) interfaces let you "attach" arbitrary named files to your query. With these functions, you can use the name of the attached file to get its contents or the path in the sandbox, and then use it as you like in the query. + +The `FileContent` and `FilePath` argument is a string with an alias. + +### Examples + +```yql +SELECT "Content of " + || FilePath("my_file.txt") + || ":\n" + || FileContent("my_file.txt"); +``` + +## FolderPath {#folderpath} + +Getting the path to the root of a directory with several "attached" files with the common prefix specified. + +The argument is a string with a prefix among aliases. + +See also [PRAGMA File](../syntax/pragma.md#file) and [PRAGMA Folder](../syntax/pragma.md#folder). + +### Examples + +```yql +PRAGMA File("foo/1.txt", "http://url/to/somewhere"); +PRAGMA File("foo/2.txt", "http://url/to/somewhere/else"); +PRAGMA File("bar/3.txt", "http://url/to/some/other/place"); + +SELECT FolderPath("foo"); -- The directory at the return path will + -- include the files 1.txt and 2.txt downloaded from the above links +``` + +## ParseFile + +Get a list of values from the attached text file. It can be combined with [IN](../syntax/expressions.md#in), attaching the file by URL (see the instruction for attaching files in the {% if feature_webui %}[web interface](../interfaces/web.md#attach) and the {% endif %} [client](../interfaces/cli.md#attach)). + +Only one file format is supported: one value per line.{% if feature_udf_noncpp %} For something more sophisticated, for now you have to write a small UDF in [Python](../udf/python.md) or [JavaScript](../udf/javascript.md). {% endif %} + +Two required arguments: + +1. List cell type: only strings and numeric types are supported. +2. The name of the attached file. + +{% note info %} + +The return value is a lazy list. For repeat use, wrap it in the function [ListCollect](list.md#listcollect) + +{% endnote %} + +### Examples + +```yql +SELECT ListLength(ParseFile("String", "my_file.txt")); +``` + +```yql +SELECT * FROM my_table +WHERE int_column IN ParseFile("Int64", "my_file.txt"); +``` + + + +## WeakField {#weakfield} + +Fetches a table column from a strong schema, if it is in a strong schema, or from the `_other` and `_rest` fields. If the value is missing, it returns `NULL`. + +Syntax: `WeakField([.], [, ])`. + +The default value is used only if the column is missing in the data schema. To use the default value in any case, use [COALESCE](#coalesce). + +### Examples + +```yql +SELECT + WeakField(my_column, String, "no value"), + WeakField(my_table.other_column, Int64) +FROM my_table; +``` + + + +{% endif %} + +## Ensure... {#ensure} + +Checking for the user conditions: + +* `Ensure()`: Checking whether the predicate is true at query execution. +* `EnsureType()`: Checking that the expression type exactly matches the specified type. +* `EnsureConvertibleTo()`: A soft check of the expression type (with the same rules as for implicit type conversion). + +If the check fails, the entire query fails. + +Arguments: + +1. An expression that will result from a function call if the check is successful. It's also checked for the data type in the corresponding functions. +2. Ensure uses a Boolean predicate that is checked for being `true`. The other functions use the data type that can be obtained using the [relevant functions](types.md), or a string literal with a [text description of the type](../types/type_string.md). +3. An optional string with an error comment to be included in the overall error message when the query is complete. The data itself can't be used for type checks, since the data check is performed at query validation (or can be an arbitrary expression in the case of Ensure). + +{% if backend_name != "YDB" %} + +To check the conditions based on the final calculation result, it's convenient to combine Ensure with [DISCARD SELECT](../syntax/discard.md). + +{% endif %} + +### Examples + +```yql +SELECT Ensure( + value, + value < 100, + "value out or range" +) AS value FROM my_table; +``` + +```yql +SELECT EnsureType( + value, + TypeOf(other_value), + "expected value and other_value to be of same type" +) AS value FROM my_table; +``` + +```yql +SELECT EnsureConvertibleTo( + value, + Double?, + "expected value to be numeric" +) AS value FROM my_table; +``` + + + +{% if feature_codegen %} + +## EvaluateExpr, EvaluateAtom {#evaluate_expr_atom} + +Evaluate an expression before the start of the main calculation and input its result to the query as a literal (constant). In many contexts, where only a constant would be expected in standard SQL (for example, in table names, in the number of rows in [LIMIT](../syntax/select/limit_offset.md), and so on), this functionality is implicitly enabled automatically. + +EvaluateExpr can be used where the grammar already expects an expression. For example, you can use it to: + +* Round the current time to days, weeks, or months and insert it into the query to ensure correct [query caching](../syntax/pragma.md#yt.querycachemode), although usually when [functions are used to get the current time](#current-utc), query caching is completely disabled. +* Run a heavy calculation with a small result once per query instead of once per job. + +{% if backend_name == "YT" %} + +EvaluateAtom lets you dynamically create an [atom](../types/special.md), but since atoms are mainly controlled from a lower [s-expressions](/docs/s_expressions/functions) level, it's generally not recommended to use this function directly. + +{% endif %} + +The only argument for both functions is the expression for calculation and substitution. + +Restrictions: + +* The expression must not trigger MapReduce operations. +* This functionality is fully locked in YQL over YDB. + +### Examples + +```yql +$now = CurrentUtcDate(); +SELECT EvaluateExpr( + DateTime::MakeDate(DateTime::StartOfWeek($now) + ) +); +``` + + + +{% endif %} + +## Literals of primitive types {#data-type-literals} + +For primitive types, you can create literals based on string literals. + +### Syntax + +`( [, ] )` + +Unlike `CAST("myString" AS MyType)`: + +* The check for literal's castability to the desired type occurs at validation. +* The result is non-optional. + +For the data types `Date`, `Datetime`, `Timestamp`, and `Interval`, literals are supported only in the format corresponding to [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). `Interval` has the following differences from the standard: + +* It supports the negative sign for shifts to the past. +* Microseconds can be expressed as fractional parts of seconds. +* You can't use units of measurement exceeding one week. +* The options with the beginning/end of the interval and with repetitions, are not supported. + +For the data types `TzDate`, `TzDatetime`, `TzTimestamp`, literals are also set in the format meeting [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601), but instead of the optional Z suffix, they specify the [IANA name of the time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones), separated by comma (for example, GMT or Europe/Moscow). + +{% include [decimal args](../_includes/decimal_args.md) %} + +### Examples + +```yql +SELECT + Bool("true"), + Uint8("0"), + Int32("-1"), + Uint32("2"), + Int64("-3"), + Uint64("4"), + Float("-5"), + Double("6"), + Decimal("1.23", 5, 2), -- up to 5 decimal digits, with 2 after the decimal point + String("foo"), + Utf8("Hello"), + Yson("[3;%false]"), + Json(@@{"a":1,"b":null}@@), + Date("2017-11-27"), + Datetime("2017-11-27T13:24:00Z"), + Timestamp("2017-11-27T13:24:00.123456Z"), + Interval("P1DT2H3M4.567890S"), + TzDate("2017-11-27,Europe/Moscow"), + TzDatetime("2017-11-27T13:24:00,America/Los_Angeles"), + TzTimestamp("2017-11-27T13:24:00.123456,GMT"), + Uuid("f9d5cc3f-f1dc-4d9c-b97e-766e57ca4ccb"); +``` + + + +{% if feature_webui %} + +## Access to the metadata of the current operation {#metadata} + +When you run YQL operations via the web interface or HTTP API, you get access to the following data: + +* `CurrentOperationId()`: The private ID of the operation. +* `CurrentOperationSharedId()`: The public ID of the operation. +* `CurrentAuthenticatedUser()`: The username of the current user. + +No arguments. + +If this data is missing, for example, when you run operations in the embedded mode, the functions return an empty string. + +### Examples + +```yql +SELECT + CurrentOperationId(), + CurrentOperationSharedId(), + CurrentAuthenticatedUser(); +``` + + + +{% endif %} + +## ToBytes and FromBytes {#to-from-bytes} + +Conversion of [primitive data types](../types/primitive.md) to a string with their binary representation and back. Numbers are represented in the [little endian](https://en.wikipedia.org/wiki/Endianness#Little-endian) format. + +### Examples + +```yql +SELECT + ToBytes(123), -- "\u0001\u0000\u0000\u0000" + FromBytes( + "\xd2\x02\x96\x49\x00\x00\x00\x00", + Uint64 + ); -- 1234567890ul +``` + + + +## ByteAt {#byteat} + +Getting the byte value inside a string at an index counted from the beginning of the string. If an invalid index is specified, `NULL` is returned. + +Arguments: + +1. String: `String` or `Utf8`. +2. Index: `Uint32`. + +### Examples + +```yql +SELECT + ByteAt("foo", 0), -- 102 + ByteAt("foo", 1), -- 111 + ByteAt("foo", 9); -- NULL +``` + + + +## ...Bit {#bitops} + +`TestBit()`, `ClearBit()`, `SetBit()` and `FlipBit()`: Test, clear, set, or flip a bit in an unsigned number using the specified bit sequence number. + +Arguments: + +1. An unsigned number that's subject to the operation. TestBit is also implemented for strings. +2. Number of the bit. + +TestBit returns `true/false`. The other functions return a copy of their first argument with the corresponding conversion. + +### Examples + +```yql +SELECT + TestBit(1u, 0), -- true + SetBit(8u, 0); -- 9 +``` + + + +## Abs {#abs} + +The absolute value of the number. + +### Examples + +```yql +SELECT Abs(-123); -- 123 +``` + + + +## Just {#optional-ops} + +`Just()`: Change the value's data type to [optional](../types/optional.md) from the current data type (i.e.,`T` is converted to `T?`). + +The reverse operation is [Unwrap](#optional-ops). + +### Examples + +```yql +SELECT + Just("my_string"); -- String? +``` + +## Unwrap {#unwrap} + +`Unwrap()`: Converting the [optional](../types/optional.md) value of the data type to the relevant non-optional type, raising a runtime error if the data is `NULL`. This means that `T?` becomes `T`. + +If the value isn't [optional](../types/optional.md), then the function returns its first argument unchanged. + +Arguments: + +1. Value to be converted. +2. An optional string with a comment for the error text. + +Reverse operation is [Just](#optional-ops). + +### Examples + +```yql +$value = Just("value"); + +SELECT Unwrap($value, "Unexpected NULL for $value"); +``` + +## Nothing {#nothing} + +`Nothing()`: Create an empty value for the specified [Optional](../types/optional.md) data type. + +### Examples + +```yql +SELECT + Nothing(String?); -- an empty (NULL) value with the String? type +``` + +[Learn more about ParseType and other functions for data types](types.md). + + + +## Callable {#callable} + +Create a callable value with the specified signature from a lambda function. It's usually used to put callable values into containers. + +Arguments: + +1. Type. +2. Lambda function. + +### Examples + +```yql +$lambda = ($x) -> { + RETURN CAST($x as String) +}; + +$callables = AsTuple( + Callable(Callable<(Int32)->String>, $lambda), + Callable(Callable<(Bool)->String>, $lambda), +); + +SELECT $callables.0(10), $callables.1(true); +``` + + + +## Pickle, Unpickle {#pickle} + +`Pickle()` and `StablePickle()` serialize an arbitrary object into a sequence of bytes, if possible. Typical non-serializable objects are Callable and Resource. The serialization format is not versioned and can be used within a single query. For the Dict type, the StablePickle function pre-sorts the keys, and for Pickle, the order of dictionary elements in the serialized representation isn't defined. + +`Unpickle()` is the inverse operation (deserialization), where with the first argument being the data type of the result and the second argument is the string with the result of `Pickle()` or `StablePickle()`. + +### Examples + +```yql +SELECT * +FROM my_table +WHERE Digest::MurMurHash32( + Pickle(TableRow()) + ) %10 ==0; -- actually, it is better to use TABLESAMPLE + +$buf = Pickle(123); +SELECT Unpickle(Int32, $buf); +``` + + + +## StaticMap + +Transforms a structure or tuple by applying a lambda function to each item. + +Arguments: + +* Structure or tuple. +* Lambda for processing items. + +Result: a structure or tuple with the same number and naming of items as in the first argument, and with item data types determined by lambda results. + +### Examples + +```yql +SELECT * +FROM ( + SELECT + StaticMap(TableRow(), ($item) -> { + return CAST($item AS String); + }) + FROM my_table +) FLATTEN COLUMNS; -- converting all columns to rows +``` + + + +## StaticZip + +Merges structures or tuples element-by-element. All arguments (one or more) must be either structures with the same set of fields or tuples of the same length. +The result will be a structure or tuple, respectively. +Each item of the result is a tuple comprised of items taken from arguments. + +### Examples + +```yql +$one = <|k1:1, k2:2.0|>; +$two = <|k1:3.0, k2:4|>; + +-- Adding two structures item-by-item +SELECT StaticMap(StaticZip($one, $two), ($tuple)->($tuple.0 + $tuple.1)) AS sum; +``` + + + +## StaticFold, StaticFold1 {#staticfold} + +```yql +StaticFold(obj:Struct/Tuple, initVal, updateLambda) +StaticFold1(obj:Struct/Tuple, initLambda, updateLambda) +``` + +Left fold over struct/tuple elements. +The folding of tuples is done in order from the element with the lower index to the element with the larger one; for structures, the order is not guaranteed. + +- `obj` - object to fold +- `initVal` - _(for StaticFold)_ initial fold state +- `initLambda` - _(for StaticFold1)_ lambda that produces initial fold state from the first element +- `updateLambda` - lambda that produces the new state (arguments are the next element and the previous state) + + +`StaticFold(<|key_1:$el_1, key_2:$el_2, ..., key_n:$el_n|>, $init, $f)` transforms into: + +```yql +$f($el_n, ...$f($el_2, $f($init, el_1))...) +``` + +`StaticFold1(<|key_1:$el_1, key_2:$el_2, ..., key_n:$el_n|>, $f0, $f)`: + +```yql +$f($el_n, ...$f($el_2, $f($f0($init), el_1))...) +``` + +`StaticFold1(<||>, $f0, $f)` returns `NULL`. + +Works with tuples in the same way. + + +## AggregationFactory {#aggregationfactory} + +Create a factory for [aggregation functions](aggregation.md) to separately describe the methods of aggregation and data types subject to aggregation. + +Arguments: + +1. A string in double quotes with the name of an aggregate function, for example ["MIN"](aggregation.md#min). +2. Optional parameters of the aggregate function that are data-independent. For example, the percentile value in [PERCENTILE](aggregation.md#percentile). + +The resulting factory can be used as the second parameter of the function [AGGREGATE_BY](aggregation.md#aggregate-by). +If the aggregate function is applied to two columns instead of one, as, for example, [MIN_BY](aggregation.md#minby), then in [AGGREGATE_BY](aggregation.md#aggregate-by), the first argument passes a `Tuple` of two values. See more details in the description of the applicable aggregate function. + +### Examples + +```yql +$factory = AggregationFactory("MIN"); +SELECT + AGGREGATE_BY (value, $factory) AS min_value -- apply the MIN aggregation to the "value" column +FROM my_table; +``` + +## AggregateTransformInput {#aggregatetransform} + +`AggregateTransformInput()` converts an [aggregation factory](aggregation.md), for example, obtained using the [AggregationFactory](#aggregationfactory) function, to other factory, in which the specified transformation of input items is performed before starting aggregation. + +Arguments: + +1. Aggregation factory. +2. A lambda function with one argument that converts an input item. + +### Examples + +```yql +$f = AggregationFactory("sum"); +$g = AggregateTransformInput($f, ($x) -> (cast($x as Int32))); +$h = AggregateTransformInput($f, ($x) -> ($x * 2)); +SELECT ListAggregate([1,2,3], $f); -- 6 +SELECT ListAggregate(["1","2","3"], $g); -- 6 +SELECT ListAggregate([1,2,3], $h); -- 12 +``` + +## AggregateTransformOutput {#aggregatetransformoutput} + +`AggregateTransformOutput()` converts an [aggregation factory](aggregation.md), for example, obtained using the [AggregationFactory](#aggregationfactory) function, to other factory, in which the specified transformation of the result is performed after ending aggregation. + +Arguments: + +1. Aggregation factory. +2. A lambda function with one argument that converts the result. + +### Examples + +```yql +$f = AggregationFactory("sum"); +$g = AggregateTransformOutput($f, ($x) -> ($x * 2)); +SELECT ListAggregate([1,2,3], $f); -- 6 +SELECT ListAggregate([1,2,3], $g); -- 12 +``` + +## AggregateFlatten {#aggregateflatten} + +Adapts a factory for [aggregation functions](aggregation.md), for example, obtained using the [AggregationFactory](#aggregationfactory) function in a way that allows aggregation of list input items. This operation is similar to [FLATTEN LIST BY](../syntax/flatten.md): Each list item is aggregated. + +Arguments: + +1. Aggregation factory. + +### Examples + +```yql +$i = AggregationFactory("AGGREGATE_LIST_DISTINCT"); +$j = AggregateFlatten($i); +SELECT AggregateBy(x, $j) from ( + select [1,2] as x + union all + select [2,3] as x +); -- [1, 2, 3] +``` + + + +{% if tech %} + +## YQL::, s-expressions {#s-expressions} + +For the full list of internal YQL functions, see the [documentation for s-expressions](/docs/s_expressions/functions), an alternative low-level YQL syntax. Any of the functions listed there can also be called from the SQL syntax by adding the `YQL::` prefix to its name. However, we don't recommend doing this, because this mechanism is primarily intended to temporarily bypass possible issues and for internal testing purposes. + +If the function is available in SQL syntax without the `YQL::` prefix, then its behavior may differ from the same-name function from the s-expressions documentation, if any. + + + +{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/codegen.md b/ydb/docs/en/core/yql/reference/builtins/codegen.md similarity index 83% rename from ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/codegen.md rename to ydb/docs/en/core/yql/reference/builtins/codegen.md index 44e952910c49..2728742947aa 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/codegen.md +++ b/ydb/docs/en/core/yql/reference/builtins/codegen.md @@ -1,6 +1,6 @@ # Functions for code generation -When running calculations, you can generate the code including [S-expressions](/docs/s_expressions) nodes. This uses a mechanism for packing the code in the [resource](../../types/special.md). After building the code, you can insert it into the main program using the [EvaluateCode](#evaluatecode) function. For debugging purposes, you can convert the code to a string using the [FormatCode](#formatcode) function. +When running calculations, you can generate the code including [S-expressions](/docs/s_expressions) nodes. This uses a mechanism for packing the code in the [resource](../types/special.md). After building the code, you can insert it into the main program using the [EvaluateCode](#evaluatecode) function. For debugging purposes, you can convert the code to a string using the [FormatCode](#formatcode) function. Possible node types in S-expressions that can be used for code generation: @@ -112,8 +112,8 @@ SELECT FormatCode(FuncCode( You can build a code node with the `lambda function declaration` type from: -* [a Lambda function](../../syntax/expressions.md#lambda), if you know the number of arguments in advance. In this case, the nodes of the `argument` type will be passed as arguments to this lambda function. -* The number of arguments and a [lambda function](../../syntax/expressions.md#lambda) with one argument. In this case, a list of nodes of the `argument`type will be passed as an argument to this lambda function. +* [a Lambda function](../syntax/expressions.md#lambda), if you know the number of arguments in advance. In this case, the nodes of the `argument` type will be passed as arguments to this lambda function. +* The number of arguments and a [lambda function](../syntax/expressions.md#lambda) with one argument. In this case, a list of nodes of the `argument`type will be passed as an argument to this lambda function. ### Examples @@ -163,7 +163,7 @@ SELECT $add3(1); -- 4 ## QuoteCode -Substituting into the main program the code node that represents an expression or a [lambda function](../../syntax/expressions.md#lambda) passed in the argument. If free arguments of lambda functions were found during the substitution, they are calculated and substituted into the code as in the [ReprCode](#reprcode) function. +Substituting into the main program the code node that represents an expression or a [lambda function](../syntax/expressions.md#lambda) passed in the argument. If free arguments of lambda functions were found during the substitution, they are calculated and substituted into the code as in the [ReprCode](#reprcode) function. ### Examples diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/dict.md b/ydb/docs/en/core/yql/reference/builtins/dict.md similarity index 87% rename from ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/dict.md rename to ydb/docs/en/core/yql/reference/builtins/dict.md index 0e1bdfab5676..d09bbfadd4af 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/dict.md +++ b/ydb/docs/en/core/yql/reference/builtins/dict.md @@ -2,9 +2,9 @@ ## DictCreate {#dictcreate} -Construct an empty dictionary. Two arguments are passed: for a key and a value. Each argument specifies a string with the data type declaration or the type itself built by [type functions](../types.md). There are no dictionaries with an unknown key or value type in YQL. As a key, you can set a [primitive data type](../../types/primitive.md), except for `Yson` and `Json` that may be [optional](../../types/optional.md) or a tuple of them of a length of at least two. +Construct an empty dictionary. Two arguments are passed: for a key and a value. Each argument specifies a string with the data type declaration or the type itself built by [type functions](types.md). There are no dictionaries with an unknown key or value type in YQL. As a key, you can set a [primitive data type](../types/primitive.md), except for `Yson` and `Json` that may be [optional](../types/optional.md) or a tuple of them of a length of at least two. -[Documentation for the type definition format](../../types/type_string.md). +[Documentation for the type definition format](../types/type_string.md). ### Examples @@ -18,9 +18,9 @@ SELECT DictCreate(Tuple, OptionalType(DataType("String"))); ## SetCreate {#setcreate} -Construct an empty set. An argument is passed: the key type that can be built by [type functions](../types.md). There are no sets with an unknown key type in YQL. As a key, you can set a [primitive data type](../../types/primitive.md), except for `Yson` and `Json` that may be [optional](../../types/optional.md) or a tuple of them of a length of at least two. +Construct an empty set. An argument is passed: the key type that can be built by [type functions](types.md). There are no sets with an unknown key type in YQL. As a key, you can set a [primitive data type](../types/primitive.md), except for `Yson` and `Json` that may be [optional](../types/optional.md) or a tuple of them of a length of at least two. -[Documentation for the type definition format](../../types/type_string.md). +[Documentation for the type definition format](../types/type_string.md). ### Examples @@ -176,7 +176,7 @@ FROM my_table; ## DictAggregate {#dictaggregate} -Apply [aggregation factory](../basic.md#aggregationfactory) to the passed dictionary where each value is a list. The factory is applied separately inside each key. +Apply [aggregation factory](basic.md#aggregationfactory) to the passed dictionary where each value is a list. The factory is applied separately inside each key. If the list is empty, the aggregation result is the same as for an empty table: 0 for the `COUNT` function and `NULL` for other functions. If the list under a certain key is empty in the passed dictionary, such a key is removed from the result. If the passed dictionary is optional and contains `NULL`, the result is also `NULL`. @@ -184,7 +184,7 @@ If the passed dictionary is optional and contains `NULL`, the result is also `NU Arguments: 1. Dictionary. -2. [Aggregation factory](../basic.md#aggregationfactory). +2. [Aggregation factory](basic.md#aggregationfactory). ### Examples diff --git a/ydb/docs/en/core/yql/reference/builtins/index.md b/ydb/docs/en/core/yql/reference/builtins/index.md new file mode 100644 index 000000000000..31c56ac25bb2 --- /dev/null +++ b/ydb/docs/en/core/yql/reference/builtins/index.md @@ -0,0 +1,25 @@ +# Built-in YQL functions + +- [Basic](basic.md) +- [Aggregate](aggregation.md) + +{% if feature_window_functions %} + +- [Window](window.md) + +{% endif %} + +- [For lists](list.md) +- [For dictionaries](dict.md) +- [For structures](struct.md) +- [For types](types.md) + +{% if feature_codegen %} + +- [For code generation](codegen.md) + +{% endif %} + +- [For JSON](json.md) +- [C++ libraries](../udf/list/index.md) + diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/json.md b/ydb/docs/en/core/yql/reference/builtins/json.md similarity index 99% rename from ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/json.md rename to ydb/docs/en/core/yql/reference/builtins/json.md index 34d041b2e7ad..d9168fa6d1d5 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/json.md +++ b/ydb/docs/en/core/yql/reference/builtins/json.md @@ -474,7 +474,7 @@ JsonPath supports predicates which are expressions that return a Boolean value a #### `like_regex` -The `like_regex` predicate lets you check if a string matches a regular expression. The syntax of regular expressions is the same as in [Hyperscan UDF](../../udf/list/hyperscan.md) and [REGEXP](../../syntax/expressions.md#regexp). +The `like_regex` predicate lets you check if a string matches a regular expression. The syntax of regular expressions is the same as in [Hyperscan UDF](../udf/list/hyperscan.md) and [REGEXP](../syntax/expressions.md#regexp). ##### Syntax @@ -1166,5 +1166,5 @@ SELECT ## See also -* [{#T}](../../../../recipes/yql/accessing-json.md) -* [{#T}](../../../../recipes/yql/modifying-json.md) \ No newline at end of file +* [{#T}](../recipes/accessing-json.md) +* [{#T}](../recipes/modifying-json.md) diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/list.md b/ydb/docs/en/core/yql/reference/builtins/list.md similarity index 95% rename from ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/list.md rename to ydb/docs/en/core/yql/reference/builtins/list.md index f47042430b99..c42b131f98c8 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/list.md +++ b/ydb/docs/en/core/yql/reference/builtins/list.md @@ -2,9 +2,9 @@ ## ListCreate {#list-create} -Construct an empty list. The only argument specifies a string describing the data type of the list cell, or the type itself obtained using [relevant functions](../types.md). YQL doesn't support lists with an unknown cell type. +Construct an empty list. The only argument specifies a string describing the data type of the list cell, or the type itself obtained using [relevant functions](types.md). YQL doesn't support lists with an unknown cell type. -[Documentation for the type definition format](../../types/type_string.md). +[Documentation for the type definition format](../types/type_string.md). ### Examples @@ -101,7 +101,7 @@ SELECT ListSort($list, ($x) -> { {% note info %} -The example used a [lambda function](../../syntax/expressions.md#lambda). +The example used a [lambda function](../syntax/expressions.md#lambda). {% endnote %} @@ -151,7 +151,7 @@ SELECT ListUnionAll( Based on the input lists, build a list of pairs containing the list items with matching indexes (`List`). The length of the returned list is determined by the shortest list for ListZip and the longest list for ListZipAll. -When the shorter list is exhausted, a `NULL` value of a relevant [optional type](../../types/optional.md) is paired with the elements of the longer list. +When the shorter list is exhausted, a `NULL` value of a relevant [optional type](../types/optional.md) is paired with the elements of the longer list. {% if feature_column_container_type %} @@ -238,7 +238,7 @@ Returns a sample without replacement from the list. If the probability/sample size is NULL, returns the original list. -An optional argument is used to control randomness, see [documentation for `Random`](./basic/random.md). +An optional argument is used to control randomness, see [documentation for `Random`](basic.md#random). ### Examples @@ -259,7 +259,7 @@ SELECT ListSampleN($list, 2); -- [4, 2] ## ListShuffle {#listshuffle} -Returns a shuffled copy of the list. An optional argument is used to control randomness, see [documentation for `Random`](./basic/random.md). +Returns a shuffled copy of the list. An optional argument is used to control randomness, see [documentation for `Random`](basic.md#random). ### Examples @@ -309,12 +309,12 @@ Arguments: 1. Source list. 2. Functions for processing list elements, such as: - * [Lambda function](../../syntax/expressions.md#lambda). + * [Lambda function](../syntax/expressions.md#lambda). * `Module::Function` - C++ UDF. {% if feature_udf_noncpp %} - * [Python UDF](../../udf/python.md), [JavaScript UDF](../../udf/javascript.md) or any other called value. + * [Python UDF](../udf/python.md), [JavaScript UDF](../udf/javascript.md) or any other called value. If the source list is optional, then the output list is also optional. @@ -617,14 +617,14 @@ SELECT ## ListAggregate {#listaggregate} -Apply the [aggregation factory](../basic.md#aggregationfactory) to the passed list. +Apply the [aggregation factory](basic.md#aggregationfactory) to the passed list. If the passed list is empty, the aggregation result is the same as for an empty table: 0 for the `COUNT` function and `NULL` for other functions. If the passed list is optional and `NULL`, the result is also `NULL`. Arguments: 1. List. -2. [Aggregation factory](../basic.md#aggregationfactory). +2. [Aggregation factory](basic.md#aggregationfactory). ### Examples @@ -660,7 +660,7 @@ FROM my_table; Converts a list to a dictionary where the keys are unique elements of this list, and values are omitted and have the type `Void`. For the `List` list, the result type is `Dict`. An optional list is also supported, resulting in an optional dictionary. -Inverse function: get a list of keys for the [DictKeys](../dict.md#dictkeys) dictionary. +Inverse function: get a list of keys for the [DictKeys](dict.md#dictkeys) dictionary. {% if feature_column_container_type %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/struct.md b/ydb/docs/en/core/yql/reference/builtins/struct.md similarity index 99% rename from ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/struct.md rename to ydb/docs/en/core/yql/reference/builtins/struct.md index 2714aff8688c..9ab3442d7285 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/struct.md +++ b/ydb/docs/en/core/yql/reference/builtins/struct.md @@ -34,7 +34,7 @@ If the field set contains duplicate values, an error is returned. Arguments: * The first argument passes the source structure to be expanded. -* All the other arguments must be named, each argument adds a new field and the argument's name is used as the field's name (as in [AsStruct](../basic.md#asstruct)). +* All the other arguments must be named, each argument adds a new field and the argument's name is used as the field's name (as in [AsStruct](basic.md#asstruct)). ### Examples diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/toc_i.yaml b/ydb/docs/en/core/yql/reference/builtins/toc_i.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/builtins/toc_i.yaml rename to ydb/docs/en/core/yql/reference/builtins/toc_i.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/types.md b/ydb/docs/en/core/yql/reference/builtins/types.md similarity index 92% rename from ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/types.md rename to ydb/docs/en/core/yql/reference/builtins/types.md index 80613a6d6148..001f1e81d8ed 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/types.md +++ b/ydb/docs/en/core/yql/reference/builtins/types.md @@ -2,11 +2,11 @@ ## FormatType {#formattype} -Serializing a type {% if feature_codegen %} or a handle type{% endif %} to a human-readable string. This helps at debugging and will also be used in the next examples of this section. [Documentation for the format](../../types/type_string.md). +Serializing a type {% if feature_codegen %} or a handle type{% endif %} to a human-readable string. This helps at debugging and will also be used in the next examples of this section. [Documentation for the format](../types/type_string.md). ## ParseType {#parsetype} -Building a type from a string with description. [Documentation for its format](../../types/type_string.md). +Building a type from a string with description. [Documentation for its format](../types/type_string.md). ### Examples @@ -45,7 +45,7 @@ SELECT FormatType(TypeOf( ## DataType {#datatype} -Returns a type for [primitive data types](../../types/primitive.md) based on type name. +Returns a type for [primitive data types](../types/primitive.md) based on type name. ### Examples @@ -128,7 +128,7 @@ SELECT FormatType(VariantType( ## ResourceType {#resourcetype} -Returns the type of the [resource](../../types/special.md) based on the passed string label. +Returns the type of the [resource](../types/special.md) based on the passed string label. ### Examples @@ -157,7 +157,7 @@ SELECT FormatType(CallableType( ## GenericType, UnitType, and VoidType {#generictype} -Return the same-name [special data types](../../types/special.md). They have no arguments because they are not parameterized. +Return the same-name [special data types](../types/special.md). They have no arguments because they are not parameterized. ### Examples @@ -284,7 +284,7 @@ FormatType(VariantUnderlyingType( ## Functions for data types during calculations -To work with data types during calculations, use handle types: these are [resources](../../types/special.md) that contain an opaque type definition. After constructing the type handle, you can revert to the regular type using the [EvaluateType](#evaluatetype) function. For debug purposes, you can convert a handle type to a string using the [FormatType](#formattype) function. +To work with data types during calculations, use handle types: these are [resources](../types/special.md) that contain an opaque type definition. After constructing the type handle, you can revert to the regular type using the [EvaluateType](#evaluatetype) function. For debug purposes, you can convert a handle type to a string using the [FormatType](#formattype) function. ### TypeHandle @@ -298,7 +298,7 @@ SELECT FormatType(TypeHandle(TypeOf("foo"))); -- String ### EvaluateType -Getting the type from the type handle passed to the argument. The function is evaluated before the start of the main calculation, as well as [EvaluateExpr](../basic.md#evaluate_expr_atom). +Getting the type from the type handle passed to the argument. The function is evaluated before the start of the main calculation, as well as [EvaluateExpr](basic.md#evaluate_expr_atom). #### Examples @@ -308,7 +308,7 @@ SELECT FormatType(EvaluateType(TypeHandle(TypeOf("foo")))); -- String ### ParseTypeHandle -Building a type handle from a string with description. [Documentation for its format](../../types/type_string.md). +Building a type handle from a string with description. [Documentation for its format](../types/type_string.md). #### Examples @@ -329,7 +329,7 @@ SELECT TypeKind(ParseTypeHandle("List")); -- List ### DataTypeComponents -Getting the name and parameters for a [primitive data type](../../types/primitive.md) from the primitive type handle passed to the argument. Reverse function: [DataTypeHandle](#datatypehandle). +Getting the name and parameters for a [primitive data type](../types/primitive.md) from the primitive type handle passed to the argument. Reverse function: [DataTypeHandle](#datatypehandle). #### Examples @@ -340,7 +340,7 @@ SELECT DataTypeComponents(ParseTypeHandle("Decimal(4,1)")); -- ["Decimal", "4", ### DataTypeHandle -Constructing a handle for a [primitive data type](../../types/primitive.md) from its name and parameters passed to the argument as a list. Reverse function: [DataTypeComponents](#datatypecomponents). +Constructing a handle for a [primitive data type](../types/primitive.md) from its name and parameters passed to the argument as a list. Reverse function: [DataTypeComponents](#datatypecomponents). #### Examples diff --git a/ydb/docs/en/core/yql/reference/builtins/window.md b/ydb/docs/en/core/yql/reference/builtins/window.md new file mode 100644 index 000000000000..f9a670167be7 --- /dev/null +++ b/ydb/docs/en/core/yql/reference/builtins/window.md @@ -0,0 +1,247 @@ + +# List of window functions in YQL + +The syntax for calling window functions is detailed in a [separate article](../syntax/window.md). + + + +## Aggregate functions {#aggregate-functions} + +All [aggregate functions](aggregation.md) can also be used as window functions. +In this case, each row includes an aggregation result obtained on a set of rows from the [window frame](../syntax/window.md#frame). + +### Examples + +```yql +SELECT + SUM(int_column) OVER w1 AS running_total, + SUM(int_column) OVER w2 AS total, +FROM my_table +WINDOW + w1 AS (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), + w2 AS (); +``` + + + +## ROW_NUMBER {#row_number} + +Row number within a [partition](../syntax/window.md#partition). No arguments. + +### Signature + +```yql +ROW_NUMBER()->Uint64 +``` + +### Examples + +```yql +SELECT + ROW_NUMBER() OVER w AS row_num +FROM my_table +WINDOW w AS (ORDER BY key); +``` + + + +## LAG / LEAD {#lag-lead} + +Accessing a value from a row in the [section](../syntax/window.md#partition) that lags behind (`LAG`) or leads (`LEAD`) the current row by a fixed number. The first argument specifies the expression to be accessed, and the second argument specifies the offset in rows. You may omit the offset. By default, the neighbor row is used: the previous or next, respectively (hence, 1 is assumed by default). For the rows having no neighbors at a given distance (for example, `LAG(expr, 3)` `NULL` is returned in the first and second rows of the section). + +### Signature + +```yql +LEAD(T[,Int32])->T? +LAG(T[,Int32])->T? +``` + +### Examples + +```yql +SELECT + int_value - LAG(int_value) OVER w AS int_value_diff +FROM my_table +WINDOW w AS (ORDER BY key); +``` + +```yql +SELECT item, odd, LAG(item, 1) OVER w as lag1 FROM ( + SELECT item, item % 2 as odd FROM ( + SELECT AsList(1, 2, 3, 4, 5, 6, 7) as item + ) + FLATTEN BY item +) +WINDOW w As ( + PARTITION BY odd + ORDER BY item +); + +/* Output: +item odd lag1 +-------------------- +2 0 NULL +4 0 2 +6 0 4 +1 1 NULL +3 1 1 +5 1 3 +7 1 5 +*/ +``` + + +## FIRST_VALUE / LAST_VALUE + +Access values from the first and last rows (using the `ORDER BY` clause for the window) of the [window frame](../syntax/window.md#frame). The only argument is the expression that you need to access. + +Optionally, `OVER` can be preceded by the additional modifier `IGNORE NULLS`. It changes the behavior of functions to the first or last **non-empty** (i.e., non-`NULL`) value among the window frame rows. The antonym of this modifier is `RESPECT NULLS`: it's the default behavior that can be omitted. + +### Signature + +```yql +FIRST_VALUE(T)->T? +LAST_VALUE(T)->T? +``` + +### Examples + +```yql +SELECT + FIRST_VALUE(my_column) OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + +```yql +SELECT + LAST_VALUE(my_column) IGNORE NULLS OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + + + +## NTH_VALUE + +Access a value from a row specified by position in the window's `ORDER BY` order within [window frame](../syntax/window.md#frame). Arguments - the expression to access and the row number, starting with 1. + +Optionally, the `IGNORE NULLS` modifier can be specified before `OVER`, which causes rows with `NULL` in the first argument's value to be skipped. The antonym of this modifier is `RESPECT NULLS`, which is the default behavior and may be skipped. + +### Signature + +```yql +NTH_VALUE(T,N)->T? +``` + +### Examples + +```yql +SELECT + NTH_VALUE(my_column, 2) OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + +```yql +SELECT + NTH_VALUE(my_column, 3) IGNORE NULLS OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + + + + +## RANK / DENSE_RANK / PERCENT_RANK {#rank} + +Number the groups of neighboring rows in the [partition](../syntax/window.md#partition) with the same expression value in the argument. `DENSE_RANK` numbers the groups one by one, and `RANK` skips `(N - 1)` values, with `N` being the number of rows in the previous group. `PERCENT_RANK` returns the relative rank of the current row: $(RANK - 1)/(number of rows in the partition - 1)$. + +If there is no argument, it uses the order specified in the `ORDER BY` section in the window definition. +If the argument is omitted and `ORDER BY` is not specified, then all rows are considered equal to each other. + +{% note info %} + +Passing an argument to `RANK`/`DENSE_RANK`/`PERCENT_RANK` is a non-standard extension in YQL. + +{% endnote %} + +### Signature + +```text +RANK([T])->Uint64 +DENSE_RANK([T])->Uint64 +PERCENT_RANK([T])->Double +``` + +### Examples + +```yql +SELECT + RANK(my_column) OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + +```yql +SELECT + DENSE_RANK() OVER w +FROM my_table +WINDOW w AS (ORDER BY my_column); +``` + +```yql +SELECT + PERCENT_RANK() OVER w +FROM my_table +WINDOW w AS (ORDER BY my_column); +``` + + + +## NTILE + +Distributes the rows of an ordered [partition](../syntax/window.md#partition) into a specified number of groups. The groups are numbered starting with one. For each row, the `NTILE` function returns the number of the group to which the row belongs. + +### Signature + +```yql +NTILE(Uint64)->Uint64 +``` + +### Examples + +```yql +SELECT + NTILE(10) OVER w AS group_num +FROM my_table +WINDOW w AS (ORDER BY key); +``` + + + +## CUME_DIST + +Returns the relative position (> 0 and <= 1) of a row within a [partition](../syntax/window.md#partition). No arguments. + +### Signature + +```yql +CUME_DIST()->Double +``` + +### Examples + +```yql +SELECT + CUME_DIST() OVER w AS dist +FROM my_table +WINDOW w AS (ORDER BY key); +``` + + +## SessionState() {#session-state} + +A non-standard window function `SessionState()` (without arguments) lets you get the session calculation status from [SessionWindow](../syntax/group_by.md#session-window) for the current row. +It's allowed only if `SessionWindow()` is present in the `PARTITION BY` section in the window definition. + diff --git a/ydb/docs/en/core/yql/reference/essentials.base_rev b/ydb/docs/en/core/yql/reference/essentials.base_rev new file mode 100644 index 000000000000..643de7419f4a --- /dev/null +++ b/ydb/docs/en/core/yql/reference/essentials.base_rev @@ -0,0 +1 @@ +9cf1bce240d3b7ba00185ee4715c7533ddf91cb9;yql/essentials/docs/en diff --git a/ydb/docs/en/core/yql/reference/index.md b/ydb/docs/en/core/yql/reference/index.md index b87ca4d5cbed..10a22f8a12bf 100644 --- a/ydb/docs/en/core/yql/reference/index.md +++ b/ydb/docs/en/core/yql/reference/index.md @@ -1,3 +1,20 @@ -{% include [intro.md](_includes/index/intro.md) %} +# YQL - Overview + +*YQL* ({{ ydb-short-name }} Query Language) is a universal declarative query language for {{ ydb-short-name }}, a dialect of SQL. YQL has been natively designed for large distributed databases, and therefore has a number of differences from the SQL standard. + +{{ ydb-short-name }} tools support interfaces for sending YQL queries and receiving their execution results: + + + +- [YDB CLI](../../reference/ydb-cli/index.md) +- [YDB SDK](../../reference/ydb-sdk/index.md) + +This documentation section contains the YQL reference that includes the sections: + +- [Data types](types/index.md) with a description of data types used in YQL +- [Syntax]syntax/index.md) with a full list of YQL commands +- [Built-in functions](builtins/index.md) with a description of the available built-in functions + +You can also take a tutorial to get familiar with the basic YQL commands, in the [YQL tutorial](../../dev/yql-tutorial/index.md) section. + -{% include [intro.md](_includes/index/start.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/recipes/yql/accessing-json.md b/ydb/docs/en/core/yql/reference/recipes/accessing-json.md similarity index 82% rename from ydb/docs/en/core/recipes/yql/accessing-json.md rename to ydb/docs/en/core/yql/reference/recipes/accessing-json.md index 27cbd72e4199..fca18ede86a5 100644 --- a/ydb/docs/en/core/recipes/yql/accessing-json.md +++ b/ydb/docs/en/core/yql/reference/recipes/accessing-json.md @@ -2,8 +2,8 @@ YQL provides two main ways to retrieve values from JSON: -- Using [**JSON functions from the SQL standard**](../../yql/reference/builtins/json.md). This approach is recommended for simple cases and for teams that are familiar with them from other DBMSs. -- Using [**Yson UDF**](../../yql/reference/udf/list/yson.md), [list](../../yql/reference/builtins/list.md) and [dict](../../yql/reference/builtins/dict.md) builtins, and [lambdas](../../yql/reference/syntax/expressions.md#lambda). This approach is more flexible and tightly integrated with {{ ydb-short-name }}'s data type system, thus recommended for complex cases. +- Using [**JSON functions from the SQL standard**](../builtins/json.md). This approach is recommended for simple cases and for teams that are familiar with them from other DBMSs. +- Using [**Yson UDF**](../udf/list/yson.md), [list](../builtins/list.md) and [dict](../builtins/dict.md) builtins, and [lambdas](../syntax/expressions.md#lambda). This approach is more flexible and tightly integrated with {{ ydb-short-name }}'s data type system, thus recommended for complex cases. Below are the recipes that will use the same input JSON to demonstrate how to use each option to check whether a key exists, get a specific value, and retrieve a subtree. @@ -100,4 +100,4 @@ SELECT ## See also -- [{#T}](modifying-json.md) \ No newline at end of file +- [{#T}](modifying-json.md) diff --git a/ydb/docs/en/core/recipes/yql/index.md b/ydb/docs/en/core/yql/reference/recipes/index.md similarity index 77% rename from ydb/docs/en/core/recipes/yql/index.md rename to ydb/docs/en/core/yql/reference/recipes/index.md index d6558b78d4d2..824bbd152721 100644 --- a/ydb/docs/en/core/recipes/yql/index.md +++ b/ydb/docs/en/core/yql/reference/recipes/index.md @@ -10,5 +10,5 @@ Table of contents: See also: -- [{#T}](../../yql/reference/index.md) -- [{#T}](../../dev/index.md) +- [{#T}](../index.md) +- [{#T}](../../../dev/index.md) diff --git a/ydb/docs/en/core/recipes/yql/modifying-json.md b/ydb/docs/en/core/yql/reference/recipes/modifying-json.md similarity index 81% rename from ydb/docs/en/core/recipes/yql/modifying-json.md rename to ydb/docs/en/core/yql/reference/recipes/modifying-json.md index 0298cf6461dd..3619aa1137e9 100644 --- a/ydb/docs/en/core/recipes/yql/modifying-json.md +++ b/ydb/docs/en/core/yql/reference/recipes/modifying-json.md @@ -17,7 +17,7 @@ SELECT Yson::SerializeJson(Yson::From($result_dict)); ## See also -- [{#T}](../../yql/reference/udf/list/yson.md) -- [{#T}](../../yql/reference/builtins/list.md) -- [{#T}](../../yql/reference/builtins/dict.md) -- [{#T}](accessing-json.md) \ No newline at end of file +- [{#T}](../udf/list/yson.md) +- [{#T}](../builtins/list.md) +- [{#T}](../builtins/dict.md) +- [{#T}](accessing-json.md) diff --git a/ydb/docs/en/core/recipes/yql/toc_p.yaml b/ydb/docs/en/core/yql/reference/recipes/toc_i.yaml similarity index 100% rename from ydb/docs/en/core/recipes/yql/toc_p.yaml rename to ydb/docs/en/core/yql/reference/recipes/toc_i.yaml diff --git a/ydb/docs/en/core/recipes/yql/ttl.md b/ydb/docs/en/core/yql/reference/recipes/ttl.md similarity index 89% rename from ydb/docs/en/core/recipes/yql/ttl.md rename to ydb/docs/en/core/yql/reference/recipes/ttl.md index 8df3d423ef70..b1a7ceefeac8 100644 --- a/ydb/docs/en/core/recipes/yql/ttl.md +++ b/ydb/docs/en/core/yql/reference/recipes/ttl.md @@ -12,7 +12,7 @@ ALTER TABLE `mytable` SET (TTL = Interval("PT1H") ON created_at); {% note tip %} -An `Interval` is created from a string literal in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format with [some restrictions](../../yql/reference/builtins/basic#data-type-literals). +An `Interval` is created from a string literal in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format with [some restrictions](../builtins/basic#data-type-literals). {% endnote %} @@ -24,7 +24,7 @@ ALTER TABLE `mytable` SET (TTL = Interval("PT1H") ON modified_at AS SECONDS); ## Enabling data eviction to S3-compatible external storage {#enable-tiering-on-existing-tables} -{% include [OLTP_not_allow_note](../../_includes/not_allow_for_oltp_note.md) %} +{% include [OLTP_not_allow_note](../../../_includes/not_allow_for_oltp_note.md) %} In the following example, rows of the table `mytable` will be moved to the bucket described in the external data source `/Root/s3_cold_data` one hour after the time recorded in the column `created_at` and will be deleted after 24 hours: @@ -37,9 +37,9 @@ ALTER TABLE `mytable` SET ( ); ``` -{% include [OLTP_not_allow_note](../../_includes/not_allow_for_oltp_note.md) %} +{% include [OLTP_not_allow_note](../../../_includes/not_allow_for_oltp_note.md) %} -To enable data eviction, an [external data source](../../concepts/datamodel/external_data_source.md) object that describes a connection to the external storage is needed. +To enable data eviction, an [external data source](../../../concepts/datamodel/external_data_source.md) object that describes a connection to the external storage is needed. In the example below, an external data source `/Root/s3_cold_data` is created. It describes a connection to bucket `test_cold_data` located in Yandex Object Storage with authorization by static access keys provided via secrets `access_key` and `secret_key`. ```yql diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_assets/join-YQL-06.png b/ydb/docs/en/core/yql/reference/syntax/_assets/join-YQL-06.png similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_assets/join-YQL-06.png rename to ydb/docs/en/core/yql/reference/syntax/_assets/join-YQL-06.png diff --git a/ydb/docs/en/core/yql/reference/syntax/action.md b/ydb/docs/en/core/yql/reference/syntax/action.md new file mode 100644 index 000000000000..91e8bb18ad93 --- /dev/null +++ b/ydb/docs/en/core/yql/reference/syntax/action.md @@ -0,0 +1,159 @@ +# ACTION + +## DEFINE ACTION {#define-action} + +Specifies a named action that is a parameterizable block of multiple top-level expressions. + +### Syntax + +1. `DEFINE ACTION`: action definition. +1. [Action name](expressions.md#named-nodes) that will be used to access the defined action further in the query. +1. The values of parameter names are listed in parentheses. +1. `AS` keyword. +1. List of top-level expressions. +1. `END DEFINE`: The marker of the last expression inside the action. + +One or more of the last parameters can be marked with a question mark `?` as optional. If they are omitted during the call, they will be assigned the `NULL` value. + +## DO {#do} + +Executes an `ACTION` with the specified parameters. + +### Syntax + +1. `DO`: Executing an action. +1. The named expression for which the action is defined. +1. The values to be used as parameters are listed in parentheses. + +`EMPTY_ACTION`: An action that does nothing. + +{% if feature_mapreduce %} + +{% note info %} + +In large queries, you can use separate files for action definition and include them to the main query using [EXPORT](export_import.md#export) + [IMPORT](export_import.md#import) so that instead of one long text you can have several logical parts that are easier to navigate. An important nuance: the `USE my_cluster;` directive in the import query does not affect behavior of actions declared in other files. + +{% endnote %} + +{% endif %} + +### Example + +```yql +DEFINE ACTION $hello_world($name, $suffix?) AS + $name = $name ?? ($suffix ?? "world"); + SELECT "Hello, " || $name || "!"; +END DEFINE; + +DO EMPTY_ACTION(); +DO $hello_world(NULL); +DO $hello_world("John"); +DO $hello_world(NULL, "Earth"); +``` + + + +## BEGIN .. END DO {#begin} + +Performing an action without declaring it (anonymous action). + +### Syntax + +1. `BEGIN`. +1. List of top-level expressions. +1. `END DO`. + +An anonymous action can't include any parameters. + +### Example + +```yql +DO BEGIN + SELECT 1; + SELECT 2 -- here and in the previous example, you might omit ';' before END +END DO +``` + + + +{% if feature_mapreduce %} + + ## EVALUATE IF {#evaluate-if} + +`EVALUATE IF`: Executing an action depending on the condition. It's followed by: + +1. Condition. +2. [DO](#do) with the name and parameters of the action or an anonymous action. +3. An optional `ELSE` followed by the second `DO` for a situation where the condition is not met. + +## EVALUATE FOR {#evaluate-for} + +`EVALUATE FOR`: Executing an action for each item in the list. It's followed by: + +1. [A named expression](expressions.md#named-nodes) applied to each next element in the list. +2. `IN` keyword. +3. The above-declared named expression applied to the list the action is executed on. +4. [DO](#do) with the name and parameters of an action or an anonymous action. In the parameters, you can use both the current element from the first paragraph and any named expressions declared above, including the list itself. +5. An optional `ELSE` followed by the second `DO` for the situation when the list is empty. + +### Examples + +```yql +DEFINE ACTION $hello() AS + SELECT "Hello!"; +END DEFINE; + +DEFINE ACTION $bye() AS + SELECT "Bye!"; +END DEFINE; + +EVALUATE IF RANDOM(0) > 0.5 + DO $hello() +ELSE + DO $bye(); + +EVALUATE IF RANDOM(0) > 0.1 DO BEGIN + SELECT "Hello!"; +END DO; + +EVALUATE FOR $i IN AsList(1, 2, 3) DO BEGIN + SELECT $i; +END DO; +``` + +```yql +-- copy the $input table to $count of new tables +$count = 3; +$input = "my_input"; +$inputs = ListReplicate($input, $count); +$outputs = ListMap( + ListFromRange(0, $count), + ($i) -> { + RETURN "tmp/out_" || CAST($i as String) + } +); +$pairs = ListZip($inputs, $outputs); + +DEFINE ACTION $copy_table($pair) as + $input = $pair.0; + $output = $pair.1; + INSERT INTO $output WITH TRUNCATE + SELECT * FROM $input; +END DEFINE; + +EVALUATE FOR $pair IN $pairs + DO $copy_table($pair) +ELSE + DO EMPTY_ACTION (); -- you may omit this ELSE, + -- do nothing is implied by default +``` + +{% note info %} + +Note that `EVALUATE` is run before the operation starts. Please also note that in `EVALUATE` you can't use [anonymous tables](select.md#temporary-tables). + +{% endnote %} + + + +{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter-async-replication.md b/ydb/docs/en/core/yql/reference/syntax/alter-async-replication.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter-async-replication.md rename to ydb/docs/en/core/yql/reference/syntax/alter-async-replication.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter-group.md b/ydb/docs/en/core/yql/reference/syntax/alter-group.md similarity index 86% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter-group.md rename to ydb/docs/en/core/yql/reference/syntax/alter-group.md index 716cb158d4d8..ee2fd755c23a 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter-group.md +++ b/ydb/docs/en/core/yql/reference/syntax/alter-group.md @@ -12,4 +12,4 @@ ALTER GROUP role_name DROP USER user_name [, ... ] * `role_name`: The name of the group. * `user_name`: The name of the user. -{% include [x](_includes/builtin_groups.md) %} +{% include [x](../_includes/builtin_groups.md) %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter-topic.md b/ydb/docs/en/core/yql/reference/syntax/alter-topic.md similarity index 93% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter-topic.md rename to ydb/docs/en/core/yql/reference/syntax/alter-topic.md index 7ebe239c4dff..e7d3f8c590e8 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter-topic.md +++ b/ydb/docs/en/core/yql/reference/syntax/alter-topic.md @@ -1,6 +1,6 @@ # ALTER TOPIC -You can use the `ALTER TOPIC` command to change the [topic](../../../../concepts/topic) settings, as well as add, update, or delete its consumers. +You can use the `ALTER TOPIC` command to change the [topic](../../../concepts/topic) settings, as well as add, update, or delete its consumers. Here is the general format of the `ALTER TOPIC` command: @@ -12,7 +12,7 @@ ALTER TOPIC topic_path action1, action2, ..., actionN; ## Updating a set of consumers -`ADD CONSUMER`: Adds a [consumer](../../../../concepts/topic#consumer) to a topic. +`ADD CONSUMER`: Adds a [consumer](../../../concepts/topic#consumer) to a topic. The following example will add a consumer with default settings to the topic. @@ -33,7 +33,7 @@ ALTER TOPIC `my_topic` ADD CONSUMER new_consumer2 WITH (important = false); {% if feature_topic_codecs %} -* `supported_codecs`: List of [codecs](../../../../concepts/topic#message-codec) supported by the consumer. +* `supported_codecs`: List of [codecs](../../../concepts/topic#message-codec) supported by the consumer. {% endif %} @@ -138,7 +138,7 @@ ALTER TOPIC `my_topic` RESET ( {% if feature_topic_codecs %} -* `supported_codecs`: List of [codecs](../../../../concepts/topic#message-codec) supported by the topic. Value type: `String`. +* `supported_codecs`: List of [codecs](../../../concepts/topic#message-codec) supported by the topic. Value type: `String`. {% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter-user.md b/ydb/docs/en/core/yql/reference/syntax/alter-user.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter-user.md rename to ydb/docs/en/core/yql/reference/syntax/alter-user.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter-view.md b/ydb/docs/en/core/yql/reference/syntax/alter-view.md similarity index 82% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter-view.md rename to ydb/docs/en/core/yql/reference/syntax/alter-view.md index fcf724150125..9b68faf94d3d 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter-view.md +++ b/ydb/docs/en/core/yql/reference/syntax/alter-view.md @@ -1,6 +1,6 @@ # ALTER VIEW -`ALTER VIEW` changes the definition of a [view](../../../../concepts/datamodel/view). +`ALTER VIEW` changes the definition of a [view](concepts/datamodel/view). {% note warning %} @@ -20,4 +20,4 @@ Please note that the two statements are executed separately, unlike a single `AL ## See also * [CREATE VIEW](create-view.md) -* [DROP VIEW](drop-view.md) \ No newline at end of file +* [DROP VIEW](drop-view.md) diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/changefeed.md b/ydb/docs/en/core/yql/reference/syntax/alter_table/changefeed.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/changefeed.md rename to ydb/docs/en/core/yql/reference/syntax/alter_table/changefeed.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/columns.md b/ydb/docs/en/core/yql/reference/syntax/alter_table/columns.md similarity index 99% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/columns.md rename to ydb/docs/en/core/yql/reference/syntax/alter_table/columns.md index 3220aefde947..26612d29b608 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/columns.md +++ b/ydb/docs/en/core/yql/reference/syntax/alter_table/columns.md @@ -12,4 +12,4 @@ ALTER TABLE episodes ADD COLUMN views Uint64; ```yql ALTER TABLE episodes DROP COLUMN views; -``` \ No newline at end of file +``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/family.md b/ydb/docs/en/core/yql/reference/syntax/alter_table/family.md similarity index 98% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/family.md rename to ydb/docs/en/core/yql/reference/syntax/alter_table/family.md index 98eb406db202..b7319edb5f9c 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/family.md +++ b/ydb/docs/en/core/yql/reference/syntax/alter_table/family.md @@ -77,4 +77,4 @@ The code below changes the compression level of codec if it supports different c ALTER TABLE series_with_families ALTER FAMILY default SET COMPRESSION_LEVEL 5; ``` -You can specify any parameters of a group of columns from the [`CREATE TABLE`](../create_table/index.md) command. \ No newline at end of file +You can specify any parameters of a group of columns from the [`CREATE TABLE`](../create_table/index.md) command. diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/index.md b/ydb/docs/en/core/yql/reference/syntax/alter_table/index.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/index.md rename to ydb/docs/en/core/yql/reference/syntax/alter_table/index.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/rename.md b/ydb/docs/en/core/yql/reference/syntax/alter_table/rename.md similarity index 99% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/rename.md rename to ydb/docs/en/core/yql/reference/syntax/alter_table/rename.md index 35102cec4370..71d3303532d9 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/rename.md +++ b/ydb/docs/en/core/yql/reference/syntax/alter_table/rename.md @@ -22,4 +22,4 @@ Renaming can be used to move a table from one directory within the database to a ``` yql ALTER TABLE `table1` RENAME TO `/backup/table1`; -``` \ No newline at end of file +``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/secondary_index.md b/ydb/docs/en/core/yql/reference/syntax/alter_table/secondary_index.md similarity index 99% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/secondary_index.md rename to ydb/docs/en/core/yql/reference/syntax/alter_table/secondary_index.md index e7fc8521708f..a527930b8ea0 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/secondary_index.md +++ b/ydb/docs/en/core/yql/reference/syntax/alter_table/secondary_index.md @@ -101,4 +101,4 @@ Example of index renaming: ```yql ALTER TABLE `series` RENAME INDEX `title_index` TO `title_index_new`; -``` \ No newline at end of file +``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/set.md b/ydb/docs/en/core/yql/reference/syntax/alter_table/set.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/set.md rename to ydb/docs/en/core/yql/reference/syntax/alter_table/set.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/toc_i.yaml b/ydb/docs/en/core/yql/reference/syntax/alter_table/toc_i.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/toc_i.yaml rename to ydb/docs/en/core/yql/reference/syntax/alter_table/toc_i.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/toc_p.yaml b/ydb/docs/en/core/yql/reference/syntax/alter_table/toc_p.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/alter_table/toc_p.yaml rename to ydb/docs/en/core/yql/reference/syntax/alter_table/toc_p.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/analyze.md b/ydb/docs/en/core/yql/reference/syntax/analyze.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/analyze.md rename to ydb/docs/en/core/yql/reference/syntax/analyze.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/commit.md b/ydb/docs/en/core/yql/reference/syntax/commit.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/commit.md rename to ydb/docs/en/core/yql/reference/syntax/commit.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create-async-replication.md b/ydb/docs/en/core/yql/reference/syntax/create-async-replication.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create-async-replication.md rename to ydb/docs/en/core/yql/reference/syntax/create-async-replication.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create-group.md b/ydb/docs/en/core/yql/reference/syntax/create-group.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create-group.md rename to ydb/docs/en/core/yql/reference/syntax/create-group.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create-object-type-secret.md b/ydb/docs/en/core/yql/reference/syntax/create-object-type-secret.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create-object-type-secret.md rename to ydb/docs/en/core/yql/reference/syntax/create-object-type-secret.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create-topic.md b/ydb/docs/en/core/yql/reference/syntax/create-topic.md similarity index 87% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create-topic.md rename to ydb/docs/en/core/yql/reference/syntax/create-topic.md index f9d5a3f27f64..72f35fdb5167 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/create-topic.md +++ b/ydb/docs/en/core/yql/reference/syntax/create-topic.md @@ -1,8 +1,8 @@ # CREATE TOPIC -The `CREATE TOPIC` call creates a [topic](../../../../concepts/topic). +The `CREATE TOPIC` call creates a [topic](concepts/topic). -When creating a topic, you can add topic [consumers](../../../../concepts/topic#consumer) to it and topic settings. +When creating a topic, you can add topic [consumers](concepts/topic#consumer) to it and topic settings. ```yql CREATE TOPIC topic_path ( @@ -38,7 +38,7 @@ CREATE TOPIC `my_topic` ( * `read_from`: Sets up the message write time starting from which the consumer will receive data. Data written before this time will not be read. Value type: `Datetime` OR `Timestamp` OR `integer` (unix-timestamp in the numeric format). Default value: `0` (read from the earliest available message). {% if feature_topic_codecs %} -* `supported_codecs`: List of [codecs](../../../../concepts/topic#message-codec) supported by the consumer. +* `supported_codecs`: List of [codecs](concepts/topic#message-codec) supported by the consumer. {% endif %} @@ -62,6 +62,6 @@ CREATE TOPIC `my_topic` WITH( {% if feature_topic_codecs %} -* `supported_codecs`: List of [codecs](../../../../concepts/topic#message-codec) supported by the topic. Value type: `String`. +* `supported_codecs`: List of [codecs](concepts/topic#message-codec) supported by the topic. Value type: `String`. {% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create-user.md b/ydb/docs/en/core/yql/reference/syntax/create-user.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create-user.md rename to ydb/docs/en/core/yql/reference/syntax/create-user.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create-view.md b/ydb/docs/en/core/yql/reference/syntax/create-view.md similarity index 96% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create-view.md rename to ydb/docs/en/core/yql/reference/syntax/create-view.md index 278a95178f8a..40f31451b2b5 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/create-view.md +++ b/ydb/docs/en/core/yql/reference/syntax/create-view.md @@ -1,6 +1,6 @@ # CREATE VIEW -`CREATE VIEW` defines a [view](../../../../concepts/datamodel/view) with a given query. +`CREATE VIEW` defines a [view](concepts/datamodel/view) with a given query. A view logically represents a table formed by a given query. The view does not physically store the table but executes the query to produce the data whenever the view is accessed. @@ -80,4 +80,4 @@ WHERE episodes.season_id = 1 AND episodes.episode_id = 1; ## See also * [ALTER VIEW](alter-view.md) -* [DROP VIEW](drop-view.md) \ No newline at end of file +* [DROP VIEW](drop-view.md) diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/family.md b/ydb/docs/en/core/yql/reference/syntax/create_table/family.md similarity index 99% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/family.md rename to ydb/docs/en/core/yql/reference/syntax/create_table/family.md index 86e3e0439ec8..988f6b6297a6 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/family.md +++ b/ydb/docs/en/core/yql/reference/syntax/create_table/family.md @@ -80,4 +80,4 @@ In the example below, for the created table, the `family_large` group of columns Available types of storage devices depend on the {{ ydb-short-name }} cluster configuration. -{% endnote %} \ No newline at end of file +{% endnote %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/index.md b/ydb/docs/en/core/yql/reference/syntax/create_table/index.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/index.md rename to ydb/docs/en/core/yql/reference/syntax/create_table/index.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md b/ydb/docs/en/core/yql/reference/syntax/create_table/secondary_index.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/secondary_index.md rename to ydb/docs/en/core/yql/reference/syntax/create_table/secondary_index.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/temporary.md b/ydb/docs/en/core/yql/reference/syntax/create_table/temporary.md similarity index 98% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/temporary.md rename to ydb/docs/en/core/yql/reference/syntax/create_table/temporary.md index 76a1e0255140..a14bc09124cb 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/temporary.md +++ b/ydb/docs/en/core/yql/reference/syntax/create_table/temporary.md @@ -12,4 +12,4 @@ CREATE TEMPORARY TABLE table_name ( ... ); - ``` \ No newline at end of file + ``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/toc_i.yaml b/ydb/docs/en/core/yql/reference/syntax/create_table/toc_i.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/toc_i.yaml rename to ydb/docs/en/core/yql/reference/syntax/create_table/toc_i.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/toc_p.yaml b/ydb/docs/en/core/yql/reference/syntax/create_table/toc_p.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/toc_p.yaml rename to ydb/docs/en/core/yql/reference/syntax/create_table/toc_p.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/with.md b/ydb/docs/en/core/yql/reference/syntax/create_table/with.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/create_table/with.md rename to ydb/docs/en/core/yql/reference/syntax/create_table/with.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/declare/general.md b/ydb/docs/en/core/yql/reference/syntax/declare.md similarity index 56% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/declare/general.md rename to ydb/docs/en/core/yql/reference/syntax/declare.md index a19fcbab0547..93cd978cd41e 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/declare/general.md +++ b/ydb/docs/en/core/yql/reference/syntax/declare.md @@ -1,6 +1,6 @@ # DECLARE -Declares a typed [named expression](../../expressions.md#named-nodes) whose value will be passed separately from the query text. With parameterization, you can separately develop an analytical solution and then launch it sequentially with different input values. +Declares a typed [named expression](expressions.md#named-nodes) whose value will be passed separately from the query text. With parameterization, you can separately develop an analytical solution and then launch it sequentially with different input values. In the case of transactional load, parameters let you avoid recompilation of queries when repeating calls of the same type. This way you can reduce server utilization and exclude compilation time from the total time of query execution. @@ -15,14 +15,14 @@ DECLARE $named-node AS data_type; 1. `DECLARE` keyword. 1. `$named-node`: The name by which you can access the passed value. It must start with `$`. 1. `AS` keyword. -1. `data_type` is the data type [represented as a string in the accepted format](../../../types/type_string.md). +1. `data_type` is the data type [represented as a string in the accepted format](../types/type_string.md). Only serializable data types are allowed: -* [Primitive types](../../../types/primitive.md). -* [Optional types](../../../types/optional.md). -* [Containers](../../../types/containers.md), except `Stream`. -* `Void` and `Null` are the supported [special types](../../../types/special.md). +* [Primitive types](../types/primitive.md). +* [Optional types](../types/optional.md). +* [Containers](../types/containers.md), except `Stream`. +* `Void` and `Null` are the supported [special types](../types/special.md). ## Example diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/delete.md b/ydb/docs/en/core/yql/reference/syntax/delete.md similarity index 72% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/delete.md rename to ydb/docs/en/core/yql/reference/syntax/delete.md index f794a5a9d4ca..a5d7ffb821b6 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/delete.md +++ b/ydb/docs/en/core/yql/reference/syntax/delete.md @@ -4,15 +4,15 @@ {% note warning %} -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} +Supported only for [row-oriented](../../../concepts/datamodel/table.md#row-oriented-tables) tables. Support for [column-oriented](../../../concepts/datamodel/table.md#column-oriented-tables) tables is currently under development. -Instead of using `DELETE FROM` to delete data from colum-oriented tables, you can use the mechanism of deleting rows by time — [TTL](../../../../concepts/ttl.md). TTL can be set when [creating](../create_table/index.md) the table via `CREATE TABLE` or [modified](../alter_table/index.md) later via `ALTER TABLE`. +Instead of using `DELETE FROM` to delete data from colum-oriented tables, you can use the mechanism of deleting rows by time — [TTL](../../../concepts/ttl.md). TTL can be set when [creating](create_table/index.md) the table via `CREATE TABLE` or [modified](alter_table/index.md) later via `ALTER TABLE`. {% endnote %} {% endif %} -Deletes rows that match the `WHERE` clause, from the table.{% if feature_mapreduce %} The table is searched by name in the database specified by the [USE](../use.md) operator.{% endif %} +Deletes rows that match the `WHERE` clause, from the table.{% if feature_mapreduce %} The table is searched by name in the database specified by the [USE](use.md) operator.{% endif %} ## Example diff --git a/ydb/docs/en/core/yql/reference/syntax/discard.md b/ydb/docs/en/core/yql/reference/syntax/discard.md new file mode 100644 index 000000000000..480fe5dedaab --- /dev/null +++ b/ydb/docs/en/core/yql/reference/syntax/discard.md @@ -0,0 +1,31 @@ +# DISCARD + +Calculates {% if select_command == "SELECT STREAM" %}[`SELECT STREAM`](select_stream.md){% else %}[`SELECT`](select/index.md){% endif %}{% if feature_mapreduce %}{% if reduce_command %}, [`{{ reduce_command }}`](reduce.md){% endif %}, or [`{{ process_command }}`](process.md){% endif %} without returning the result neither to the client or table.{% if feature_mapreduce %} You can't use it along with [INTO RESULT](into_result.md).{% endif %} + +It's good to combine it with [`Ensure`](../builtins/basic.md#ensure) to check the final calculation result against the user's criteria. + +{% if select_command != true or select_command == "SELECT" %} + +## Examples + +```yql +DISCARD SELECT 1; +``` + +```yql +INSERT INTO result_table WITH TRUNCATE +SELECT * FROM +my_table +WHERE value % 2 == 0; + +COMMIT; + +DISCARD SELECT Ensure( + 0, -- will discard result anyway + COUNT(*) > 1000, + "Too small result table, got only " || CAST(COUNT(*) AS String) || " rows" +) FROM result_table; +``` + +{% endif %} + diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/drop-async-replication.md b/ydb/docs/en/core/yql/reference/syntax/drop-async-replication.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/drop-async-replication.md rename to ydb/docs/en/core/yql/reference/syntax/drop-async-replication.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/drop-group.md b/ydb/docs/en/core/yql/reference/syntax/drop-group.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/drop-group.md rename to ydb/docs/en/core/yql/reference/syntax/drop-group.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/drop-user.md b/ydb/docs/en/core/yql/reference/syntax/drop-user.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/drop-user.md rename to ydb/docs/en/core/yql/reference/syntax/drop-user.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/drop-view.md b/ydb/docs/en/core/yql/reference/syntax/drop-view.md similarity index 72% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/drop-view.md rename to ydb/docs/en/core/yql/reference/syntax/drop-view.md index 5a581ef5612a..beb6b28c30c8 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/drop-view.md +++ b/ydb/docs/en/core/yql/reference/syntax/drop-view.md @@ -1,6 +1,6 @@ # DROP VIEW -`DROP VIEW` deletes an existing [view](../../../../concepts/datamodel/view). +`DROP VIEW` deletes an existing [view](concepts/datamodel/view). ## Syntax @@ -23,4 +23,4 @@ DROP VIEW recent_series; ## See also * [CREATE VIEW](create-view.md) -* [ALTER VIEW](alter-view.md) \ No newline at end of file +* [ALTER VIEW](alter-view.md) diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/drop_table.md b/ydb/docs/en/core/yql/reference/syntax/drop_table.md similarity index 65% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/drop_table.md rename to ydb/docs/en/core/yql/reference/syntax/drop_table.md index fc2f5a482588..878337bcaa53 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/drop_table.md +++ b/ydb/docs/en/core/yql/reference/syntax/drop_table.md @@ -1,6 +1,6 @@ # DROP TABLE -Deletes the specified table.{% if feature_mapreduce %} The table is searched by name in the database specified by the [USE](../use.md) operator.{% endif %} +Deletes the specified table.{% if feature_mapreduce %} The table is searched by name in the database specified by the [USE](use.md) operator.{% endif %} If there is no such table, an error is returned. diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/export_import.md b/ydb/docs/en/core/yql/reference/syntax/export_import.md similarity index 68% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/export_import.md rename to ydb/docs/en/core/yql/reference/syntax/export_import.md index 0b984edd3b6b..0e95c300d962 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/export_import.md +++ b/ydb/docs/en/core/yql/reference/syntax/export_import.md @@ -2,7 +2,7 @@ Here's the mechanism for putting part of the query into a separate attached file: -* [PRAGMA Library](../pragma.md#library) marks the attached file as available for import. +* [PRAGMA Library](pragma.md#library) marks the attached file as available for import. ## `Export` @@ -14,13 +14,13 @@ Here's the mechanism for putting part of the query into a separate attached file {% note info %} -You can use the library to include [lambdas](../expressions.md#lambda), [actions](../action.md){% if feature_subquery %}, [named subqueries](../subquery.md){% endif %}, constants and expressions, but **not subqueries or aggregate functions**. +You can use the library to include [lambdas](expressions.md#lambda), [actions](action.md){% if feature_subquery %}, [named subqueries](subquery.md){% endif %}, constants and expressions, but **not subqueries or aggregate functions**. {% endnote %} {% note warning %} -The file linked by the [PRAGMA Library](../pragma.md#library) must be attached to the query. **You can't use a [PRAGMA File](../pragma.md#file) for this purpose**. +The file linked by the [PRAGMA Library](pragma.md#library) must be attached to the query. **You can't use a [PRAGMA File](pragma.md#file) for this purpose**. {% endnote %} @@ -59,3 +59,5 @@ FROM ( ) ``` + + diff --git a/ydb/docs/en/core/yql/reference/syntax/expressions.md b/ydb/docs/en/core/yql/reference/syntax/expressions.md new file mode 100644 index 000000000000..d775b15fb53b --- /dev/null +++ b/ydb/docs/en/core/yql/reference/syntax/expressions.md @@ -0,0 +1,590 @@ +# Expressions + + + +## String concatenation {#concatenation} + +Executed using the binary operator `||`. + +As with other binary operators, if the data on either side is `NULL`, the result is also `NULL`. + +Don't confuse this operator with a logical "or": in SQL, it's denoted by the `OR` keyword. It's also not worth doing concatenation using `+`. + +### Examples + +```yql +SELECT "fo" || "o"; +``` + + + +## Matching a string by pattern {#check-match} + +`REGEXP` and `RLIKE` are aliases used to call [Re2::Grep](../udf/list/re2.md#match). `MATCH`: Same for [Re2::Match](../udf/list/re2.md#match). + +`LIKE` works as follows: + +* Patterns can include two special characters: + + * `%`: Zero or more of any characters. + * `_`: Exactly one of any character. + +All other characters are literals that represent themselves. + +* As opposed to `REGEXP`, `LIKE` must be matched exactly. For example, to search a substring, add `%` at the beginning and end of the pattern. +* `ILIKE` is a case-insensitive version of `LIKE`. +* If `LIKE` is applied to the key column of the sorted table and the pattern doesn't start with a special character, filtering by prefix drills down directly to the cluster level, which in some cases lets you avoid the full table scan. This optimization is disabled for `ILIKE`. +* To escape special characters, specify the escaped character after the pattern using the `ESCAPE '?'` keyword. Instead of `?` you can use any character except `%`, `_` and `\`. For example, if you use a question mark as an escape character, the expressions `?%`, `?_` and `??` will match their second character in the template: percent, underscore, and question mark, respectively. The escape character is undefined by default. + +The most popular way to use the `LIKE` and `REGEXP` keywords is to filter a table using the statements with the `WHERE` clause. However, there are no restrictions on using templates in this context: you can use them in most of contexts involving strings, for example, with concatenation by using `||`. + +### Examples + +```yql +SELECT * FROM my_table +WHERE string_column REGEXP '\\d+'; +-- the second slash is required because +-- all the standard string literals in SQL +-- can accept C-escaped strings +``` + +```yql +SELECT + string_column LIKE '___!_!_!_!!!!!!' ESCAPE '!' + -- searches for a string of exactly 9 characters: + -- 3 arbitrary characters + -- followed by 3 underscores + -- and 3 exclamation marks +FROM my_table; +``` + +```yql +SELECT * FROM my_table +WHERE key LIKE 'foo%bar'; +-- if the table is sorted by key, it will only scan the keys, +-- starting with "foo", and then, among them, +-- will leave only those that end in "bar" +``` + + + +## Operators + +### Arithmetic operators {#math-operators} + +The operators `+`, `-`, `*`, `/`, `%` are defined for [primitive data types](../types/primitive.md) that are variations of numbers. + +For the Decimal data type, bankers rounding is used (to the nearest even integer). + +#### Examples + +```yql +SELECT 2 + 2; +``` + +```yql +SELECT 0.0 / 0.0; +``` + +### Comparison operators {#comparison-operators} + +The operators `=`, `==`, `!=`, `<>`, `>`, `<` are defined for: + +* Primitive data types except Yson and Json. +* Tuples and structures with the same set of fields. No order is defined for structures, but you can check for (non-)equality. Tuples are compared element-by-element left to right. + +#### Examples + +```yql +SELECT 2 > 1; +``` + +### Logical operators {#logic-operators} + +Use the operators `AND`, `OR`, `XOR` for logical operations on Boolean values (`Bool`). + +#### Examples* + +```yql +SELECT 3 > 0 AND false; +``` + +### Bitwise operators {#bit-operators} + +Bitwise operations on numbers: + +* `&`, `|`, `^`: AND, OR, and XOR, respectively. Don't confuse bitwise operations with the related keywords. The keywords `AND`, `OR`, and `XOR` are used *for Boolean values only*, but not for numbers. +* ` ~ `: A negation. +* `<`, `>`: Left or right shifts. +* `|<`, `>|`: Circular left or right shifts. + +#### Examples + +```yql +SELECT + key << 10 AS key, + ~value AS value +FROM my_table; +``` + +### Precedence and associativity of operators {#operator-priority} + +Operator precedence determines the order of evaluation of an expression that contains different operators. +For example, the expression `1 + 2 * 3` is evaluated as `1 + (2 * 3)` because the multiplication operator has a higher precedence than the addition operator. + +Associativity determines the order of evaluating expressions containing operators of the same type. +For example, the expression `1 + 2 + 3` is evaluated as `(1 + 2) + 3` because the addition operator is left-associative. +On the other hand, the expression `a ?? b ?? c` is evaluated as `a ?? (b ?? c)` because the `??` operator is right-associative + +The table below shows precedence and associativity of YQL operators. +The operators in the table are listed in descending order of precedence. + +| Priority | Operator | Description | Associativity | +| --- | --- | --- | --- | +| 1 | `a[], a.foo, a()` | Accessing a container item, calling a function | Left | +| 2 | `+a, -a, ~a, NOT a` | Unary operators: plus, minus, bitwise and logical negation | Right | +| 3 | `a\|\|b` | [String concatenation](#concatenation) | Left | +| 4 | `a*b, a/b, a%b` | Multiplication, division, remainder of division | Left | +| 5 | `a+b, a-b` | Addition/Subtraction | Left | +| 6 | `a ?? b` | Operator notation for [NVL/COALESCE](../builtins/basic.md#coalesce) | Right | +| 7 | `ab, a\|\|b,` `a\|b, a^b, a&b` | Shift operators and logical bit operators | Left | +| 8 | `ab` | Comparison | Left | +| 9 | `a IN b` | Occurrence of an element in a set | Left | +| 9 | `a==b, a=b, a!=b, a<>b,` `a is (not) distinct from b` | Comparison for (non-)equality | Left | +| 10 | `a XOR b` | Logical XOR | Left | +| 11 | `a AND b` | Logical AND | Left | +| 12 | `a OR b` | Logical OR | Left | + + + +## IS \[NOT\] NULL {#is-null} + +Matching an empty value (`NULL`). Since `NULL` is a special value [equal to nothing](../types/optional.md#null_expr), the ordinary [comparison operators](#comparison-operators) can't be used to match it. + +### Examples + +```yql +SELECT key FROM my_table +WHERE value IS NOT NULL; +``` + + + +## IS \[NOT\] DISTINCT FROM {#is-distinct-from} + +Comparing of two values. Unlike the regular [comparison operators](#comparison-operators), NULLs are treated as equal to each other. +More precisely, the comparison is carried out according to the following rules: + +1. The operators `IS DISTINCT FROM`/`IS NOT DISTINCT FROM` are defined for those and only for those arguments for which the operators `!=` and `=` are defined. +2. The result of `IS NOT DISTINCT FROM` is equal to the logical negation of the `IS DISTINCT FROM` result for these arguments. +3. If the result of the `==` operator is not equal to zero for some arguments, then it is equal to the result of the `IS NOT DISTINCT FROM` operator for the same arguments. +4. If both arguments are empty `Optional` or `NULL`s, then the value of `IS NOT DISTINCT FROM` is `True`. +5. The result of `IS NOT DISTINCT FROM` for an empty `Optional` or `NULL` and filled-in `Optional` or non-`Optional` value is `False`. + +For values of composite types, these rules are used recursively. + + +## BETWEEN {#between} + +Checking whether a value is in a range. It's equivalent to two conditions with `>=` and `<=` (range boundaries are included). Can be used with the `NOT` prefix to support inversion. + +### Examples + +```yql +SELECT * FROM my_table +WHERE key BETWEEN 10 AND 20; +``` + + + +## IN {#in} + +Checking whether a value is inside of a set of values. It's logically equivalent to a chain of equality comparisons using `OR` but implemented more efficiently. + +{% note warning "Warning" %} + +Unlike a similar keyword in Python, in YQL `IN` **DOES NOT** search for a substring inside a string. To search for a substring, use the function [String::Contains](../udf/list/string.md) or [LIKE/REGEXP](#check-match) mentioned above. + +{% endnote %} + +Immediately after `IN`, you can specify the `COMPACT` modifier. +If `COMPACT` is not specified, then `IN` with a subquery is executed as a relevant `JOIN` (`LEFT SEMI` for `IN` and `LEFT ONLY` for `NOT IN`), if possible. +Using the `COMPACT` modifier forces the in-memory execution strategy: a hash table is immediately built from the contents of the right `IN` part in-memory, and then the left part is filtered. + +The `COMPACT` modifier must be used with care. Since the hash table is built in-memory, the query may fail if the right part of `IN` contains many large or different elements. + +{% if feature_mapreduce %} +Since YQL imposes a limit on the query size in bytes (it's about 1Mb), add large lists of values to your query by URLs and use the [ParseFile](../builtins/basic.md#parsefile) function. +{% endif %} + +### Examples + +```yql +SELECT column IN (1, 2, 3) +FROM my_table; +``` + +```yql +SELECT * FROM my_table +WHERE string_column IN ("a", "b", "c"); +``` + +```yql +$foo = AsList(1, 2, 3); +SELECT 1 IN $foo; +``` + +```yql +$values = (SELECT column + 1 FROM table); +SELECT * FROM my_table WHERE + -- filtering by an in-memory hash table for one_table + column1 IN COMPACT $values AND + -- followed by LEFT ONLY JOIN with other_table + column2 NOT IN (SELECT other_column FROM other_table); +``` + + + +## AS {#as} + +Can be used in the following scenarios: + +* Adding a short name (alias) for columns or tables within the query. +* Using named arguments in function calls. +* To specify the target type in the case of explicit type casting, see [CAST](#cast). + +### Examples + +{% if select_command != "SELECT STREAM" %} + +```yql +SELECT key AS k FROM my_table; +``` + +```yql +SELECT t.key FROM my_table AS t; +``` + +```yql +SELECT + MyFunction(key, 123 AS my_optional_arg) +FROM my_table; +``` + +{% else %} + +```yql +SELECT STREAM key AS k FROM my_stream; +``` + +```yql +SELECT STREAM s.key FROM my_stream AS s; +``` + +```yql +SELECT STREAM + MyFunction(key, 123 AS my_optional_arg) +FROM my_stream; +``` + +{% endif %} + + + +## CAST {#cast} + + + +Tries to cast the value to the specified type. The attempt may fail and return `NULL`. When used with numbers, it may lose precision or most significant bits. +{% if feature_column_container_type %} +For lists and dictionaries, it can either delete or replace with `NULL` the elements whose conversion failed. +For structures and tuples, it deletes elements that are omitted in the target type. +For more information about casting rules, see [here](../types/cast.md). +{% endif %} + +{% include [decimal_args](../_includes/decimal_args.md) %} + +### Examples + +{% include [cast_examples](../_includes/cast_examples.md) %} + + +## BITCAST {#bitcast} + +Performs a bitwise conversion of an integer value to the specified integer type. The conversion is always successful, but may lose precision or high-order bits. + +### Examples + +```yql +SELECT + BITCAST(100000ul AS Uint32), -- 100000 + BITCAST(100000ul AS Int16), -- -31072 + BITCAST(100000ul AS Uint16), -- 34464 + BITCAST(-1 AS Int16), -- -1 + BITCAST(-1 AS Uint16); -- 65535 +``` + + + +## CASE {#case} + +Conditional expressions and branching. It's similar to `if`, `switch` and ternary operators in the imperative programming languages. +If the result of the `WHEN` expression is `true`, the value of the `CASE` expression becomes the result following the condition, and the rest of the `CASE` expression isn't calculated. If the condition is not met, all the `WHEN` clauses that follow are checked. If none of the `WHEN` clauses are met, the `CASE` value is assigned the result from the `ELSE` clause. +The `ELSE` branch is mandatory in the `CASE` expression. Expressions in `WHEN` are checked sequentially, from top to bottom. + +Since its syntax is quite sophisticated, it's often more convenient to use the built-in function [IF](../builtins/basic.md#if). + +### Examples + +```yql +SELECT + CASE + WHEN value > 0 + THEN "positive" + ELSE "negative" + END +FROM my_table; +``` + +```yql +SELECT + CASE value + WHEN 0 THEN "zero" + WHEN 1 THEN "one" + ELSE "not zero or one" + END +FROM my_table; +``` + + + +## Named expressions {#named-nodes} + +Complex queries may be sophisticated, containing lots of nested levels and/or repeating parts. In YQL, you can use named expressions to assign a name to an arbitrary expression or subquery. Named expressions can be referenced in other expressions or subqueries. In this case, the original expression/subquery is actually substituted at point of use. + +A named expression is defined as follows: + +```yql + = | ; +``` + +Here `` consists of a $ character and an arbitrary non-empty identifier (for example, `$foo`). + +If the expression on the right is a tuple, you can automatically unpack it by specifying several named expressions separated by commas on the left: + +```yql +, , ... = ; +``` + +In this case, the number of expressions must match the tuple size. + +Each named expression has a scope. It starts immediately after the definition of a named expression and ends at the end of the nearest enclosed namescope (for example, at the end of the query or at the end of the body of the [lambda function](#lambda), [ACTION](action.md#define-action){% if feature_subquery %}, [SUBQUERY](subquery.md#define-subquery){% endif %}{% if feature_mapreduce %}, or the cycle [EVALUATE FOR](action.md#evaluate-for){% endif %}). +Redefining a named expression with the same name hides the previous expression from the current scope. + +If the named expression has never been used, a warning is issued. To avoid such a warning, use the underscore as the first character in the ID (for example, `$_foo`). +The named expression `$_` is called an anonymous named expression and is processed in a special way: it works as if `$_` would be automatically replaced by `$_`. +Anonymous named expressions are convenient when you don't need the expression value. For example, to fetch the second element from a tuple of three elements, you can write: + +```yql +$_, $second, $_ = AsTuple(1, 2, 3); +select $second; +``` + +An attempt to reference an anonymous named expression results in an error: + +```yql +$_ = 1; +select $_; --- error: Unable to reference anonymous name $_ +export $_; --- An error: Can not export anonymous name $_ +``` + +{% if feature_mapreduce %} +Moreover, you can't import a named expression with an anonymous alias: + +```yql +import utils symbols $sqrt as $_; --- error: Can not import anonymous name $_ +``` + +{% endif %} +Anonymous argument names are also supported for [lambda functions](#lambda), [ACTION](action.md#define-action){% if feature_subquery %}, [SUBQUERY](subquery.md#define-subquery){% endif %}{% if feature_mapreduce %}, and in [EVALUATE FOR](action.md#evaluate-for){% endif %}. + +{% note info %} + +If named expression substitution results in completely identical subgraphs in the query execution graph, the graphs are combined to execute a subgraph only once. + +{% endnote %} + +### Examples + +```yql +$multiplier = 712; +SELECT + a * $multiplier, -- $multiplier is 712 + b * $multiplier, + (a + b) * $multiplier +FROM abc_table; +$multiplier = c; +SELECT + a * $multiplier -- $multiplier is column c +FROM abc_table; +``` + +```yql +$intermediate = ( + SELECT + value * value AS square, + value + FROM my_table +); +SELECT a.square * b.value +FROM $intermediate AS a +INNER JOIN $intermediate AS b +ON a.value == b.square; +``` + +```yql +$a, $_, $c = AsTuple(1, 5u, "test"); -- unpack a tuple +SELECT $a, $c; +``` + +```yql +$x, $y = AsTuple($y, $x); -- swap expression values +``` + + + +## Table expressions {#table-contexts} + +A table expression is an expression that returns a table. Table expressions in YQL are as follows: + +* Subqueries: `(SELECT key, subkey FROM T)` +* [Named subqueries](#named-nodes): `$foo = SELECT * FROM T;` (in this case, `$foo` is also a table expression) +{% if feature_subquery %} +* [Subquery templates](subquery.md#define-subquery): `DEFINE SUBQUERY $foo($name) AS ... END DEFINE;` (`$foo("InputTable")` is a table expression). +{% endif %} + +Semantics of a table expression depends on the context where it is used. In YQL, table expressions can be used in the following contexts: + +* Table context: after [FROM](select/from.md). In this case, table expressions work as expected: for example, `$input = SELECT a, b, c FROM T; SELECT * FROM $input` returns a table with three columns. The table context also occurs after [UNION ALL](select/union.md#unionall){% if feature_join %}, [JOIN](join.md#join){% endif %}{% if feature_mapreduce and process_command == "PROCESS" %}, [PROCESS](process.md#process), [REDUCE](reduce.md#reduce){% endif %}; +* Vector context: after [IN](#in). In this context, the table expression must contain exactly one column (the name of this column doesn't affect the expression result in any way). A table expression in a vector context is typed as a list (the type of the list element is the same as the column type in this case). Example: `SELECT * FROM T WHERE key IN (SELECT k FROM T1)`; +* A scalar context arises *in all the other cases*. As in a vector context, a table expression must contain exactly one column, but the value of the table expression is a scalar, that is, an arbitrarily selected value of this column (if no rows are returned, the result is `NULL`). Example: `$count = SELECT COUNT(*) FROM T; SELECT * FROM T ORDER BY key LIMIT $count / 2`; + +The order of rows in a table context, the order of elements in a vector context, and the rule for selecting a value from a scalar context (if multiple values are returned), aren't defined. This order also cannot be affected by `ORDER BY`: `ORDER BY` without `LIMIT` is ignored in table expressions with a warning, and `ORDER BY` with `LIMIT` defines a set of elements rather than the order within that set. + +{% if feature_mapreduce and process_command == "PROCESS" %} + +There is an exception to this rule. Named expression with [PROCESS](process.md#process), if used in a scalar context, behaves as in a table context: + +```yql +$input = SELECT 1 AS key, 2 AS value; +$process = PROCESS $input; + +SELECT FormatType(TypeOf($process)); -- $process is used in a scalar context, + -- but the SELECT result in this case is List + +SELECT $process[0].key; -- that returns 1 + +SELECT FormatType(TypeOf($input)); -- throws an error: $input in a scalar context must contain one column +``` + +{% note warning %} + +A common error is to use an expression in a scalar context rather than a table context or vector context. For example: + +```yql +$dict = SELECT key, value FROM T1; + +DEFINE SUBQUERY $merge_dict($table, $dict) AS +SELECT * FROM $table LEFT JOIN $dict USING(key); +END DEFINE; + +SELECT * FROM $merge_dict("Input", $dict); -- $dict is used in a scalar context in this case. + -- an error: exactly one column is expected in a scalar context +``` + +A correct notation in this case is: + +```yql +DEFINE SUBQUERY $dict() AS +SELECT key, value FROM T1; +END DEFINE; + +DEFINE SUBQUERY $merge_dict($table, $dict) AS +SELECT * FROM $table LEFT JOIN $dict() USING(key); -- Using the table expression $dict() + -- (Calling a subquery template) in a table context +END DEFINE; + +SELECT * FROM $merge_dict("Input", $dict); -- $dict - is a subquery template (rather than a table expression) + -- that is passed as an argument of a table expression +``` + +{% endnote %} + +{% endif %} + + + +## Lambda functions {#lambda} + +Let you combine multiple expressions into a single callable value. + +List arguments in round brackets, following them by the arrow and lambda function body. The lambda function body includes either an expression in round brackets or curly brackets around an optional chain of [named expressions](#named-nodes) assignments and the call result after the `RETURN` keyword in the last expression. + +The scope for the lambda body: first the local named expressions, then arguments, then named expressions defined above by the lambda function at the top level of the query. + +Only use pure expressions inside the lambda body (those might also be other lambdas, possibly passed through arguments). However, you can't use [SELECT](select/index.md), [INSERT INTO](insert_into.md), or other top-level expressions. + +One or more of the last lambda parameters can be marked with a question mark as optional: if they haven't been specified when calling lambda, they are assigned the `NULL` value. + +### Examples + +```yql +$f = ($y) -> { + $prefix = "x"; + RETURN $prefix || $y; +}; + +$g = ($y) -> ("x" || $y); + +$h = ($x, $y?) -> ($x + ($y ?? 0)); + +SELECT $f("y"), $g("z"), $h(1), $h(2, 3); -- "xy", "xz", 1, 5 +``` + +```yql +-- if the lambda result is calculated by a single expression, then you can use a more compact syntax: +$f = ($x, $_) -> ($x || "suffix"); -- the second argument is not used +SELECT $f("prefix_", "whatever"); +``` + + + +## Accessing containers {#items-access} + +For accessing the values inside containers: + +* `Struct<>`, `Tuple<>` and `Variant<>`, use a **dot**. The set of keys (for the tuple and the corresponding variant — indexes) is known at the query compilation time. The key is **validated** before beginning the query execution. +* `List<>` and `Dict<>`, use **square brackets**. The set of keys (set of indexes for keys) is known only at the query execution time. The key is **not validated** before beginning the query execution. If no value is found, an empty value (NULL) is returned. + +[Description and list of available containers](../types/containers.md). + +When using this syntax to access containers within table columns, be sure to specify the full column name, including the table name or table alias separated by a dot (see the first example below). + +### Examples + +```yql +SELECT + t.struct.member, + t.tuple.7, + t.dict["key"], + t.list[7] +FROM my_table AS t; +``` + +```yql +SELECT + Sample::ReturnsStruct().member; +``` + + + diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_by.md b/ydb/docs/en/core/yql/reference/syntax/flatten.md similarity index 56% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_by.md rename to ydb/docs/en/core/yql/reference/syntax/flatten.md index bedec048bf91..3f7924f0d970 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_by.md +++ b/ydb/docs/en/core/yql/reference/syntax/flatten.md @@ -2,7 +2,7 @@ ## FLATTEN BY {#flatten-by} -Converts rows in the source table using vertical unpacking of [containers](../../../types/containers.md) of variable length (lists or dictionaries). +Converts rows in the source table using vertical unpacking of [containers](../types/containers.md) of variable length (lists or dictionaries). For example: @@ -41,11 +41,11 @@ SELECT value, id FROM as_table($sample) FLATTEN BY (value); This conversion can be convenient in the following cases: -* When it is necessary to output statistics by cells from a container column (for example, via [`GROUP BY`](../../group_by.md)). +* When it is necessary to output statistics by cells from a container column (for example, via [`GROUP BY`](group_by.md)). {% if feature_join %} -* When the cells in a container column store IDs from another table that you want to join with [`JOIN`](../../join.md). +* When the cells in a container column store IDs from another table that you want to join with [`JOIN`](join.md). {% endif %} @@ -68,9 +68,87 @@ This conversion can be convenient in the following cases: {% note info %} -`FLATTEN BY` interprets [optional data types](../../../types/optional.md) as lists of length 0 or 1. The table rows with `NULL` are skipped, and the column type changes to a similar non-optional type. +`FLATTEN BY` interprets [optional data types](../types/optional.md) as lists of length 0 or 1. The table rows with `NULL` are skipped, and the column type changes to a similar non-optional type. `FLATTEN BY` makes only one conversion at a time, so use `FLATTEN LIST BY` or `FLATTEN OPTIONAL BY` on optional containers, for example, `Optional>`. {% endnote %} + + +### Specifying the container type {#flatten-by-specific-type} + +To specify the type of container to convert to, you can use: + +* `FLATTEN LIST BY` + + For `Optional>`, `FLATTEN LIST BY` will unpack the list, treating `NULL` as an empty list. + +* `FLATTEN DICT BY` + + For `Optional>`, `FLATTEN DICT BY` will unpack the dictionary, interpreting `NULL` as an empty dictionary. + +* `FLATTEN OPTIONAL BY` + + To filter the `NULL` values without serialization, specify the operation by using `FLATTEN OPTIONAL BY`. + +### Examples + +```yql +SELECT + t.item.0 AS key, + t.item.1 AS value, + t.dict_column AS original_dict, + t.other_column AS other +FROM my_table AS t +FLATTEN DICT BY dict_column AS item; +``` + +```yql +SELECT * FROM ( + SELECT + AsList(1, 2, 3) AS a, + AsList("x", "y", "z") AS b +) FLATTEN LIST BY (a, b); +``` + +```yql +SELECT * FROM ( + SELECT + "1;2;3" AS a, + AsList("x", "y", "z") AS b +) FLATTEN LIST BY (String::SplitToList(a, ";") as a, b); +``` + + + +### Analogues of FLATTEN BY in other DBMS {#flatten-other-dmb} + +* PostgreSQL: `unnest` +* Hive: `LATERAL VIEW` +* MongoDB: `unwind` +* Google BigQuery: `FLATTEN` +* ClickHouse: `ARRAY JOIN / arrayJoin` + + + +## FLATTEN COLUMNS {#flatten-columns} + +Converts a table where all columns must be structures to a table with columns corresponding to each element of each structure from the source columns. + +The names of the source column structures are not used and not returned in the result. Be sure that the structure element names aren't repeated in the source columns. + +### Example + +```yql +SELECT x, y, z +FROM ( + SELECT + AsStruct( + 1 AS x, + "foo" AS y), + AsStruct( + false AS z) +) FLATTEN COLUMNS; +``` + diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/grant.md b/ydb/docs/en/core/yql/reference/syntax/grant.md similarity index 96% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/grant.md rename to ydb/docs/en/core/yql/reference/syntax/grant.md index 223880b93b09..f3bb897c8030 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/grant.md +++ b/ydb/docs/en/core/yql/reference/syntax/grant.md @@ -15,7 +15,7 @@ GRANT {{permission_name} [, ...] | ALL [PRIVILEGES]} ON {path_to_scheme_object [ `WITH GRANT OPTION` - using this clause gives the user or group the right to manage access rights - to grant or revoke specific rights. The clause functions similarly to granting the `"ydb.access.grant"` right or `GRANT`. A subject with the `ydb.access.grant` right cannot grant rights broader than they themselves have on the access object `path_to_scheme_object`. -{% include [x](_includes/permissions/permissions_list.md) %} +{% include [x](../_includes/permissions_list.md) %} ## Examples diff --git a/ydb/docs/en/core/yql/reference/syntax/group_by.md b/ydb/docs/en/core/yql/reference/syntax/group_by.md new file mode 100644 index 000000000000..6fb297631cbf --- /dev/null +++ b/ydb/docs/en/core/yql/reference/syntax/group_by.md @@ -0,0 +1,366 @@ +{% if select_command == "SELECT STREAM" %} + +## GROUP BY ... HOP + +Group the table by the values of the specified columns or expressions and the time window. + +If GROUP BY is present in the query, then when selecting columns (between `SELECT STREAM ... FROM`) you can **only** use the following constructs: + +1. Columns by which grouping is performed (they are included in the `GROUP BY` argument). +2. Aggregate functions (see the next section). Columns by which **no** grouping is made can only be included as arguments for an aggregate function. +3. Functions that output the start and end time of the current window (`HOP_START` and `HOP_END`) +4. Arbitrary calculations combining paragraphs 1-3. + +You can group by the result of calculating an arbitrary expression from the source columns. In this case, to access the result of this expression, we recommend you to assign a name to it using `AS`, see the second example. + +Aggregate functions automatically skip `NULL` in their arguments. + +Among the columns by which grouping is performed, make sure to use the `HOP` construct to define the time window for grouping. + +```yql +HOP(time_extractor, hop, interval, delay) +``` + +The implemented version of the time window is called the **hopping window**. This is a window that moves forward in discrete intervals (the `hop` parameter). The total duration of the window is set by the `interval` parameter. To determine the time of each input event, the `time_extractor` parameter is used. This expression depends only on the input values of the stream's columns and must have the `Timestamp` type. It indicates where exactly to get the time value from input events. + +In each stream defined by the values of all the grouping columns, the window moves forward independently of other streams. Advancement of the window is totally dependent on the latest event of the stream. Since records in streams get somewhat mixed in time, the `delay` parameter has been added so you can delay the closing of the window by a specified period. Events arriving before the current window are ignored. + +The `interval` and `delay` parameters must be multiples of the `hop` parameter. Non-multiple intervals will be rounded down. + +To set `hop`, `interval` and `delay`, use a string expression compliant with [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). This is the format that is used to construct the built-in type `Interval` [from a string](../builtins/basic.md#data-type-literals). + +Functions with omitted `HOP_START` and `HOP_END` parameters, return a value of the `Timestamp` type and correspond to the start and end of the current window. + +The **tumbling window** known in other systems is a special case of a **hopping window** when `interval` == `hop`. + +## Examples + +```yql +SELECT STREAM + key, + COUNT(*) +FROM my_stream +GROUP BY + HOP(CAST(subkey AS Timestamp), "PT10S", "PT1M", "PT30S"), + key; +-- hop = 10 seconds +-- interval = 1 minute +-- delay = 30 seconds +``` + +```yql +SELECT STREAM + double_key, + HOP_END() as time, + COUNT(*) as count +FROM my_stream +GROUP BY + key + key AS double_key, + HOP(ts, "PT1M", "PT1M", "PT1M"); +``` + + + +## HAVING {#having} + +Filtering a `SELECT STREAM` based on the calculation results of [aggregate functions](../builtins/aggregation.md). The syntax is similar to [WHERE](select_stream.md#where). + +### Examples + +```yql +SELECT STREAM + key +FROM my_table +GROUP BY key, HOP(ts, "PT1M", "PT1M", "PT1M") +HAVING COUNT(value) > 100; +``` + + + +{% else %} + +## GROUP BY + +Group the `SELECT` results by the values of the specified columns or expressions. `GROUP BY` is often combined with [aggregate functions](../builtins/aggregation.md) (`COUNT`, `MAX`, `MIN`, `SUM`, `AVG`) to perform calculations in each group. + +### Syntax + +```yql +SELECT -- In SELECT, you can use: + column1, -- key columns specified in GROUP BY + key_n, -- named expressions specified in GROUP BY + column1 + key_n, -- arbitrary non-aggregate functions on them + Aggr_Func1( column2 ), -- aggregate functions containing any columns as arguments, + Aggr_Func2( key_n + column2 ), -- including named expressions specified in GROUP BY + ... +FROM table +GROUP BY + column1, column2, ..., + AS key_n -- When grouping by expression, you can set a name for it using AS, + -- and use it in SELECT +``` + +The query in the format `SELECT * FROM table GROUP BY k1, k2, ...` returns all columns listed in GROUP BY, i.e., is equivalent to `SELECT DISTINCT k1, k2, ... FROM table`. + +An asterisk can also be used as an argument for the `COUNT` aggregate function. `COUNT(*)` means "the count of rows in the group". + +{% note info %} + +Aggregate functions ignore `NULL` in their arguments, except for `COUNT`. + +{% endnote %} + +YQL also provides aggregation factories implemented by the functions [`AGGREGATION_FACTORY`](../builtins/basic.md#aggregationfactory) and [`AGGREGATE_BY`](../builtins/aggregation.md#aggregateby). + +### Examples + +```yql +SELECT key, COUNT(*) FROM my_table +GROUP BY key; +``` + +```yql +SELECT double_key, COUNT(*) FROM my_table +GROUP BY key + key AS double_key; +``` + +```yql +SELECT + double_key, -- OK: A key column + COUNT(*) AS group_size, -- OK: COUNT(*) + SUM(key + subkey) AS sum1, -- OK: An aggregate function + CAST(SUM(1 + 2) AS String) AS sum2, -- OK: An aggregate function with a constant argument + SUM(SUM(1) + key) AS sum3, -- ERROR: Nested aggregations are not allowed + key AS k1, -- ERROR: Using a non-key column named key without aggregation + key * 2 AS dk1, -- ERROR in YQL: using a non-key column named key without aggregation +FROM my_table +GROUP BY + key * 2 AS double_key, + subkey as sk, +``` + +{% note warning %} + +Specifying a name for a column or expression in `GROUP BY .. AS foo` it is an extension on top of YQL. Such a name becomes visible in `WHERE` despite the fact that filtering by `WHERE` is executed [before](select/where.md) the grouping. For example, if the `T` table includes two columns, `foo` and `bar`, then the query `SELECT foo FROM T WHERE foo > 0 GROUP BY bar AS foo` would actually filter data by the `bar` column from the source table. + +{% endnote %} + + + +## GROUP BY ... SessionWindow() {#session-window} + +YQL supports grouping by session. To standard expressions in `GROUP BY`, you can add a special `SessionWindow` function: + +```yql +SELECT + user, + session_start, + SessionStart() AS same_session_start, -- It's same as session_start + COUNT(*) AS session_size, + SUM(value) AS sum_over_session, +FROM my_table +GROUP BY user, SessionWindow(, ) AS session_start +``` + +The following happens in this case: + +1. The input table is partitioned by the grouping keys specified in `GROUP BY`, ignoring SessionWindow (in this case, it's based on `user`). + + If `GROUP BY` includes nothing more than SessionWindow, then the input table gets into one partition. + +2. Each partition is split into disjoint subsets of rows (sessions). + + For this, the partition is sorted in the ascending order of the `time_expr` expression. + The session limits are drawn between neighboring items of the partition, that differ in their `time_expr` values by more than `timeout_expr`. + +3. The sessions obtained in this way are the final partitions on which aggregate functions are calculated. + +The `SessionWindow()` key column (in the example, it's `session_start`) has the value "the minimum `time_expr` in the session". +If `GROUP BY` includes SessionWindow(), you can use a special aggregate function +[SessionStart](../builtins/aggregation.md#session-start). + +An extended version of SessionWindow with four arguments is also supported: + +`SessionWindow(, , , )` + +Where: + +* ``: An expression used to sort the source partition +* ``: A lambda function to initialize the state of session calculation. It has the signature `(TableRow())->State`. It's called once for the first (following the sorting order) element of the source partition +* ``: A lambda function to update the status of session calculation and define the session limits. It has the signature `(TableRow(), State)->Tuple`. It's called for every item of the source partition, except the first one. The new value of state is calculated based on the current row of the table and the previous state. If the first item in the return tuple is `True`, then a new session starts from the _current_ row. The key of the new session is obtained by applying `` to the second item in the tuple. +* ``: A lambda function for calculating the session key (the "value" of SessionWindow() that is also accessible via SessionStart()). The function has the signature `(TableRow(), State)->SessionKey`. It's called for the first item in the partition (after ``) and those items for which `` has returned `True` in the first item in the tuple. Please note that to start a new session, you should make sure that `` has returned a value different from the previous session key. Sessions having the same keys are not merged. For example, if `` returns the sequence `0, 1, 0, 1`, then there will be four different sessions. + +Using the extended version of SessionWindow, you can, for example, do the following: divide a partition into sessions, as in the SessionWindow use case with two arguments, but with the maximum session length limited by a certain constant: + +### Example + +```yql +$max_len = 1000; -- is the maximum session length. +$timeout = 100; -- is the timeout (timeout_expr in a simplified version of SessionWindow). + +$init = ($row) -> (AsTuple($row.ts, $row.ts)); -- is the session status: tuple from 1) value of the temporary column ts in the session's first line and 2) in the current line +$update = ($row, $state) -> { + $is_end_session = $row.ts - $state.0 > $max_len OR $row.ts - $state.1 > $timeout; + $new_state = AsTuple(IF($is_end_session, $row.ts, $state.0), $row.ts); + return AsTuple($is_end_session, $new_state); +}; +$calculate = ($row, $state) -> ($row.ts); +SELECT + user, + session_start, + SessionStart() AS same_session_start, -- It's same as session_start + COUNT(*) AS session_size, + SUM(value) AS sum_over_session, +FROM my_table +GROUP BY user, SessionWindow(ts, $init, $update, $calculate) AS session_start +``` + +You can use `SessionWindow` in `GROUP BY` only once. + + + +{% if feature_group_by_rollup_cube %} + +## ROLLUP, CUBE, and GROUPING SETS {#rollup} + +The results of calculating the aggregate function as subtotals for the groups and overall totals over individual columns or whole table. + +### Syntax + +```yql +SELECT + c1, c2, -- the columns to group by + +AGGREGATE_FUNCTION(c3) AS outcome_c -- an aggregate function (SUM, AVG, MIN, MAX, COUNT) + +FROM table_name + +GROUP BY + GROUP_BY_EXTENSION(c1, c2) -- an extension of GROUP BY: ROLLUP, CUBE, or GROUPING SETS +``` + +* `ROLLUP` groups the column values in the order they are listed in the arguments (strictly from left to right), generates subtotals for each group and the overall total. +* `CUBE` groups the values for every possible combination of columns, generates the subtotals for each group and the overall total. +* `GROUPING SETS` sets the groups for subtotals. + +You can combine `ROLLUP`, `CUBE` and `GROUPING SETS`, separating them by commas. + +### GROUPING {#grouping} + +The values of columns not used in calculations are replaced with `NULL` in the subtotal. In the overall total, the values of all columns are replaced by `NULL`. `GROUPING`: A function that allows you to distinguish the source `NULL` values from the `NULL` values added while calculating subtotals and overall totals. + +`GROUPING` returns a bit mask: + +* `0`: If `NULL` is used for the original empty value. +* `1`: If `NULL` is added for a subtotal or overall total. + +### Example + +```yql +SELECT + column1, + column2, + column3, + + CASE GROUPING( + column1, + column2, + column3, + ) + WHEN 1 THEN "Subtotal: column1 and column2" + WHEN 3 THEN "Subtotal: column1" + WHEN 4 THEN "Subtotal: column2 and column3" + WHEN 6 THEN "Subtotal: column3" + WHEN 7 THEN "Grand total" + ELSE "Individual group" + END AS subtotal, + + COUNT(*) AS rows_count + +FROM my_table + +GROUP BY + ROLLUP( + column1, + column2, + column3 + ), + GROUPING SETS( + (column2, column3), + (column3) + -- if you add here (column2) as well, then together + -- the ROLLUP and GROUPING SETS would produce a result + -- similar to CUBE + ) +; +``` + + + +{% endif %} + +## DISTINCT {#distinct} + +Applying [aggregate functions](../builtins/aggregation.md) only to distinct values of the column. + +{% note info %} + +Applying `DISTINCT` to calculated values is not currently implemented. For this purpose, you can use a [subquery](select/from.md) or the expression `GROUP BY ... AS ...`. + +{% endnote %} + +### Example + +```yql +SELECT + key, + COUNT (DISTINCT value) AS count -- top 3 keys by the number of unique values +FROM my_table +GROUP BY key +ORDER BY count DESC +LIMIT 3; +``` + +You can also use `DISTINCT` to fetch distinct rows using [`SELECT DISTINCT`](select/distinct.md). + + + +## GROUP COMPACT BY + +Improves aggregation efficiency if the query author knows in advance that none of aggregation keys finds large amounts of data (i.e., with the order of magnitude exceeding a gigabyte or a million of rows). If this assumption fails to materialize, then the operation may fail with Out of Memory error or start running much slower compared to the non-COMPACT version. + +Unlike the usual GROUP BY, the Map-side combiner stage and additional Reduce are disabled for each field with [DISTINCT](../syntax/group_by.md#distinct) aggregation. + +### Example + +```yql +SELECT + key, + COUNT (DISTINCT value) AS count -- top 3 keys by the number of unique values +FROM my_table +GROUP COMPACT BY key +ORDER BY count DESC +LIMIT 3; +``` + + + +## HAVING {#having} + +Filtering a `SELECT` based on the calculation results of [aggregate functions](../builtins/aggregation.md). The syntax is similar to [WHERE](select/where.md). + +### Example + +```yql +SELECT + key +FROM my_table +GROUP BY key +HAVING COUNT(value) > 100; +``` + + + +{% endif %} + + diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/index.md b/ydb/docs/en/core/yql/reference/syntax/index.md similarity index 97% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/index.md rename to ydb/docs/en/core/yql/reference/syntax/index.md index 34b4c12c4a12..289dc93d94a2 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/index.md +++ b/ydb/docs/en/core/yql/reference/syntax/index.md @@ -63,7 +63,12 @@ {% endif %} +{% if backend_name != "YDB" %} + * [DISCARD](discard.md) + +{% endif %} + * [INTO RESULT](into_result.md) {% if feature_mapreduce %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/insert_into.md b/ydb/docs/en/core/yql/reference/syntax/insert_into.md similarity index 50% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/insert_into.md rename to ydb/docs/en/core/yql/reference/syntax/insert_into.md index 776f1a789aa2..8ca50f196e5c 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/insert_into.md +++ b/ydb/docs/en/core/yql/reference/syntax/insert_into.md @@ -4,9 +4,17 @@ {% note warning %} -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} +Supported only for [row-oriented](../../../concepts/datamodel/table.md#row-oriented-tables) tables. Support for [column-oriented](../../../concepts/datamodel/table.md#column-oriented-tables) tables is currently under development. -{% include [ways_add_data_to_olap](../../../../_includes/ways_add_data_to_olap.md) %} +{% if oss %} + +Available methods for loading data into columnar tables: + +* [{{ ydb-short-name }} CLI](../../../reference/ydb-cli/export-import/import-file.md) +* [Bulk data upsert](../../../recipes/ydb-sdk/bulk-upsert.md) +* [Yandex Data Transfer](https://yandex.cloud/ru/services/data-transfer) + +{% endif %} {% endnote %} @@ -14,11 +22,11 @@ {% if select_command != "SELECT STREAM" %} Adds rows to the table. {% if feature_bulk_tables %} If the target table already exists and is not sorted, the operation `INSERT INTO` adds rows at the end of the table. In the case of a sorted table, YQL tries to preserve sorting by running a sorted merge. {% endif %}{% if feature_map_tables %} If you try to insert a row into a table with an existing primary key value, the operation fails with the `PRECONDITION_FAILED` error code and the `Operation aborted due to constraint violation: insert_pk` message returned.{% endif %} -{% if feature_mapreduce %}The table is searched by name in the database specified by the [USE](../use.md) operator.{% endif %} +{% if feature_mapreduce %}The table is searched by name in the database specified by the [USE](use.md) operator.{% endif %} `INSERT INTO` lets you perform the following operations: -* Adding constant values using [`VALUES`](../values.md). +* Adding constant values using [`VALUES`](values.md). ```yql INSERT INTO my_table (Key1, Key2, Value1, Value2) @@ -41,7 +49,7 @@ {% else %} -Send the result of the [SELECT STREAM](../select_stream.md) calculation to the specified stream on the cluster specified by the [USE](../use.md) operator. The stream must exist and have a scheme matching the query result. +Send the result of the [SELECT STREAM](select_stream.md) calculation to the specified stream on the cluster specified by the [USE](use.md) operator. The stream must exist and have a scheme matching the query result. ## Examples @@ -60,3 +68,23 @@ SELECT STREAM * FROM rtmr_cluster.`my_stream_source`; {% endif %} + + +{% if feature_insert_with_truncate %} + +Inserts can be made with one or more modifiers. A modifier is specified after the `WITH` keyword following the table name: `INSERT INTO ... WITH SOME_HINT`. +If a modifier has a value, it's indicated after the `=` sign: `INSERT INTO ... WITH SOME_HINT=value`. +If necessary, specify multiple modifiers, they should be enclosed in parentheses: `INSERT INTO ... WITH (SOME_HINT1=value, SOME_HINT2, SOME_HINT3=value)`. + +To clear the table of existing data before writing new data to it, add the modifier: `INSERT INTO ... WITH TRUNCATE`. + +### Examples + +```yql +INSERT INTO my_table WITH TRUNCATE +SELECT key FROM my_table_source; +``` + +{% endif %} + + diff --git a/ydb/docs/en/core/yql/reference/syntax/into_result.md b/ydb/docs/en/core/yql/reference/syntax/into_result.md new file mode 100644 index 000000000000..638ee5c9a7a2 --- /dev/null +++ b/ydb/docs/en/core/yql/reference/syntax/into_result.md @@ -0,0 +1,17 @@ +# INTO RESULT + +Lets you set a custom label for [SELECT](select/index.md){% if feature_mapreduce and process_command == "PROCESS" %}, [PROCESS](process.md), or [REDUCE](reduce.md){% endif %}.{% if backend_name != "YDB" %} It can't be used along with [DISCARD](discard.md).{% endif %} + + +## Examples + +```yql +SELECT 1 INTO RESULT foo; +``` + +```yql +SELECT * FROM +my_table +WHERE value % 2 == 0 +INTO RESULT `Result name`; +``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/join.md b/ydb/docs/en/core/yql/reference/syntax/join.md similarity index 99% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/join.md rename to ydb/docs/en/core/yql/reference/syntax/join.md index cf66ea3fd009..65f18ebf6acc 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/join.md +++ b/ydb/docs/en/core/yql/reference/syntax/join.md @@ -38,7 +38,7 @@ Since columns in YQL are identified by their names, and you can't have two colum * `CROSS`: A full Cartesian product of two tables without specifying key columns and no explicit `ON/USING`. * `EXCLUSION`: Both sides minus the intersection. -![JOIN](../_assets/join-YQL-06.png) +![JOIN](_assets/join-YQL-06.png) {% note info %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/lexer.md b/ydb/docs/en/core/yql/reference/syntax/lexer.md similarity index 96% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/lexer.md rename to ydb/docs/en/core/yql/reference/syntax/lexer.md index 8c03d768b22e..ed01be7797f3 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/lexer.md +++ b/ydb/docs/en/core/yql/reference/syntax/lexer.md @@ -1,3 +1,4 @@ + # Lexical structure The {% if feature_mapreduce %}program{% else %}query{% endif %} in the YQL language is a valid UTF-8 text consisting of **statements** separated by semicolons (`;`). @@ -85,7 +86,7 @@ SELECT 1 as "column with "" double quote"; -- column name will be: column with " SQL hints are special settings with which a user can modify a query execution plan (for example, enable/disable specific optimizations or force the JOIN execution strategy). -Unlike [PRAGMA](../pragma.md), SQL hints act locally – they are linked to a specific point in the YQL query (normally, after the keyword) +Unlike [PRAGMA](pragma.md), SQL hints act locally – they are linked to a specific point in the YQL query (normally, after the keyword) and affect only the corresponding statement or even a part of it. SQL hints are a set of settings "name-value list" and defined inside special comments — comments with SQL hints must have `+` as the first character: @@ -164,7 +165,7 @@ In ASNI SQL compatibility mode, double quotes are used for IDs, and the only esc SELECT 'string with '' quote'; -- result: string with ' quote ``` -Based on string literals, [simple literals](../../builtins/basic#data-type-literals) can be obtained. +Based on string literals, [simple literals](builtins/basic#data-type-literals) can be obtained. ### Multi-line string literals {#multiline-string-literals} @@ -188,7 +189,7 @@ SELECT $text; ### Typed string literals {#typed-string-literals} -* For string literals, including [multi-string](#multiline-string-literals) ones, the `String` type is used by default (see also [PRAGMA UnicodeLiterals](../pragma.md#UnicodeLiterals)). +* For string literals, including [multi-string](#multiline-string-literals) ones, the `String` type is used by default (see also [PRAGMA UnicodeLiterals](pragma.md#UnicodeLiterals)). * You can use the following suffixes to explicitly control the literal type: * `s` — `String` @@ -230,3 +231,5 @@ SELECT 456s AS `Int16`, 1.2345f AS `Float`; ``` + + diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/not_yet_supported.md b/ydb/docs/en/core/yql/reference/syntax/not_yet_supported.md similarity index 86% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/not_yet_supported.md rename to ydb/docs/en/core/yql/reference/syntax/not_yet_supported.md index 2dae040aa38a..f6ebbc1d5926 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/not_yet_supported.md +++ b/ydb/docs/en/core/yql/reference/syntax/not_yet_supported.md @@ -10,5 +10,5 @@ An alternative is to explicitly list the matching columns on both sides. ## NOW() / CURRENT_TIME() {#now} -An alternative is to use the functions [CurrentUtcDate, CurrentUtcDatetime and CurrentUtcTimestamp](../../builtins/basic.md#current-utc). +An alternative is to use the functions [CurrentUtcDate, CurrentUtcDatetime and CurrentUtcTimestamp](../builtins/basic.md#current-utc). diff --git a/ydb/docs/en/core/yql/reference/syntax/pragma.md b/ydb/docs/en/core/yql/reference/syntax/pragma.md new file mode 100644 index 000000000000..e56e659dcb83 --- /dev/null +++ b/ydb/docs/en/core/yql/reference/syntax/pragma.md @@ -0,0 +1,499 @@ +# PRAGMA + +## Definition + +Redefinition of settings. + +### Syntax + +`PRAGMA x.y = "z";` or `PRAGMA x.y("z", "z2", "z3");`: + +* `x`: (optional) The category of the setting. +* `y`: The name of the setting. +* `z`: (optional for flags) The value of the setting. The following suffixes are acceptable: + + * `Kb`, `Mb`, `Gb`: For the data amounts. + * `sec`, `min`, `h`, `d`: For the time values. + +### Examples + +```yql +PRAGMA AutoCommit; +``` + +```yql +PRAGMA TablePathPrefix = "home/yql"; +``` + +```yql +PRAGMA Warning("disable", "1101"); +``` + +With some exceptions, you can return the settings values to their default states using `PRAGMA my_pragma = default;`. + +For the full list of available settings, [see the table below](pragma.md#pragmas). + +### Scope {#pragmascope} + +Unless otherwise specified, a pragma affects all the subsequent expressions up to the end of the module where it's used. If necessary and logically possible, you can change the value of this setting several times within a given query to make it different at different execution steps. + +There are also special scoped pragmas with the scope defined by the same rules as the scope of [named expressions](expressions.md#named-nodes). Unlike scoped pragmas, regular pragmas can only be used in the global scope (not inside lambda functions, `ACTION`{% if feature_subquery %}, `SUBQUERY`{% endif %}, etc.). + + + +## Global {#pragmas} + +### AutoCommit {#autocommit} + +| Value type | Default | +| --- | --- | +| Flag | false | + +Automatically run [COMMIT](commit.md) after every statement. + +### TablePathPrefix {#table-path-prefix} + +| Value type | Default | +| --- | --- | +| String | — | + +Add the specified prefix to the cluster table paths. It uses standard file system path concatenation, supporting parent folder `..` referencing and requiring no trailing slash. For example, + +`PRAGMA TablePathPrefix = "home/yql"; +SELECT * FROM test;` + +The prefix is not added if the table name is an absolute path (starts with /). + +### UseTablePrefixForEach {#use-table-prefix-for-each} + +| Value type | Default | +| --- | --- | +| Flag | false | + +EACH uses [TablePathPrefix](#table-path-prefix) for each list item. + +### Warning {#warning} + +| Value type | Default | +| --- | --- | +| 1. Action
2. Warning code or "*" | — | + +Action: + +* `disable`: Disable. +* `error`: Treat as an error. +* `default`: Revert to the default behavior. + +The warning code is returned with the text itself (it's displayed on the right side of the web interface). + +#### Example + +`PRAGMA Warning("error", "*");` +`PRAGMA Warning("disable", "1101");` +`PRAGMA Warning("default", "4503");` + +In this case, all the warnings are treated as errors, except for the warning `1101` (that will be disabled) and `4503` (that will be processed by default, that is, remain a warning). Since warnings may be added in new YQL releases, use `PRAGMA Warning("error", "*");` with caution (at least cover such queries with autotests). + + + +{% if feature_mapreduce %} + +### DqEngine {#dqengine} + +| Value type | Default | +| --- | --- | +| disable/auto/force string | "auto" | + +When set to "auto", it enables a new compute engine. Computing is made, whenever possible, without creating map/reduce operations. When the value is "force", computing is made by the new engine unconditionally. +{% endif %} + +{% if feature_join %} + +### SimpleColumns {#simplecolumns} + +`SimpleColumns` / `DisableSimpleColumns` + +| Value type | Default | +| --- | --- | +| Flag | true | + +When you use `SELECT foo.* FROM ... AS foo`, remove the `foo.` prefix from the names of the result columns. + +It can be also used with a [JOIN](join.md), but in this case it may fail in the case of a name conflict (that can be resolved by using [WITHOUT](select/without.md) and renaming columns). For JOIN in SimpleColumns mode, an implicit Coalesce is made for key columns: the query `SELECT * FROM T1 AS a JOIN T2 AS b USING(key)` in the SimpleColumns mode works same as `SELECT a.key ?? b.key AS key, ... FROM T1 AS a JOIN T2 AS b USING(key)`. + +### CoalesceJoinKeysOnQualifiedAll + +`CoalesceJoinKeysOnQualifiedAll` / `DisableCoalesceJoinKeysOnQualifiedAll` + +| Value type | Default | +| --- | --- | +| Flag | true | + +Controls implicit Coalesce for the key `JOIN` columns in the SimpleColumns mode. If the flag is set, the Coalesce is made for key columns if there is at least one expression in the format `foo.*` or `*` in SELECT: for example, `SELECT a.* FROM T1 AS a JOIN T2 AS b USING(key)`. If the flag is not set, then Coalesce for JOIN keys is made only if there is an asterisk '*' after `SELECT` + +### StrictJoinKeyTypes + +`StrictJoinKeyTypes` / `DisableStrictJoinKeyTypes` + +| Value type | Default | +| --- | --- | +| Flag | false | + +If the flag is set, then [JOIN](join.md) will require strict matching of key types. +By default, JOIN preconverts keys to a shared type, which might result in performance degradation. +StrictJoinKeyTypes is a [scoped](pragma.md#pragmascope) setting. + +{% endif %} + +### AnsiInForEmptyOrNullableItemsCollections + +| Value type | Default | +| --- | --- | +| Flag | false | + +This pragma brings the behavior of the `IN` operator in accordance with the standard when there's `NULL` in the left or right side of `IN`. The behavior of `IN` when on the right side there is a Tuple with elements of different types also changed. Examples: + +`1 IN (2, 3, NULL) = NULL (was Just(False))` +`NULL IN () = Just(False) (was NULL)` +`(1, null) IN ((2, 2), (3, 3)) = Just(False) (was NULL)` + +For more information about the `IN` behavior when operands include `NULL`s, see [here](expressions.md#in). You can explicitly select the old behavior by specifying the pragma `DisableAnsiInForEmptyOrNullableItemsCollections`. If no pragma is set, then a warning is issued and the old version works. + +### AnsiRankForNullableKeys + +| Value type | Default | +| --- | --- | +| Flag | false | + +Aligns the RANK/DENSE_RANK behavior with the standard if there are optional types in the window sort keys or in the argument of such window functions. It means that: + +* The result type is always Uint64 rather than Uint64?. +* NULLs in keys are treated as equal to each other (the current implementation returns NULL). + +You can explicitly select the old behavior by using the `DisableAnsiRankForNullableKeys` pragma. If no pragma is set, then a warning is issued and the old version works. + +### AnsiCurrentRow + +| Value type | Default | +| --- | --- | +| Flag | false | + +Aligns the implicit setting of a window frame with the standard if there is ORDER BY. +If AnsiCurrentRow is not set, then the `(ORDER BY key)` window is equivalent to `(ORDER BY key ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. +The standard also requires that this window behave as `(ORDER BY key RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. +The difference is in how `CURRENT ROW` is interpreted. In `ROWS` mode `CURRENT ROW` is interpreted literally: the current row in a partition. +In `RANGE` mode, the end of the `CURRENT ROW` frame means "the last row in a partition with a sort key equal to the current row". + +### AnsiOrderByLimitInUnionAll + +| Value type | Default | +| --- | --- | +| Flag | false | + +Aligns the UNION ALL behavior with the standard if there is `ORDER BY/LIMIT/DISCARD/INSERT INTO` in the combined subqueries. It means that: + +* `ORDER BY/LIMIT/INSERT INTO` are allowed only after the last subquery. +* `DISCARD` is allowed only before the first subquery. +* The specified operators apply to the `UNION ALL` result (unlike the current behavior when they apply only to the subquery). +* To apply an operator to a subquery, enclose the subquery in parentheses. + +You can explicitly select the old behavior by using the `DisableAnsiOrderByLimitInUnionAll` pragma. If no pragma is set, then a warning is issued and the old version works. + +### OrderedColumns {#orderedcolumns} + +`OrderedColumns`/`DisableOrderedColumns` + +Output the [column order](select/order_by.md) in SELECT/JOIN/UNION ALL and preserve it when writing the results. The order of columns is undefined by default. + +### PositionalUnionAll {#positionalunionall} + +Enable the standard column-by-column execution for [UNION ALL](select/union.md#unionall). This automatically enables +[ordered columns](#orderedcolumns). + +### RegexUseRe2 + +| Value type | Default | +| --- | --- | +| Flag | false | + +Use Re2 UDF instead of Pcre to execute SQL the `REGEX`,`MATCH`,`RLIKE` statements. Re2 UDF can properly handle Unicode characters, unlike the default Pcre UDF. + +### ClassicDivision + +| Value type | Default | +| --- | --- | +| Flag | true | + +In the classical version, the result of integer division remains integer (by default). +If disabled, the result is always Double. +ClassicDivision is a [scoped](pragma.md#pragmascope) setting. + +### UnicodeLiterals + +`UnicodeLiterals`/`DisableUnicodeLiterals` + +| Value type | Default | +| --- | --- | +| Flag | false | + +When this mode is enabled, string literals without suffixes like "foo"/'bar'/@@multiline@@ will be of type `Utf8`, when disabled - `String`. +UnicodeLiterals is a [scoped](pragma.md#pragmascope) setting. + +### WarnUntypedStringLiterals + +`WarnUntypedStringLiterals`/`DisableWarnUntypedStringLiterals` + +| Value type | Default | +| --- | --- | +| Flag | false | + +When this mode is enabled, a warning will be generated for string literals without suffixes like "foo"/'bar'/@@multiline@@. It can be suppressed by explicitly choosing the suffix `s` for the `String` type, or `u` for the `Utf8` type. +WarnUntypedStringLiterals is a [scoped](pragma.md#pragmascope) setting. + +### AllowDotInAlias + +| Value type | Default | +| --- | --- | +| Flag | false | + +Enable dot in names of result columns. This behavior is disabled by default, since the further use of such columns in JOIN is not fully implemented. + +### WarnUnnamedColumns + +| Value type | Default | +| --- | --- | +| Flag | false | + +Generate a warning if a column name was automatically generated for an unnamed expression in `SELECT` (in the format `column[0-9]+`). + +### GroupByLimit + +| Value type | Default | +| --- | --- | +| Positive number | 32 | + +Increasing the limit on the number of dimensions in [GROUP BY](group_by.md). + +{% if feature_group_by_rollup_cube %} + +### GroupByCubeLimit + +| Value type | Default | +| --- | --- | +| Positive number | 5 | + +Increasing the limit on the number of dimensions in [GROUP BY](group_by.md#rollup-cube-group-sets). + +Use this option with care, because the computational complexity of the query grows exponentially with the number of dimensions. + +{% endif %} + + +## Yson + +Managing the default behavior of Yson UDF, for more information, see the [documentation](../udf/list/yson.md) and, in particular, [Yson::Options](../udf/list/yson.md#ysonoptions). + +### `yson.AutoConvert` + +| Value type | Default | +| --- | --- | +| Flag | false | + +Automatic conversion of values to the required data type in all Yson UDF calls, including implicit calls. + +### `yson.Strict` + +| Value type | Default | +| --- | --- | +| Flag | true | + +Strict mode control in all Yson UDF calls, including implicit calls. If the value is omitted or is `"true"`, it enables the strict mode. If the value is `"false"`, it disables the strict mode. + +### `yson.DisableStrict` + +| Value type | Default | +| --- | --- | +| Flag | false | + +An inverted version of `yson.Strict`. If the value is omitted or is `"true"`, it disables the strict mode. If the value is `"false"`, it enables the strict mode. + + + +{% if feature_mapreduce %} + +## Working with files + +### File + +| Value type | Default | Static/
dynamic | +| --- | --- | --- | +| Two string arguments: alias and URL | — | Static | + +Attach a file to the query by URL. For attaching files you can use the built-in functions [FilePath and FileContent](../builtins/basic.md#filecontent). This `PRAGMA` is a universal alternative to attaching files using built-in mechanisms from the [web](../interfaces/web.md#attach) or [console](../interfaces/cli.md#attach) clients. + +YQL reserves the right to cache files at the URL for an indefinite period, hence, if there is a significant change in the content behind it, we strongly recommended to modify the URL by adding/editing dummy parameters. + +### Folder + +| Value type | Default | Static/
dynamic | +| --- | --- | --- | +| Two string arguments: prefix and URL | — | Static | + +Attach a set of files to the query by URL. Works similarly to adding multiple files via [`PRAGMA File`](#file) by direct links to files with aliases obtained by combining a prefix with a file name using `/`. + +### Library + +| Value type | Default | Static/
dynamic | +| --- | --- | --- | +| One or two arguments: the file name and an optional URL | — | Static | + +Treat the specified attached file as a library from which you can do [IMPORT](export_import.md). The syntax type for the library is determined from the file extension: + +* `.sql`: For the YQL dialect of SQL (recommended). +* `.yql`: For [s-expressions](/docs/s_expressions). + +Example with a file attached to the query: + +```yql +PRAGMA library("a.sql"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +If the URL is specified, the library is downloaded from the URL rather than from the pre-attached file as in the following example: + +```yql +PRAGMA library("a.sql","{{ corporate-paste }}/5618566/text"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +In this case, you can use text parameter value substitution in the URL: + +```yql +DECLARE $_ver AS STRING; -- "5618566" +PRAGMA library("a.sql","{{ corporate-paste }}/{$_ver}/text"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +### Package + +| Value type | Default | Static /
dynamic | +| --- | --- | --- | +| Two or three arguments: package name, URL and optional token | — | Static | + +Attach a hierarchical set of files to the query by URL, treating them as a package with a given name - an interconnected set of libraries. + +Package name is expected to be given as ``project_name.package_name``; from package's libraries you can do [IMPORT](export_import.md) with a module name like ``pkg.project_name.package_name.maybe.nested.module.name``. + +Example for a package with flat hierarchy which consists of two libraries - foo.sql and bar.sql: + +```yql +PRAGMA package("project.package", "{{ corporate-yt }}/{{ corporate-yt-cluster }}/path/to/package"); +IMPORT pkg.project.package.foo SYMBOLS $foo; +IMPORT pkg.project.package.bar SYMBOLS $bar; +SELECT $foo, $bar; +``` + +You can also use text parameter value substitution in the URL: + +```yql +DECLARE $_path AS STRING; -- "path" +PRAGMA package("project.package","{{ corporate-yt }}/{{ corporate-yt-cluster }}/{$_path}/to/package"); +IMPORT pkg.project.package.foo SYMBOLS $foo; +IMPORT pkg.project.package.bar SYMBOLS $bar; +SELECT $foo, $bar; +``` + +### OverrideLibrary + +| Value type | Default | Static/
dynamic | +| --- | --- | --- | +| One argument: the file name | — | Static | + +Treat the specified attached file as a library and override with it one of package's libraries. + +File name is expected to be given as ``project_name/package_name/maybe/nested/module/name.EXTENSION``, extensions analagous to [PRAGMA Library](#library) are supported. + +Example: + +```yql +PRAGMA package("project.package", "{{ corporate-yt }}/{{ corporate-yt-cluster }}/path/to/package"); +PRAGMA override_library("project/package/maybe/nested/module/name.sql"); + +IMPORT pkg.project.package.foo SYMBOLS $foo; +SELECT $foo; +``` + +{% endif %} + + +{% if tech %} + +## YDB + +### `ydb.CostBasedOptimizationLevel` {#costbasedoptimizationlevel} + +| Level | Description | +| ----- | ------------------------ | +| 0 | Cost-based optimizer is disabled. | +| 1 | Cost-based optimizer is disabled, but estimates are computed and available. | +| 2 | Cost-based optimizer is enabled only for queries that include [column-oriented tables](../concepts/glossary.md#column-oriented-table). | +| 3 | Cost-based optimizer is enabled for all queries, but `LookupJoin` is preferred for row-oriented tables. | +| 4 | Cost-based optimizer is enabled for all queries. | + +### `kikimr.IsolationLevel` + +| Value type | Default | +| --- | --- | +| Serializable, ReadCommitted, ReadUncommitted, or ReadStale. | Serializable | + +An experimental pragma that allows you to reduce the isolation level of the current YDB transaction. + +{% endif %} + + + +{% if tech %} + +## Debugging and auxiliary settings {#debug} + +{% if feature_webui %} + +### `DirectRead` + +| Value type | Default | +| --- | --- | +| Flag | false | + +An auxiliary setting for previewing tables in the [HTTP API](../interfaces/http.md) (both for the web interface and console client). +{% endif %} + +### `config.flags("ValidateUdf", "Lazy")` + +| Value type | Default | +| --- | --- | +| String: None/Lazy/Greedy | None | + +Validating whether UDF results match the declared signature. The Greedy mode enforces materialization of lazy containers, although the Lazy mode doesn't. + +### `{{ backend_name_lower }}.DefaultCluster` + +| Value type | Default | +| --- | --- | +| A string with the cluster name | hahn | + +Selecting a cluster for calculations that don't access tables. + +### `config.flags("Diagnostics")` + +| Value type | Default | +| --- | --- | +| Flag | false | + +Getting diagnostic information from YQL as an additional result of a query. + +{% endif %} + + diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/process.md b/ydb/docs/en/core/yql/reference/syntax/process.md similarity index 83% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/process.md rename to ydb/docs/en/core/yql/reference/syntax/process.md index 7ef4424f9a87..5fa2f57c5ec8 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/process.md +++ b/ydb/docs/en/core/yql/reference/syntax/process.md @@ -1,8 +1,8 @@ # {{ process_command }} -Convert the input table using a UDF in [C++](../../udf/cpp.md){% if yt %}, [Python](../../udf/python.md) or [JavaScript](../../udf/javascript.md){% endif %} or a [lambda function](../../syntax/expressions.md#lambda) that is applied sequentially to each input row and can create zero to create one or more result row for each input row (similarly to Map in MapReduce terms). +Convert the input table using a UDF in [C++](../udf/cpp.md){% if yt %}, [Python](../udf/python.md) or [JavaScript](../udf/javascript.md){% endif %} or a [lambda function](expressions.md#lambda) that is applied sequentially to each input row and can create zero to create one or more result row for each input row (similarly to Map in MapReduce terms). -{% if feature_mapreduce %}The table is searched by name in the database specified by the [USE](../use.md) operator.{% endif %} +{% if feature_mapreduce %}The table is searched by name in the database specified by the [USE](use.md) operator.{% endif %} The parameters of the function call after the `USING` keyword explicitly specify the values of columns from which to pass values for each input row and in which order. @@ -17,7 +17,7 @@ Regardless of the option selected above, the result is converted to a flat table As `OutputType`, you can use one of the types: * `Struct<...>`: `{{ process_command }}` has exactly one output with entries of a given structure that is a flat table with columns corresponding to the fields `Struct<...>` -* `Variant,...>`: `{{ process_command }}` will have the number of outputs equal to the number of variants in `Variant`. The entries of each output are represented by a flat table with columns based on fields from the relevant variant. In this case, you can access the set of `{{ process_command }}` outputs as a `Tuple` of lists that can be unpacked into separate [named expressions](../expressions.md#named-nodes) and used independently. +* `Variant,...>`: `{{ process_command }}` will have the number of outputs equal to the number of variants in `Variant`. The entries of each output are represented by a flat table with columns based on fields from the relevant variant. In this case, you can access the set of `{{ process_command }}` outputs as a `Tuple` of lists that can be unpacked into separate [named expressions](expressions.md#named-nodes) and used independently. In the list of function arguments after the `USING` keyword, you can pass one of the two special named expressions: @@ -26,13 +26,13 @@ In the list of function arguments after the `USING` keyword, you can pass one of {% note info %} -After executing `{{ process_command }}`, within the same query, on the resulting table (or tables), you can perform {% if select_command != "SELECT STREAM" %}[SELECT](../select.md), [REDUCE](../reduce.md){% else %}[SELECT STREAM](../select_stream.md){% endif %}, [INSERT INTO](../insert_into.md), other `{{ process_command }}` and so on, depending on the intended result. +After executing `{{ process_command }}`, within the same query, on the resulting table (or tables), you can perform {% if select_command != "SELECT STREAM" %}[SELECT](select/index.md), [REDUCE](reduce.md){% else %}[SELECT STREAM](select_stream.md){% endif %}, [INSERT INTO](insert_into.md), other `{{ process_command }}` and so on, depending on the intended result. {% endnote %} The `USING` keyword and the function are optional: if you omit them, the source table is returned. {% if feature_subquery %}This can be convenient for using a [subquery template](subquery.md).{% endif %} -In `{{ process_command }}` you can pass multiple inputs (the input here means a table,{% if select_command != "PROCESS STREAM" %} a [range of tables](../select.md#range){% endif %}, a subquery, a [named expression](../expressions.md#named-nodes)), separated by commas. To the function from `USING`, you can only pass in this case special named expressions `TableRow()` or `TableRows()` that will have the following type: +In `{{ process_command }}` you can pass multiple inputs (the input here means a table,{% if select_command != "PROCESS STREAM" %} a [range of tables](select/concat.md){% endif %}, a subquery, a [named expression](expressions.md#named-nodes)), separated by commas. To the function from `USING`, you can only pass in this case special named expressions `TableRow()` or `TableRows()` that will have the following type: * `TableRow()`: A `Variant` where each element has an entry structure type from the relevant input. For each input row in the Variant, the element corresponding to the occurrence ID for this row is non-empty * `TableRows()`: A lazy iterator by Variants, in terms of the types `Stream>`. The alternative has the same semantics as for `TableRow()` @@ -123,4 +123,4 @@ $p = (PROCESS STREAM Input USING $f2(TableRows())); SELECT STREAM * FROM $p; ``` -{% endif %} \ No newline at end of file +{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/reduce.md b/ydb/docs/en/core/yql/reference/syntax/reduce.md similarity index 85% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/reduce.md rename to ydb/docs/en/core/yql/reference/syntax/reduce.md index 44b3443ddea2..e7c579c7ee5b 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/reduce.md +++ b/ydb/docs/en/core/yql/reference/syntax/reduce.md @@ -4,7 +4,7 @@ Groups the input by the specified key columns, then passes the current keys and Keywords that can follow: -* `PRESORT` (optional): Specifying the order within each group, the syntax is similar to [ORDER BY](../select.md#orderby); +* `PRESORT` (optional): Specifying the order within each group, the syntax is similar to [ORDER BY](select/order_by.md); * `ON` (required): Specifying key columns. * `USING` or `USING ALL` (required): A UDF call, see more about the rules below. @@ -22,9 +22,9 @@ Rules for passing UDF arguments: * The key to be passed to the UDF follows the rule below. If there is only one key column, then only its value is used in the key. If there are multiple columns (columns are listed similarly to `GROUP BY` separated by commas), then the key is a `Tuple` with values from the listed columns in the specified order. * When you call `REDUCE` from a query, only the expression whose values will be passed as iterator items follows the UDF name in parentheses (the second UDF argument for `USING` or the second item of the tuple for `USING ALL`). -The result is built in the same way as for [PROCESS](../process.md). You can also use the `TableRow()` keyword to get the whole string as a structure. +The result is built in the same way as for [PROCESS](process.md). You can also use the `TableRow()` keyword to get the whole string as a structure. -In `REDUCE`, you can pass multiple inputs (the input here means a table, a [range of tables](../select.md#range), a subquery, a [named expression](../expressions.md#named-nodes)), separated by commas. All inputs must have the key columns of the matching type specified in `ON`. To the function from `USING` in this case, you can only pass a special named expression `TableRow()`. The second argument (or the second element of the tuple for `USING ALL`) will include a lazy iterator over variants with a populated element that corresponds to the occurrence ID for the current entry. +In `REDUCE`, you can pass multiple inputs (the input here means a table, a [range of tables](select/concat.md), a subquery, a [named expression](expressions.md#named-nodes)), separated by commas. All inputs must have the key columns of the matching type specified in `ON`. To the function from `USING` in this case, you can only pass a special named expression `TableRow()`. The second argument (or the second element of the tuple for `USING ALL`) will include a lazy iterator over variants with a populated element that corresponds to the occurrence ID for the current entry. After `USING`, in `REDUCE` you can optionally specify `ASSUME ORDER BY` with a list of columns. The result of such a `REDUCE` statement is treated as sorted, but without actually running a sort. Sort check is performed at the query execution stage. It supports setting the sort order using the keywords `ASC` (ascending order) and `DESC` (descending order). Expressions are not supported in `ASSUME ORDER BY`. @@ -93,7 +93,7 @@ $udf = Python::MyReducer(Callable<( $script ); -REDUCE hahn.`home/yql/tutorial/users` +REDUCE my_table ON region USING $udf((name, last_visit_time)); ``` diff --git a/ydb/docs/en/core/yql/reference/syntax/replace_into.md b/ydb/docs/en/core/yql/reference/syntax/replace_into.md new file mode 100644 index 000000000000..a7235c96b7ff --- /dev/null +++ b/ydb/docs/en/core/yql/reference/syntax/replace_into.md @@ -0,0 +1,50 @@ +# REPLACE INTO + +{% if oss == true and backend_name == "YDB" %} + +{% note warning %} + +Supported only for [row-oriented](../../../concepts/datamodel/table.md#row-oriented-tables) tables. Support for [column-oriented](../../../concepts/datamodel/table.md#column-oriented-tables) tables is currently under development. + +{% if oss %} + +Available methods for loading data into columnar tables: + +* [{{ ydb-short-name }} CLI](../../../reference/ydb-cli/export-import/import-file.md) +* [Bulk data upsert](../../../recipes/ydb-sdk/bulk-upsert.md) +* [Yandex Data Transfer](https://yandex.cloud/ru/services/data-transfer) + +{% endif %} + +{% endnote %} + +{% endif %} + +Saves data to a table, overwriting the rows based on the primary key.{% if feature_mapreduce %} The table is searched by name in the database specified by the [USE](use.md) operator.{% endif %} If the given primary key is missing, a new row is added to the table. If the given `PRIMARY_KEY` exists, the row is overwritten. The values of columns not involved in the operation are replaced by their default values. + +{% note info %} + +Unlike [`INSERT INTO`](insert_into.md) and [`UPDATE`](update.md), the queries [`UPSERT INTO`](upsert_into.md) and `REPLACE INTO` don't need to pre-fetch the data, hence they run faster. + +{% endnote %} + +## Examples + +* Setting values for `REPLACE INTO` using `VALUES`. + + ```yql + REPLACE INTO my_table (Key1, Key2, Value2) VALUES + (1u, "One", 101), + (2u, "Two", 102); + COMMIT; + ``` + +* Fetching values for `REPLACE INTO` using a `SELECT`. + + ```yql + REPLACE INTO my_table + SELECT Key AS Key1, "Empty" AS Key2, Value AS Value1 + FROM my_table1; + COMMIT; + ``` + diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/revoke.md b/ydb/docs/en/core/yql/reference/syntax/revoke.md similarity index 96% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/revoke.md rename to ydb/docs/en/core/yql/reference/syntax/revoke.md index 349fb30b8753..820b51aac864 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/revoke.md +++ b/ydb/docs/en/core/yql/reference/syntax/revoke.md @@ -14,7 +14,7 @@ REVOKE [GRANT OPTION FOR] {{permission_name} [, ...] | ALL [PRIVILEGES]} ON {pat `GRANT OPTION FOR` - using this clause revokes the right to manage access rights from the user or group. All rights previously granted by this user remain in effect. The clause functions similarly to revoking the `"ydb.access.grant"` right or `GRANT`. -{% include [x](_includes/permissions/permissions_list.md) %} +{% include [x](../_includes/permissions_list.md) %} ## Examples diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/assume_order_by.md b/ydb/docs/en/core/yql/reference/syntax/select/assume_order_by.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/assume_order_by.md rename to ydb/docs/en/core/yql/reference/syntax/select/assume_order_by.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/functional_tables.md b/ydb/docs/en/core/yql/reference/syntax/select/concat.md similarity index 72% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/functional_tables.md rename to ydb/docs/en/core/yql/reference/syntax/select/concat.md index 1b6a481e3d63..efe854596fc9 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/functional_tables.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/concat.md @@ -1,6 +1,6 @@ ## Accessing multiple tables in a single query {#concat} {#each} {#range} {#like} {#filter} {#regexp} -Standard SQL uses [UNION ALL](../../select/union.md#unionall) to execute a query across multiple tables and combine the results of two or more `SELECT` statements. This is not very convenient for the use case of running the same query on multiple tables (for example, if they contain data for different dates). To make this more convenient, in YQL `SELECT` statements, after `FROM`, you can specify not only a table or a subquery, but also call built-in functions letting you combine data from multiple tables. +Standard SQL uses [UNION ALL](union.md#uniona-ll) to execute a query across multiple tables and combine the results of two or more `SELECT` statements. This is not very convenient for the use case of running the same query on multiple tables (for example, if they contain data for different dates). To make this more convenient, in YQL `SELECT` statements, after `FROM`, you can specify not only a table or a subquery, but also call built-in functions letting you combine data from multiple tables. The following functions are defined for these purposes: @@ -14,9 +14,9 @@ The following functions are defined for these purposes: * min, max: These two arguments specify a range of table names included. The range is inclusive on both ends. If no range is specified, all tables in the prefix folder are used. The names of tables or folders located in the folder specified in prefix are lexicographically matched with the `[min, max]` range rather than concatenated, so make sure to specify the range without leading slashes. * suffix is the name of the table. It's expected without a leading slash. If no suffix is specified, then the `[min, max]` arguments specify a range of table names. If the suffix is specified, then the `[min, max]` arguments specify a range of folders hosting a table with the name specified in the suffix argument. -```LIKE(`prefix`, `pattern`, `suffix`, `view`)``` and ```REGEXP(`prefix`, `pattern`, `suffix`, `view`)```: The pattern argument is specified in the format similar to the binary operators of the same name: [LIKE](../../expressions.md#like) and [REGEXP](../../expressions.md#regexp). +```LIKE(`prefix`, `pattern`, `suffix`, `view`)``` and ```REGEXP(`prefix`, `pattern`, `suffix`, `view`)```: The pattern argument is specified in the format similar to the binary operators of the same name: [LIKE](../expressions.md#like) and [REGEXP](../expressions.md#regexp). -```FILTER(`prefix`, `callable`, `suffix`, `view`)```: The `callable` argument must be a callable expression with the `(String)->Bool` signature that will be called for each table/subdirectory in the prefix folder. The query will only include those tables for which the callable value returned `true`. It is most convenient to use, as callable values, [lambda functions](../../expressions.md#lambda){% if yql == true %} or user-defined functions (UDF) written in [Python](../../../udf/python.md) or [JavaScript](../../../udf/javascript.md){% endif %}. +```FILTER(`prefix`, `callable`, `suffix`, `view`)```: The `callable` argument must be a callable expression with the `(String)->Bool` signature that will be called for each table/subdirectory in the prefix folder. The query will only include those tables for which the callable value returned `true`. It is most convenient to use, as callable values, [lambda functions](../expressions.md#lambda){% if yql == true %} or user-defined functions (UDF) written in [Python](../../udf/python.md) or [JavaScript](../../udf/javascript.md){% endif %}. {% note warning %} @@ -26,13 +26,13 @@ The list of tables is calculated **before** executing the query. Therefore, the {% endnote %} -By default, the schemas of all the unioned tables are combined using the [UNION ALL](#unionall) rules. If you don't want to combine schemas, then you can use functions with the `_STRICT` suffix, for example `CONCAT_STRICT` or `RANGE_STRICT` that are totally similar to the original functions, but treat any difference in table schemas as an error. +By default, the schemas of all the unioned tables are combined using the [UNION ALL](union.md#union-all) rules. If you don't want to combine schemas, then you can use functions with the `_STRICT` suffix, for example `CONCAT_STRICT` or `RANGE_STRICT` that are totally similar to the original functions, but treat any difference in table schemas as an error. To specify a cluster of unioned tables, add it before the function name. -All arguments of the functions described above can be declared separately using [named expressions](../../expressions.md#named-nodes). In this case, you can also use simple expressions in them by implicitly calling [EvaluateExpr](../../../builtins/basic.md#evaluate_expr_atom). +All arguments of the functions described above can be declared separately using [named expressions](../expressions.md#named-nodes). In this case, you can also use simple expressions in them by implicitly calling [EvaluateExpr](../../builtins/basic.md#evaluate_expr_atom). -To get the name of the source table from which you originally obtained each row, use [TablePath()](../../../builtins/basic.md#tablepath). +To get the name of the source table from which you originally obtained each row, use [TablePath()](../../builtins/basic.md#tablepath). ### Examples diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/distinct.md b/ydb/docs/en/core/yql/reference/syntax/select/distinct.md similarity index 66% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/distinct.md rename to ydb/docs/en/core/yql/reference/syntax/select/distinct.md index e21840d1bd09..ae3eec368563 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/distinct.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/distinct.md @@ -4,7 +4,7 @@ Selecting unique rows. {% note info %} -Applying `DISTINCT` to calculated values is not currently implemented. For this purpose, use a subquery or the clause [`GROUP BY ... AS ...`](../../group_by.md). +Applying `DISTINCT` to calculated values is not currently implemented. For this purpose, use a subquery or the clause [`GROUP BY ... AS ...`](../group_by.md). {% endnote %} @@ -15,5 +15,5 @@ SELECT DISTINCT value -- only unique values from the table FROM my_table; ``` -The `DISTINCT` keyword can also be used to apply [aggregate functions](../../../builtins/aggregation.md) only to distinct values. For more information, see the documentation for [GROUP BY](../../group_by.md). +The `DISTINCT` keyword can also be used to apply [aggregate functions](../../builtins/aggregation.md) only to distinct values. For more information, see the documentation for [GROUP BY](../group_by.md). diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/folder.md b/ydb/docs/en/core/yql/reference/syntax/select/folder.md similarity index 76% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/folder.md rename to ydb/docs/en/core/yql/reference/syntax/select/folder.md index 36755df5d5c7..d59330255db2 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/folder.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/folder.md @@ -1,6 +1,6 @@ ## Listing the contents of a directory in a cluster {#folder} -It's expressed as the `FOLDER` function in [FROM](../../select/from.md). +It's expressed as the `FOLDER` function in [FROM](from.md). Arguments: @@ -15,9 +15,9 @@ The result is a table with three fixed columns: Recommendations for use: -* To get only a list of tables, make sure to add `...WHERE Type == "table"`. Then, by optionally adding more conditions, you can use the aggregate function [AGGREGATE_LIST](../../../builtins/aggregation.md#aggregate-list) from the Path column to get only a list of paths and pass them to [EACH](#each). -* Since the Path column is output in the same format as the result of the function [TablePath()](../../../builtins/basic.md#tablepath), then they can be used to JOIN table attributes to its rows. -* We recommend that you work with the Attributes column using [Yson UDF](../../../udf/list/yson.md). +* To get only a list of tables, make sure to add `...WHERE Type == "table"`. Then, by optionally adding more conditions, you can use the aggregate function [AGGREGATE_LIST](../../builtins/aggregation.md#aggregate-list) from the Path column to get only a list of paths and pass them to [EACH](concat.md#each). +* Since the Path column is output in the same format as the result of the function [TablePath()](../../builtins/basic.md#tablepath), then they can be used to JOIN table attributes to its rows. +* We recommend that you work with the Attributes column using [Yson UDF](../../udf/list/yson.md). {% note warning %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/from.md b/ydb/docs/en/core/yql/reference/syntax/select/from.md similarity index 54% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/from.md rename to ydb/docs/en/core/yql/reference/syntax/select/from.md index d31fb57d22c2..a031bbd5adf3 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/from.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/from.md @@ -1,8 +1,8 @@ ## FROM {#from} -Data source for `SELECT`. The argument can accept the table name, the result of another `SELECT`, or a [named expression](../../expressions.md#named-nodes). Between `SELECT` and `FROM`, list the comma-separated column names from the source (or `*` to select all columns). +Data source for `SELECT`. The argument can accept the table name, the result of another `SELECT`, or a [named expression](../expressions.md#named-nodes). Between `SELECT` and `FROM`, list the comma-separated column names from the source (or `*` to select all columns). -{% if feature_mapreduce %}The table is searched by name in the database specified by the operator [USE](../../use.md).{% endif %} +{% if feature_mapreduce %}The table is searched by name in the database specified by the operator [USE](../use.md).{% endif %} ### Examples diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/from_as_table.md b/ydb/docs/en/core/yql/reference/syntax/select/from_as_table.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/from_as_table.md rename to ydb/docs/en/core/yql/reference/syntax/select/from_as_table.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/from_select.md b/ydb/docs/en/core/yql/reference/syntax/select/from_select.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/from_select.md rename to ydb/docs/en/core/yql/reference/syntax/select/from_select.md diff --git a/ydb/docs/en/core/yql/reference/syntax/select/index.md b/ydb/docs/en/core/yql/reference/syntax/select/index.md new file mode 100644 index 000000000000..b7fa9a14a216 --- /dev/null +++ b/ydb/docs/en/core/yql/reference/syntax/select/index.md @@ -0,0 +1,162 @@ + + +# SELECT + +Returns the result of evaluating the expressions specified after `SELECT`. + +It can be used in combination with other operations to obtain other effect. + +## Examples + +```yql +SELECT "Hello, world!"; +``` + +```yql +SELECT 2 + 2; +``` + + + +## SELECT execution procedure {#selectexec} + +The `SELECT` query result is calculated as follows: + +* Determine the set of input tables by evaluating the [FROM](from.md) clauses. +* Apply [SAMPLE](sample.md)/[TABLESAMPLE](sample.md) to input tables. +* Execute [FLATTEN COLUMNS](../flatten.md#flatten-columns) or [FLATTEN BY](../flatten.md); aliases set in `FLATTEN BY` become visible after this point. + +{% if feature_join %} + +* Execute every [JOIN](../join.md). + +{% endif %} + +* Add to (or replace in) the data the columns listed in [GROUP BY ... AS ...](../group_by.md). +* Execute [WHERE](where.md) — Discard all the data mismatching the predicate. +* Execute [GROUP BY](../group_by.md), evaluate aggregate functions. +* Apply the filter [HAVING](../group_by.md#having). + +{% if feature_window_functions %} + +* Evaluate [window functions](../window.md); + +{% endif %} + +* Evaluate expressions in `SELECT`. +* Assign names set by aliases to expressions in `SELECT`. +* Apply top-level [DISTINCT](distinct.md) to the resulting columns. +* Execute similarly every subquery inside [UNION ALL](union.md#union_all), combine them (see [PRAGMA AnsiOrderByLimitInUnionAll](../pragma.md#pragmas)). +* Perform sorting with [ORDER BY](order_by.md). +* Apply [OFFSET and LIMIT](limit_offset.md) to the result. + + + +## Column order in YQL {#orderedcolumns} + +The standard SQL is sensitive to the order of columns in projections (that is, in `SELECT`). While the order of columns must be preserved in the query results or when writing data to a new table, some SQL constructs use this order. +This applies, for example, to [UNION ALL](union.md#union_all) and positional [ORDER BY](order_by.md) (ORDER BY ordinal). + +The column order is ignored in YQL by default: + +* The order of columns in the output tables and query results is undefined +* The data scheme of the `UNION ALL` result is output by column names rather than positions + +If you enable `PRAGMA OrderedColumns;`, the order of columns is preserved in the query results and is derived from the order of columns in the input tables using the following rules: + +* `SELECT`: an explicit column enumeration dictates the result order. +* `SELECT` with an asterisk (`SELECT * FROM ...`) inherits the order from its input. + +{% if feature_join %} + +* The order of columns after [JOIN](../join.md): First output the left-hand columns, then the right-hand ones. If the column order in any of the sides in the `JOIN` output is undefined, the column order in the result is also undefined. + +{% endif %} + +* The order in `UNION ALL` depends on the [UNION ALL](union.md#union_all) execution mode. +* The column order for [AS_TABLE](from_as_table.md) is undefined. + +{% note warning %} + +In the YT table schema, key columns always precede non-key columns. The order of key columns is determined by the order of the composite key. +When `PRAGMA OrderedColumns;` is enabled, non-key columns preserve their output order. + +{% endnote %} + + + +### Combining queries {#combining-queries} + +Results of several SELECT statements (or subqueries) can be combined using `UNION` and `UNION ALL` keywords. + +```yql +query1 UNION [ALL] query2 (UNION [ALL] query3 ...) +``` + +Union of more than two queries is interpreted as a left-associative operation, that is + +```yql +query1 UNION query2 UNION ALL query3 +``` + +is interpreted as + +```yql +(query1 UNION query2) UNION ALL query3 +``` + +If the underlying queries have one of the `ORDER BY/LIMIT/DISCARD/INTO RESULT` operators, the following rules apply: + +* `ORDER BY/LIMIT/INTO RESULT` is only allowed after the last query +* `DISCARD` is only allowed before the first query +* the operators apply to the `UNION [ALL]` as a whole, instead of referring to one of the queries +* to apply the operator to one of the queries, enclose the query in parantheses + + +## Clauses supported in SELECT + +* [FROM](from.md) +* [FROM AS_TABLE](from_as_table.md) +* [FROM SELECT](from_select.md) +* [DISTINCT](distinct.md) +* [UNIQUE DISTINCT](unique_distinct_hints.md) +* [UNION](union.md) +* [WITH](with.md) +* [WITHOUT](without.md) +* [WHERE](where.md) +* [ORDER BY](order_by.md) +* [ASSUME ORDER BY](assume_order_by.md) +* [LIMIT OFFSET](limit_offset.md) +* [SAMPLE](sample.md) +* [TABLESAMPLE](sample.md) + +{% if yt %} + +* [FOLDER](folder.md) +* [WalkFolders](walk_folders.md) + +{% endif %} + +{% if feature_mapreduce %} + +* [VIEW](view.md) + +{% endif %} + +{% if feature_temp_table %} + +* [TEMPORARY TABLE](temporary_table.md) + +{% endif %} + +{% if feature_bulk_tables %} + +* [CONCAT](concat.md) + +{% endif %} + +{% if feature_secondary_index %} + +* [VIEW INDEX](secondary_index.md) + +{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/limit_offset.md b/ydb/docs/en/core/yql/reference/syntax/select/limit_offset.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/limit_offset.md rename to ydb/docs/en/core/yql/reference/syntax/select/limit_offset.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/order_by.md b/ydb/docs/en/core/yql/reference/syntax/select/order_by.md similarity index 90% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/order_by.md rename to ydb/docs/en/core/yql/reference/syntax/select/order_by.md index 2bb0997ede08..ac76a35e9686 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/order_by.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/order_by.md @@ -19,6 +19,6 @@ ORDER BY key DESC, LENGTH(string_column) ASC; {% if feature_window_functions %} -You can also use `ORDER BY` for [window functions](../../window.md). +You can also use `ORDER BY` for [window functions](../window.md). {% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/sample.md b/ydb/docs/en/core/yql/reference/syntax/select/sample.md similarity index 90% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/sample.md rename to ydb/docs/en/core/yql/reference/syntax/select/sample.md index 1bfd8157361b..83116a0cee67 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/sample.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/sample.md @@ -2,7 +2,15 @@ {% if oss == true and backend_name == "YDB" %} -{% include [olap_warning_note](../../../../../_includes/not_allow_for_olap_note.md) %} +{% if oss == true and backend_name == "YDB" %} + +{% note warning %} + +{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} + +{% endnote %} + +{% endif %} {% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/secondary_index.md b/ydb/docs/en/core/yql/reference/syntax/select/secondary_index.md similarity index 68% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/secondary_index.md rename to ydb/docs/en/core/yql/reference/syntax/select/secondary_index.md index 69089b6a297f..79922d18b440 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/secondary_index.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/secondary_index.md @@ -2,7 +2,15 @@ {% if oss == true and backend_name == "YDB" %} -{% include [olap_warning_note](../../../../../_includes/not_allow_for_olap_note.md) %} +{% if oss == true and backend_name == "YDB" %} + +{% note warning %} + +{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} + +{% endnote %} + +{% endif %} {% endif %} @@ -24,7 +32,7 @@ SELECT * WHERE views >= someValue ``` -* [`JOIN`](../../join.md) the `series` and `users` row-oriented tables on the `userName` field using the `users_index` and `name_index` indexes, respectively: +* [`JOIN`](../join.md) the `series` and `users` row-oriented tables on the `userName` field using the `users_index` and `name_index` indexes, respectively: ```yql SELECT t1.series_id, t1.title diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/temporary_table.md b/ydb/docs/en/core/yql/reference/syntax/select/temporary_table.md similarity index 93% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/temporary_table.md rename to ydb/docs/en/core/yql/reference/syntax/select/temporary_table.md index 9d66b7befc99..6142c9f18e83 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/temporary_table.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/temporary_table.md @@ -19,7 +19,7 @@ UNION ALL SELECT * FROM @my_temp_table WHERE value = "456"; ``` -Temporary table names can use [named expressions](../../expressions.md#named-nodes): +Temporary table names can use [named expressions](../expressions.md#named-nodes): ```yql $tmp_name = "my_temp_table"; diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/toc_i.yaml b/ydb/docs/en/core/yql/reference/syntax/select/toc_i.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/select/toc_i.yaml rename to ydb/docs/en/core/yql/reference/syntax/select/toc_i.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/toc_p.yaml b/ydb/docs/en/core/yql/reference/syntax/select/toc_p.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/select/toc_p.yaml rename to ydb/docs/en/core/yql/reference/syntax/select/toc_p.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/union_all.md b/ydb/docs/en/core/yql/reference/syntax/select/union.md similarity index 58% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/union_all.md rename to ydb/docs/en/core/yql/reference/syntax/select/union.md index 87a4b7d3ce40..4a150ec41028 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/union_all.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/union.md @@ -1,12 +1,40 @@ +# Combining subquery results (UNION) + +{% if oss == true and backend_name == "YDB" %} + +{% include [olap_warning_note](../../../../_includes/not_allow_for_olap_note.md) %} + +{% endif %} + +## UNION {#union} + +Union of the results of the underlying queries, with duplicates removed. +Behavior is identical to using `UNION ALL` followed by `SELECT DISTINCT *`. +Refer to [UNION ALL](#union-all) for more details. + +### Examples + +```yql +SELECT key FROM T1 +UNION +SELECT key FROM T2 -- returns the set of distinct keys in the tables +``` + + ## UNION ALL {#union-all} Concatenating results of multiple `SELECT` statements (or subqueries). -Two `UNION ALL` modes are supported: by column names (the default mode) and by column positions (corresponds to the ANSI SQL standard and is enabled by the [PRAGMA](../../pragma.md#positionalunionall)). +Two `UNION ALL` modes are supported: by column names (the default mode) and by column positions (corresponds to the ANSI SQL standard and is enabled by the [PRAGMA](../pragma.md#positionalunionall)). In the "by name" mode, the output of the resulting data schema uses the following rules: -{% include [union all rules](union_all_rules.md) %} +* The resulting table includes all columns that were found in at least one of the input tables. +* If a column wasn't present in all the input tables, then it's automatically assigned the [optional data type](../../types/optional.md) (that can accept `NULL`). +* If a column in different input tables had different types, then the shared type (the broadest one) is output. +* If a column in different input tables had a heterogeneous type, for example, string and numeric, an error is raised. + + The order of output columns in this mode is equal to the largest common prefix of the order of inputs, followed by all other columns in the alphabetic order. If the largest common prefix is empty (for example, if the order isn't specified for one of the inputs), then the output order is undefined. diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/unique_distinct_hints.md b/ydb/docs/en/core/yql/reference/syntax/select/unique_distinct_hints.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/unique_distinct_hints.md rename to ydb/docs/en/core/yql/reference/syntax/select/unique_distinct_hints.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/view.md b/ydb/docs/en/core/yql/reference/syntax/select/view.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/view.md rename to ydb/docs/en/core/yql/reference/syntax/select/view.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/walk_folders.md b/ydb/docs/en/core/yql/reference/syntax/select/walk_folders.md similarity index 94% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/walk_folders.md rename to ydb/docs/en/core/yql/reference/syntax/select/walk_folders.md index 59bc2ac73e25..20a5fa89de21 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/walk_folders.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/walk_folders.md @@ -3,7 +3,7 @@ Iterator over the tree of the target cluster, with the ability to accumulate state, usually a list of paths to tables. For each node's descendants, user—defined functions are called, where the state can be accumulated; attributes and nodes for further traversal can be selected. -Specified as the `WalkFolders` function in the [FROM](../../select/from.md) clause. +Specified as the `WalkFolders` function in the [FROM](from.md) clause. Returns a single column `State` with the same type as `InitialState`. @@ -59,7 +59,7 @@ Optional named parameters: {% note warning %} * WalkFolders can create a significant load on the master. It should be used with caution when dealing with attributes that contain large values (such as schema), and one should avoid traversing subtrees that are large in size and/or depth. Directory listing requests within a single WalkFolders invocation can be executed in parallel; when requesting attributes with large values, you should reduce the number of simultaneous requests using the pragma `yt.BatchListFolderConcurrency`. -* Handlers are executed via [EvaluateExpr](../../../builtins/basic.md#evaluate_expr_atom), which has a limitation on the number of YQL AST nodes. Therefore, it is not possible to use containers of extremely large size in the State. This limitation can be circumvented by either making multiple WalkFolders calls and merging the results, or by serializing the new state into a string without intermediate deserialization (e.g., JSON/Yson lines). +* Handlers are executed via [EvaluateExpr](../../builtins/basic.md#evaluate_expr_atom), which has a limitation on the number of YQL AST nodes. Therefore, it is not possible to use containers of extremely large size in the State. This limitation can be circumvented by either making multiple WalkFolders calls and merging the results, or by serializing the new state into a string without intermediate deserialization (e.g., JSON/Yson lines). * The order of node traversal in the tree is not Depth-First Search (DFS) due to parallel directory listing calls. * InitialState is used for inferring the types of handlers, and it must be specified explicitly. For instance, use `ListCreate(String)` instead of `[]`. @@ -67,7 +67,7 @@ Optional named parameters: Recommendations for usage: -* It's recommended to work with the Attributes column using [Yson UDF](../../../udf/list/yson.md). +* It's recommended to work with the Attributes column using [Yson UDF](../../udf/list/yson.md). * In a single request, the result of the listing for each directory is cached. The same subtree can be quickly traversed again in another WalkFolders call if it's convenient. ## Examples {#examples} @@ -216,4 +216,4 @@ $walkFoldersRes = SELECT * FROM WalkFolders(`initial_folder`, $initialState, $di $_, $paths = Unwrap($walkFoldersRes); SELECT $paths; -``` \ No newline at end of file +``` diff --git a/ydb/docs/en/core/yql/reference/syntax/select/where.md b/ydb/docs/en/core/yql/reference/syntax/select/where.md new file mode 100644 index 000000000000..1c18b4f0c98c --- /dev/null +++ b/ydb/docs/en/core/yql/reference/syntax/select/where.md @@ -0,0 +1,11 @@ +# WHERE + +Filtering rows in the `SELECT` result based on a condition in {% if backend_name == "YDB" %}[row-oriented](../../../../concepts/datamodel/table.md#row-oriented-tables) or [column-oriented](../../../../concepts/datamodel/table.md#column-oriented-tables){% else %} tables{% endif %}. + +## Example + +```yql +SELECT key FROM my_table +WHERE value > 0; +``` + diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/with.md b/ydb/docs/en/core/yql/reference/syntax/select/with.md similarity index 65% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/with.md rename to ydb/docs/en/core/yql/reference/syntax/select/with.md index 677a24e2d778..85c92331f9da 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/with.md +++ b/ydb/docs/en/core/yql/reference/syntax/select/with.md @@ -1,24 +1,24 @@ # WITH -It's set after the data source in `FROM` and is used for additional hints for {% if backend_name == "YDB" %}row-oriented and column-oriented{% else %} tables{% endif %}. You can't use hints for subqueries and [named expressions](../../expressions.md#named-nodes). +It's set after the data source in `FROM` and is used for additional hints for {% if backend_name == "YDB" %}row-oriented and column-oriented{% else %} tables{% endif %}. You can't use hints for subqueries and [named expressions](../expressions.md#named-nodes). The following values are supported: -* `INFER_SCHEMA`: Sets the flag for output of the table schema. The behavior is similar to the [yt.inferSchema pragma](../../pragma.md#inferschema), but for a specific data source. You can specify the number of rows to output (from 1 to 1000). -* `FORCE_INFER_SCHEMA`: Sets the flag for table schema output. The behavior is similar to the [yt.ForceInferSchema pragma](../../pragma.md#inferschema), but for a specific data source. You can specify the number of rows to output (from 1 to 1000). -* `DIRECT_READ`: Suppresses certain optimizers and enforces accessing table contents as is. The behavior is similar to the debug [pragma DirectRead](../../pragma.md#debug), but for a specific data source. +* `INFER_SCHEMA`: Sets the flag for output of the table schema. The behavior is similar to the [yt.inferSchema pragma](../pragma.md#inferschema), but for a specific data source. You can specify the number of rows to output (from 1 to 1000). +* `FORCE_INFER_SCHEMA`: Sets the flag for table schema output. The behavior is similar to the [yt.ForceInferSchema pragma](../pragma.md#inferschema), but for a specific data source. You can specify the number of rows to output (from 1 to 1000). +* `DIRECT_READ`: Suppresses certain optimizers and enforces accessing table contents as is. The behavior is similar to the debug [pragma DirectRead](../pragma.md#debug), but for a specific data source. * `INLINE`: Hints that the table contents is small and you need to use its in-memory view to process the query. The actual size of the table is not controlled in this case, and if it's large, the query might fail with an out-of-memory error. * `UNORDERED`: Suppresses original table sorting. -* `XLOCK`: Hints that you need to lock the table exclusively. It's useful when you read a table at the stage of processing the [query metaprogram](../../action.md), and then update its contents in the main query. Avoids data loss if an external process managed to change the table between executing a metaprogram phase and the main part of the query. +* `XLOCK`: Hints that you need to lock the table exclusively. It's useful when you read a table at the stage of processing the [query metaprogram](../action.md), and then update its contents in the main query. Avoids data loss if an external process managed to change the table between executing a metaprogram phase and the main part of the query. * `SCHEMA` type: Hints that the specified table schema must be used entirely, ignoring the schema in the metadata. * `COLUMNS` type: Hints that the specified types should be used for columns whose names match the table's column names in the metadata, as well as which columns are additionally present in the table. -* `IGNORETYPEV3`, `IGNORE_TYPE_V3`: Sets the flag to ignore type_v3 types in the table. The behavior is similar to the [yt.IgnoreTypeV3 pragma](../../pragma.md#ignoretypev3), but for a specific data source. +* `IGNORETYPEV3`, `IGNORE_TYPE_V3`: Sets the flag to ignore type_v3 types in the table. The behavior is similar to the [yt.IgnoreTypeV3 pragma](../pragma.md#ignoretypev3), but for a specific data source. -When setting the `SCHEMA` and `COLUMNS` hints, the type must be a [structure](../../../types/containers.md). +When setting the `SCHEMA` and `COLUMNS` hints, the type must be a [structure](../../types/containers.md). {% if feature_bulk_tables %} -If you use the `SCHEMA` hint, then with the table functions [EACH](#each), [RANGE](#range), [LIKE](#like), [REGEXP](#regexp), [FILTER](#filter) you can use an empty list of tables that is treated as an empty table with columns defined in the `SCHEMA`. +If you use the `SCHEMA` hint, then with the table functions [EACH](concat.md#each), [RANGE](concat.md#range), [LIKE](concat.md#like), [REGEXP](concat.md#regexp), [FILTER](concat.md#filter) you can use an empty list of tables that is treated as an empty table with columns defined in the `SCHEMA`. {% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/without.md b/ydb/docs/en/core/yql/reference/syntax/select/without.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/without.md rename to ydb/docs/en/core/yql/reference/syntax/select/without.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select_stream.md b/ydb/docs/en/core/yql/reference/syntax/select_stream.md similarity index 72% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select_stream.md rename to ydb/docs/en/core/yql/reference/syntax/select_stream.md index 75a071b93b1a..c364fedf7134 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select_stream.md +++ b/ydb/docs/en/core/yql/reference/syntax/select_stream.md @@ -35,7 +35,12 @@ WHERE value > 0; Concatenating the results of multiple `SELECT STREAM` statements with their schemas combined by the following rules: -{% include [union all rules](../_includes/select/union_all_rules.md) %} +* The resulting table includes all columns that were found in at least one of the input tables. +* If a column wasn't present in all the input tables, then it's automatically assigned the [optional data type](../types/optional.md) (that can accept `NULL`). +* If a column in different input tables had different types, then the shared type (the broadest one) is output. +* If a column in different input tables had a heterogeneous type, for example, string and numeric, an error is raised. + + ### Examples diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/subquery.md b/ydb/docs/en/core/yql/reference/syntax/subquery.md similarity index 86% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/subquery.md rename to ydb/docs/en/core/yql/reference/syntax/subquery.md index a73a7dfec673..0a5dcdd299af 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/subquery.md +++ b/ydb/docs/en/core/yql/reference/syntax/subquery.md @@ -2,8 +2,8 @@ ## DEFINE SUBQUERY {#define-subquery} -`DEFINE SUBQUERY` lets you declare a subquery template that is a parameterizable block of several top-level expressions (statements), and then use it repeatedly in the `FROM` section of [SELECT](../select.md){% if feature_mapreduce %} statements or as input data in [PROCESS](../process.md)/[REDUCE](../reduce.md){% endif %} with parameters. -As opposed to [actions](../action.md), the subquery template must end with the `SELECT`{% if feature_mapreduce %}/`PROCESS`/`REDUCE`{% endif %} statement whose result is the subquery's return value. Keep in mind that you can't use the top-level `SELECT`{% if feature_mapreduce %}/`PROCESS`/`REDUCE`{% endif %} statement and the modifying expressions (for example, `INSERT`) more than once. +`DEFINE SUBQUERY` lets you declare a subquery template that is a parameterizable block of several top-level expressions (statements), and then use it repeatedly in the `FROM` section of [SELECT](select/index.md){% if feature_mapreduce %} statements or as input data in [PROCESS](process.md)/[REDUCE](reduce.md){% endif %} with parameters. +As opposed to [actions](action.md), the subquery template must end with the `SELECT`{% if feature_mapreduce %}/`PROCESS`/`REDUCE`{% endif %} statement whose result is the subquery's return value. Keep in mind that you can't use the top-level `SELECT`{% if feature_mapreduce %}/`PROCESS`/`REDUCE`{% endif %} statement and the modifying expressions (for example, `INSERT`) more than once. After `DEFINE SUBQUERY`, specify: @@ -19,7 +19,7 @@ One or more of the last subquery parameters can be marked with a question as opt {% note info %} -In large queries, you can use separate files for action definition and include them to the main query using [EXPORT](../export_import.md#export) + [IMPORT](../export_import.md#import) so that instead of one long text you can have several logical parts that are easier to navigate. An important nuance: the `USE my_cluster;` directive in the import query doesn't affect behavior of actions declared in other subquery files. +In large queries, you can use separate files for action definition and include them to the main query using [EXPORT](export_import.md#export) + [IMPORT](export_import.md#import) so that instead of one long text you can have several logical parts that are easier to navigate. An important nuance: the `USE my_cluster;` directive in the import query doesn't affect behavior of actions declared in other subquery files. {% endnote %} @@ -29,7 +29,7 @@ Even if the list of parameters in the subquery template definition is empty, whe {% if feature_mapreduce %} -In some cases, instead of `DEFINE SUBQUERY` it's more convenient to use an equivalent [lambda function](../expressions.md#lambda). +In some cases, instead of `DEFINE SUBQUERY` it's more convenient to use an equivalent [lambda function](expressions.md#lambda). In this case, the lambda function must accept, as the first argument, the special object called `world` that passes dependencies to make certain PRAGMA or COMMIT statements visible at the query template's point of use. Also, make sure to pass this object as the first argument along with the other arguments (if any) to other query templates, if you use them in your lambda function. The return value of the lambda function must have the structure list type (output table) or a list of variants over a tuple of structures (multiple output tables). In the latter case, the following unpacking is usually used at the query template's point of use: @@ -84,7 +84,7 @@ SELECT * FROM $clean(); -- a: 10, b: 100 {% if feature_mapreduce %} ```yql -USE hahn; +USE my_cluster; DEFINE SUBQUERY $input() as SELECT * FROM `home/yql/tutorial/users`; @@ -106,7 +106,7 @@ SELECT * FROM $myProcess2($input, ($x) -> { RETURN AsList($x, $x) }); ``` ```yql -USE hahn; +USE my_cluster; DEFINE SUBQUERY $runPartition($table) AS $paritionByAge = ($row) -> { @@ -136,7 +136,7 @@ SELECT * FROM $j; These functions combine the results of one or more subquery templates passed by arguments. The number of parameters in such subquery templates must be the same. * `SubqueryExtend` requires matching of subquery schemas. -* `SubqueryUnionAll` follows the same rules as [ListUnionAll](../../builtins/list.md#ListUnionAll). +* `SubqueryUnionAll` follows the same rules as [ListUnionAll](../builtins/list.md#ListUnionAll). * `SubqueryMerge` uses the same constraints as `SubqueryExtend` and also outputs a sorted result if all subqueries have the same sort order. * `SubqueryUnionMerge` uses the same constraints as `SubqueryUnionAll` and also outputs a sorted result if all subqueries have the same sort order. @@ -165,7 +165,7 @@ The functions take the following arguments: They substitute each item from the list into the subquery template as a parameter and then combine the obtained subqueries. * `SubqueryExtendFor` requires matching of subquery schemas. -* `SubqueryUnionAllFor` follows the same rules as [ListUnionAll](../../builtins/list.md#ListUnionAll). +* `SubqueryUnionAllFor` follows the same rules as [ListUnionAll](../builtins/list.md#ListUnionAll). * `SubqueryMergeFor` uses the same constraints as `SubqueryExtendFor` and also outputs a sorted result if all subqueries have the same sort order. * `SubqueryUnionMergeFor` uses the same constraints as `SubqueryUnionAllFor` and also outputs a sorted result if all subqueries have the same sort order. @@ -199,4 +199,4 @@ end define; $sub2 = SubqueryOrderBy($sub, [('x',false), ('y',true)]); PROCESS $sub2(); -``` \ No newline at end of file +``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/toc_i.yaml b/ydb/docs/en/core/yql/reference/syntax/toc_i.yaml similarity index 97% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/toc_i.yaml rename to ydb/docs/en/core/yql/reference/syntax/toc_i.yaml index 834aebd348d9..90ee34ab2f02 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/toc_i.yaml +++ b/ydb/docs/en/core/yql/reference/syntax/toc_i.yaml @@ -20,7 +20,7 @@ items: - { name: COMMIT, href: commit.md } - { name: DECLARE, href: declare.md } - { name: DELETE, href: delete.md, when: feature_map_tables } -- { name: DISCARD, href: discard.md } +- { name: DISCARD, href: discard.md, when: backend_name != "YDB" } - { name: DROP ASYNC REPLICATION, href: drop-async-replication.md, when: feature_async_replication } - { name: DROP GROUP, href: drop-group.md, when: feature_user_and_group } - { name: DROP TABLE, href: drop_table.md } diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/update.md b/ydb/docs/en/core/yql/reference/syntax/update.md similarity index 58% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/update.md rename to ydb/docs/en/core/yql/reference/syntax/update.md index 852676f63e87..9ef2957fea7d 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/update.md +++ b/ydb/docs/en/core/yql/reference/syntax/update.md @@ -4,15 +4,23 @@ {% note warning %} -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} +Supported only for [row-oriented](../../../concepts/datamodel/table.md#row-oriented-tables) tables. Support for [column-oriented](../../../concepts/datamodel/table.md#column-oriented-tables) tables is currently under development. -{% include [ways_add_data_to_olap](../../../../_includes/ways_add_data_to_olap.md) %} +{% if oss %} + +Available methods for loading data into columnar tables: + +* [{{ ydb-short-name }} CLI](../../../reference/ydb-cli/export-import/import-file.md) +* [Bulk data upsert](../../../recipes/ydb-sdk/bulk-upsert.md) +* [Yandex Data Transfer](https://yandex.cloud/ru/services/data-transfer) + +{% endif %} {% endnote %} {% endif %} -Updates the data in the table.{% if feature_mapreduce %} The table is searched by name in the database specified by the [USE](../use.md) operator.{% endif %} After the `SET` keyword, enter the columns where you want to update values and the new values themselves. The list of rows is defined by the `WHERE` clause. If `WHERE` is omitted, the updates are applied to all the rows of the table. +Updates the data in the table.{% if feature_mapreduce %} The table is searched by name in the database specified by the [USE](use.md) operator.{% endif %} After the `SET` keyword, enter the columns where you want to update values and the new values themselves. The list of rows is defined by the `WHERE` clause. If `WHERE` is omitted, the updates are applied to all the rows of the table. `UPDATE` can't change the value of the primary key columns. diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/upsert_into.md b/ydb/docs/en/core/yql/reference/syntax/upsert_into.md similarity index 60% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/upsert_into.md rename to ydb/docs/en/core/yql/reference/syntax/upsert_into.md index d9271099a50c..844e8063ea1c 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/upsert_into.md +++ b/ydb/docs/en/core/yql/reference/syntax/upsert_into.md @@ -4,9 +4,17 @@ {% note warning %} -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} +Supported only for [row-oriented](../../../concepts/datamodel/table.md#row-oriented-tables) tables. Support for [column-oriented](../../../concepts/datamodel/table.md#column-oriented-tables) tables is currently under development. -{% include [ways_add_data_to_olap](../../../../_includes/ways_add_data_to_olap.md) %} +{% if oss %} + +Available methods for loading data into columnar tables: + +* [{{ ydb-short-name }} CLI](../../../reference/ydb-cli/export-import/import-file.md) +* [Bulk data upsert](../../../recipes/ydb-sdk/bulk-upsert.md) +* [Yandex Data Transfer](https://yandex.cloud/ru/services/data-transfer) + +{% endif %} {% endnote %} @@ -16,13 +24,13 @@ UPSERT (which stands for UPDATE or INSERT) updates or inserts multiple rows to a {% if feature_mapreduce %} -The table is searched by name in the database specified by the [USE](../use.md) operator. +The table is searched by name in the database specified by the [USE](use.md) operator. {% endif %} {% if feature_replace %} -`UPSERT` and [`REPLACE`](../replace_into.md) are data modification operations that don't require a prefetch and run faster and cheaper than other operations because of that. +`UPSERT` and [`REPLACE`](replace_into.md) are data modification operations that don't require a prefetch and run faster and cheaper than other operations because of that. {% else %} `UPSERT` is the only data modification operation that doesn't require prefetching and runs faster and cheaper than other operations because of that. diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/use.md b/ydb/docs/en/core/yql/reference/syntax/use.md similarity index 60% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/use.md rename to ydb/docs/en/core/yql/reference/syntax/use.md index 6d68589683cf..b647c733e3b5 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/use.md +++ b/ydb/docs/en/core/yql/reference/syntax/use.md @@ -2,13 +2,13 @@ Specifying the "database". As a rule, one of the {{ backend_name }} clusters is used as a database. This database will be used by default to search for tables whenever the database hasn't been specified explicitly. -If the query doesn't include `USE`, then the cluster must be specified at the beginning of the table path in the format ``` cluster.`path/to/table` ```, for example ```hahn.`home/yql/test` ```. Backticks are used to automatically escape special characters (in this case, slashes). +If the query doesn't include `USE`, then the cluster must be specified at the beginning of the table path in the format ``` cluster.`path/to/table` ```, for example ```cluster.`home/yql/test` ```. Backticks are used to automatically escape special characters (in this case, slashes). -Usually the cluster name is specified explicitly, but you can use an expression for it. For example, this will let you use the parameters declared by [DECLARE](../declare.md). -In this case, `USE` must have the notation `USE yt:$cluster_name`, where `$cluster_name` is the [named expression](../expressions.md#named-nodes) of the `String` type. +Usually the cluster name is specified explicitly, but you can use an expression for it. For example, this will let you use the parameters declared by [DECLARE](declare.md). +In this case, `USE` must have the notation `USE yt:$cluster_name`, where `$cluster_name` is the [named expression](expressions.md#named-nodes) of the `String` type. Alternatively, you can specify the cluster right at the beginning of the table path in the format ```yt:$cluster_name.`path/to/table` ```. -As far as `USE` is concerned, you can add it inside [actions](../action.md){% if feature_subquery %} or [subquery templates](../subquery.md){% endif %}. The value of the current cluster is inherited by declarations of nested actions{% if feature_subquery %} or subqueries{% endif %}. The scope of `USE` is terminated at the end of the action{% if feature_subquery %} or {% endif %} subquery template where it has been declared. +As far as `USE` is concerned, you can add it inside [actions](action.md){% if feature_subquery %} or [subquery templates](subquery.md){% endif %}. The value of the current cluster is inherited by declarations of nested actions{% if feature_subquery %} or subqueries{% endif %}. The scope of `USE` is terminated at the end of the action{% if feature_subquery %} or {% endif %} subquery template where it has been declared. ## Examples diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/values.md b/ydb/docs/en/core/yql/reference/syntax/values.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/values.md rename to ydb/docs/en/core/yql/reference/syntax/values.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/window.md b/ydb/docs/en/core/yql/reference/syntax/window.md similarity index 94% rename from ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/window.md rename to ydb/docs/en/core/yql/reference/syntax/window.md index 5d4554f9a2c0..7c7d9e7df8ef 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/window.md +++ b/ydb/docs/en/core/yql/reference/syntax/window.md @@ -2,7 +2,7 @@ Window functions were introduced in the SQL:2003 standard and expanded in the SQL:2011 standard. They let you run calculations on a set of table rows that are related to the current row in some way. -Unlike [aggregate functions](../../builtins/aggregation.md), window functions don't group rows into one output row: the number of rows in the resulting table is always the same as in the source table. +Unlike [aggregate functions](../builtins/aggregation.md), window functions don't group rows into one output row: the number of rows in the resulting table is always the same as in the source table. If a query contains both aggregate and window functions, grouping is performed and aggregate function values are calculated first. The calculated values of aggregate functions can be used as window function arguments (but not the other way around). @@ -69,7 +69,7 @@ There should be no window function calls in any of the expressions inside the wi If `PARTITION BY` is set, the source table rows are grouped into *partitions*, which are then handled independently of each other. If `PARTITION BY` isn't set, all rows in the source table are put in the same partition. If `ORDER BY` is set, it determines the order of rows in a partition. -Both in `PARTITION BY` and [GROUP BY](../group_by.md) you can use aliases and [SessionWindow](../group_by.md#session-window). +Both in `PARTITION BY` and [GROUP BY](group_by.md) you can use aliases and [SessionWindow](group_by.md#session-window). If `ORDER BY` is omitted, the order of rows in the partition is undefined. @@ -88,7 +88,7 @@ Namely, if there is `ORDER BY`, then `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRE Further, depending on the specific window function, it's calculated either based on the set of rows in the partition or the set of rows in the window frame. -[List of available window functions](../../builtins/window.md) +[List of available window functions](../builtins/window.md) #### Examples diff --git a/ydb/docs/en/core/yql/reference/toc_i.yaml b/ydb/docs/en/core/yql/reference/toc_i.yaml index 5ecab61267fa..9781b330eea1 100644 --- a/ydb/docs/en/core/yql/reference/toc_i.yaml +++ b/ydb/docs/en/core/yql/reference/toc_i.yaml @@ -1,2 +1,9 @@ +title: YQL over {{ backend_name }} +# href: index.md items: -- include: { mode: merge, path: yql-core/toc_m.yaml } +- name: Data types + include: { mode: link, path: types/toc_i.yaml } +- name: Syntax + include: { mode: link, path: syntax/toc_i.yaml } +- name: Built-in functions + include: { mode: link, path: builtins/toc_i.yaml } diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/cast.md b/ydb/docs/en/core/yql/reference/types/cast.md similarity index 96% rename from ydb/docs/en/core/yql/reference/yql-core/types/_includes/cast.md rename to ydb/docs/en/core/yql/reference/types/cast.md index 38d1cdb62199..6136c2f5802d 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/cast.md +++ b/ydb/docs/en/core/yql/reference/types/cast.md @@ -1,4 +1,4 @@ -# Rules for type casting using the operator [CAST](../../syntax/expressions.md#cast) +# Rules for type casting using the operator [CAST](../syntax/expressions.md#cast) ## Rules for casting primitive data types @@ -11,7 +11,7 @@ * If, in a certain combination of the source and target type, casting can't be performed for all possible values of the source type, then, if the casting fails, `CAST` returns `NULL`. In such cases, one `Optional` level is added to the return value type, unless already present. For example, the constructs: `CAST("3.14" AS Float?)` and `CAST("3.14" AS Float)` are fully equivalent and return `Float?`. * If casting is possible for all values of the source type, then adding '?' works the same way as `Just` on top: `CAST(3.14 AS Utf8?)` is same as `Just(CAST(3.14 AS Utf8))`. -All combinations of primitive data types for which `CAST` can be used are described [here](../primitive.md). +All combinations of primitive data types for which `CAST` can be used are described [here](primitive.md). ## Casting rules for containers diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/containers.md b/ydb/docs/en/core/yql/reference/types/containers.md similarity index 81% rename from ydb/docs/en/core/yql/reference/yql-core/types/_includes/containers.md rename to ydb/docs/en/core/yql/reference/types/containers.md index f580c3f02d16..550e825833bf 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/containers.md +++ b/ydb/docs/en/core/yql/reference/types/containers.md @@ -2,7 +2,9 @@ YQL supports container types to define complex data structures organized in various ways. Values of container types can be passed to YQL queries as input parameters or returned from YQL queries as columns of the set of results. +{% if backend_name == "YDB" %} Container types can't be used as column data types for {{ ydb-short-name }} tables. +{% endif %} | Type | Declaration,
example | Description | | ------------ | ---------------- | ------------- | @@ -18,10 +20,10 @@ Container types can't be used as column data types for {{ ydb-short-name }} tabl If necessary, you can nest containers in any combination, for example, `List>`. -In certain contexts, [optional values](../optional.md) can also be considered a container type (`Optional`) that behaves like a list of length 0 or 1. +In certain contexts, [optional values](optional.md) can also be considered a container type (`Optional`) that behaves like a list of length 0 or 1. -To create literals of list containers, dictionary containers, set containers, tuple containers, or structure containers, you can use the [operator notation](../../builtins/basic.md#containerliteral). -To create a variant literal over a tuple or structure, use the function [Variant](../../builtins/basic.md#variant). -To create an enumeration literal, use the function [Enum](../../builtins/basic.md#enum). +To create literals of list containers, dictionary containers, set containers, tuple containers, or structure containers, you can use the [operator notation](../builtins/basic.md#containerliteral). +To create a variant literal over a tuple or structure, use the function [Variant](../builtins/basic.md#variant). +To create an enumeration literal, use the function [Enum](../builtins/basic.md#enum). -To access the container elements, use a [dot or square brackets](../../syntax/expressions.md#items-access), depending on the container type. +To access the container elements, use a [dot or square brackets](../syntax/expressions.md#items-access), depending on the container type. diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/index.md b/ydb/docs/en/core/yql/reference/types/index.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/types/index.md rename to ydb/docs/en/core/yql/reference/types/index.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/json.md b/ydb/docs/en/core/yql/reference/types/json.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/types/_includes/json.md rename to ydb/docs/en/core/yql/reference/types/json.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/optional.md b/ydb/docs/en/core/yql/reference/types/optional.md similarity index 60% rename from ydb/docs/en/core/yql/reference/yql-core/types/_includes/optional.md rename to ydb/docs/en/core/yql/reference/types/optional.md index cf8afa562cff..81dd19c97b6c 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/optional.md +++ b/ydb/docs/en/core/yql/reference/types/optional.md @@ -2,16 +2,16 @@ Any typed data in YQL, including table columns, can be either non-nullable (guaranteed value) or nullable (empty value denoted as `NULL`). Data types that can include `NULL` values are called *optional* or, in SQL terms, *nullable*. -Optional data types in the [text format](../type_string.md) use the question mark at the end (for example, `String?`) or the notation `Optional<...>`. +Optional data types in the [text format](type_string.md) use the question mark at the end (for example, `String?`) or the notation `Optional<...>`. The following operations are most often performed on optional data types: -* [IS NULL](../../syntax/expressions.md#is-null): Matching an empty value -* [COALESCE](../../builtins/basic.md#coalesce): Leave the filled values unchanged and replace `NULL` with the default value that follows -* [UNWRAP](../../builtins/basic.md#optional-ops): Extract the value of the original type from the optional data type, `T?`. is converted to `T` -* [JUST](../../builtins/basic#optional-ops): Add optionality to the current type, `T` is converted to `T?`. -* [NOTHING](../../builtins/basic.md#optional-ops): Create an empty value with the specified type. +* [IS NULL](../syntax/expressions.md#is-null): Matching an empty value +* [COALESCE](../builtins/basic.md#coalesce): Leave the filled values unchanged and replace `NULL` with the default value that follows +* [UNWRAP](../builtins/basic.md#optional-ops): Extract the value of the original type from the optional data type, `T?`. is converted to `T` +* [JUST](../builtins/basic#optional-ops): Add optionality to the current type, `T` is converted to `T?`. +* [NOTHING](../builtins/basic.md#optional-ops): Create an empty value with the specified type. -`Optional` (nullable) isn't a property of a data type or column, but a container type where [containers](../containers.md) can be arbitrarily nested into each other. For example, a column with the type `Optional>` can accept 4 values: `NULL` of the whole container, `NULL` of the inner container, `TRUE`, and `FALSE`. The above-declared type differs from `List>`, because it uses `NULL` as an empty list, and you can't put more than one non-null element in it. In addition, `Optional>` type values are returned as results when searching by the key in the `Dict(k,v)` dictionary with `Optional` type values. Using this type of result data, you can distinguish between a `NULL` value in the dictionary and a situation when the key is missing. +`Optional` (nullable) isn't a property of a data type or column, but a container type where [containers](containers.md) can be arbitrarily nested into each other. For example, a column with the type `Optional>` can accept 4 values: `NULL` of the whole container, `NULL` of the inner container, `TRUE`, and `FALSE`. The above-declared type differs from `List>`, because it uses `NULL` as an empty list, and you can't put more than one non-null element in it. In addition, `Optional>` type values are returned as results when searching by the key in the `Dict(k,v)` dictionary with `Optional` type values. Using this type of result data, you can distinguish between a `NULL` value in the dictionary and a situation when the key is missing. {% if backend_name == "YDB" %} @@ -63,11 +63,11 @@ SELECT ## Data types that do not allow NULL values {#notnull} -[Primitive types](../primitive.md) in YQL cannot hold a `NULL` value: the container described above, `Optional`, is intended for storing `NULL`. In SQL terms, primitive types in YQL are *non-nullable* types. +[Primitive types](primitive.md) in YQL cannot hold a `NULL` value: the container described above, `Optional`, is intended for storing `NULL`. In SQL terms, primitive types in YQL are *non-nullable* types. In YQL, there is no implicit type conversion from Optional to T, so the enforceability of the NOT NULL constraint on a table column is ensured at the query compilation stage in {{ ydb-short-name }}. -You can create a non-nullable column in a {{ ydb-short-name }} table using the [CREATE TABLE](../../../reference/syntax/create_table/index.md) operation with the keyword `NOT NULL`: +You can create a non-nullable column in a {{ ydb-short-name }} table using the [CREATE TABLE](../syntax/create_table/index.md) operation with the keyword `NOT NULL`: ```yql CREATE TABLE t ( @@ -91,6 +91,6 @@ INSERT INTO t(c) SELECT CAST('q' AS Utf8); ``` -cannot be executed. The reason for this is the type mismatch between the column `c`, which has the type `Utf8`, and the result of the `CAST` function, which has the type `Optional`. To make the query work correctly in such scenarios, it is necessary to use the [COALESCE](../../builtins/basic.md#coalesce) function, whose argument can specify a fallback value to insert into the table in case the function (in the example, CAST) returns an empty `Optional`. If, in the case of an empty `Optional`, the insertion should not be performed and an error should be returned, the [UNWRAP](../../builtins/basic.md#optional-ops) function can be used to unpack the contents of the optional type. +cannot be executed. The reason for this is the type mismatch between the column `c`, which has the type `Utf8`, and the result of the `CAST` function, which has the type `Optional`. To make the query work correctly in such scenarios, it is necessary to use the [COALESCE](../builtins/basic.md#coalesce) function, whose argument can specify a fallback value to insert into the table in case the function (in the example, CAST) returns an empty `Optional`. If, in the case of an empty `Optional`, the insertion should not be performed and an error should be returned, the [UNWRAP](../builtins/basic.md#optional-ops) function can be used to unpack the contents of the optional type. -{% endif %} \ No newline at end of file +{% endif %} diff --git a/ydb/docs/en/core/yql/reference/types/primitive.md b/ydb/docs/en/core/yql/reference/types/primitive.md new file mode 100644 index 000000000000..bea1a43c8014 --- /dev/null +++ b/ydb/docs/en/core/yql/reference/types/primitive.md @@ -0,0 +1,195 @@ +# Primitive data types + + + +The terms "simple", "primitive", and "elementary" data types are used synonymously. + +## Numeric types {#numeric} + +| Type | Description | Notes | +| ----- | ----- | ----- | +| `Bool` | Boolean value. | +| `Int8` | A signed integer.
Acceptable values: from -27 to 27–1. | +| `Int16` | A signed integer.
Acceptable values: from –215 to 215–1. | +| `Int32` | A signed integer.
Acceptable values: from –231 to 231–1. | +| `Int64` | A signed integer.
Acceptable values: from –263 to 263–1. | +| `Uint8` | An unsigned integer.
Acceptable values: from 0 to 28–1. | +| `Uint16` | An unsigned integer.
Acceptable values: from 0 to 216–1. | +| `Uint32` | An unsigned integer.
Acceptable values: from 0 to 232–1. | +| `Uint64` | An unsigned integer.
Acceptable values: from 0 to 264–1. | +| `Float` | A real number with variable precision, 4 bytes in size. | {% if feature_map_tables %}Can't be used in the primary key{% endif %} | +| `Double` | A real number with variable precision, 8 bytes in size. | {% if feature_map_tables %}Can't be used in the primary key{% endif %} | +| `Decimal` | A real number with the specified precision, up to 35 decimal digits | {% if feature_map_tables %}When used in table columns, the precision is fixed: Decimal(22,9){% endif %} | +{% if feature_map_tables %} +|`DyNumber` | A binary representation of a real number with an accuracy of up to 38 digits.
Acceptable values: positive numbers from 1×10-130 up to 1×10126–1, negative numbers from -1×10126–1 to -1×10-130, and 0.
Compatible with the `Number` type in AWS DynamoDB. It's not recommended for {{ backend_name_lower }}-native applications. | | +{% endif %} + + +## String types {#string} + +| Type | Description | Notes | +| ----- | ----- | ----- | +| `String` | A string that can contain any binary data | +| `Utf8` | Text encoded in [UTF-8](https://en.wikipedia.org/wiki/UTF-8) | +| `Json` | [JSON](https://en.wikipedia.org/wiki/JSON) represented as text | Doesn't support matching{% if feature_map_tables %}, can't be used in the primary key{% endif %} | +| `JsonDocument` | [JSON](https://en.wikipedia.org/wiki/JSON) in an indexed binary representation | Doesn't support matching{% if feature_map_tables %}, can't be used in the primary key{% endif %} | +| `Yson` | [YSON](../udf/list/yson.md) in a textual or binary representation. | Doesn't support matching{% if feature_map_tables %}, can't be used in the primary key{% endif %} | +| `Uuid` | Universally unique identifier [UUID](https://tools.ietf.org/html/rfc4122) | + +{% note info "Cell size restrictions" %} + +The maximum value size for a {% if feature_map_tables %}non-key {% endif %} column cell with any string data type is 8 MB. + +{% endnote %} + +Unlike the `JSON` data type that stores the original text representation passed by the user, `JsonDocument` uses an indexed binary representation. An important difference from the point of view of semantics is that `JsonDocument` doesn't preserve formatting, the order of keys in objects, or their duplicates. + +Thanks to the indexed view, `JsonDocument` lets you bypass the document model using `JsonPath` without the need to parse the full content. This helps efficiently perform operations from the [JSON API](../builtins/json.md), reducing delays and cost of user queries. Execution of `JsonDocument` queries can be up to several times more efficient depending on the type of load. + +Due to the added redundancy, `JsonDocument` is less effective in storage. The additional storage overhead depends on the specific content, but is 20-30% of the original volume on average. Saving data in `JsonDocument` format requires additional conversion from the textual representation, which makes writing it less efficient. However, for most read-intensive scenarios that involve processing data from JSON, this data type is preferred and recommended. + +{% note warning %} + +To store numbers (JSON Number) in `JsonDocument`, as well as for arithmetic operations on them in the [JSON API](../builtins/json.md), the [Double](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) type is used. Precision might be lost when non-standard representations of numbers are used in the source JSON document. + +{% endnote %} + + + +## Date and time {#datetime} + +| Type | Description | Notes | +| ----- | ----- | ----- | +| `Date` | Date, precision to the day | Range of values for all time types except `Interval`: From 00:00 01.01.1970 to 00:00 01.01.2106. Internal `Date` representation: Unsigned 16-bit integer | +| `Datetime` | Date/time, precision to the second | Internal representation: Unsigned 32-bit integer | +| `Timestamp` | Date/time, precision to the microsecond | Internal representation: Unsigned 64-bit integer | +| `Interval` | Time interval (signed), precision to microseconds | Value range: From -136 years to +136 years. Internal representation: Signed 64-bit integer. {% if feature_map_tables %}Can't be used in the primary key{% endif %} | +| `TzDate` | Date with time zone label, precision to the day | Not supported in table columns | +| `TzDateTime` | Date/time with time zone label, precision to the second | Not supported in table columns | +| `TzTimestamp` | Date/time with time zone label, precision to the microsecond | Not supported in table columns | + + + +### Supporting types with a time zone label + +Time zone label for the `TzDate`, `TzDatetime`, `TzTimestamp` types is an attribute that is used: + +* When converting ([CAST](../syntax/expressions.md#cast), [DateTime::Parse](../udf/list/datetime.md#parse), [DateTime::Format](../udf/list/datetime.md#format)) to a string and from a string. +* In [DateTime::Split](../udf/list/datetime.md#split), a timezone component is added to `Resource`. + +The point in time for these types is stored in UTC, and the timezone label doesn't participate in any other calculations in any way. For example: + +```yql +SELECT -- these expressions are always true for any timezones: the timezone doesn't affect the point in time. + AddTimezone(CurrentUtcDate(), "Europe/Moscow") == + AddTimezone(CurrentUtcDate(), "America/New_York"), + AddTimezone(CurrentUtcDatetime(), "Europe/Moscow") == + AddTimezone(CurrentUtcDatetime(), "America/New_York"); +``` + +Keep in mind that when converting between `TzDate` and `TzDatetime`, or `TzTimestamp` the date's midnight doesn't follow the local time zone, but midnight in UTC for the date in UTC. + + + +## Casting between data types {#cast} + +### Explicit casting {#explicit-cast} + +Explicit casting using [CAST](../syntax/expressions.md#cast): + +#### Casting to numeric types + +| Type | Bool | Int | Uint | Float | Double | Decimal | +| --- | --- | --- | --- | --- | --- | --- | +| **Bool** | — | Yes1 | Yes1 | Yes1 | Yes1 | No | Yes | No | +| **INT** | Yes2 | — | Yes3 | Yes | Yes | Yes | +| **Uint** | Yes2 | Yes | — | Yes | Yes | Yes | +| **Float** | Yes2 | Yes | Yes | — | Yes | No | +| **Double** | Yes2 | Yes | Yes | Yes | — | No | +| **Decimal** | No | Yes | Yes | Yes | Yes | — | +| **String** | Yes | Yes | Yes | Yes | Yes | Yes | +| **Utf8** | Yes | Yes | Yes | Yes | Yes | Yes | +| **Json** | No | No | No | No | No | No | +| **Yson** | Yes4 | Yes4 | Yes4 | Yes4 | Yes4 | Yes4 | +| **Uuid** | No | No | No | No | No | No | +| **Date** | No | Yes | Yes | Yes | Yes | No | Yes | +| **Datetime** | No | Yes | Yes | Yes | Yes | No | +| **Timestamp** | No | Yes | Yes | Yes | Yes | No | +| **Interval** | No | Yes | Yes | Yes | Yes | No | + +1 `True` is converted to `1` and `False` to `0`. +2 Any value other than `0` is converted to `True`, `0` is converted to `False`. +3 Possible only in the case of a non-negative value. +4 Using the built-in function [Yson::ConvertTo](../udf/list/yson.md#ysonconvertto). + +#### Converting to date and time data types + +| Type | Date | Datetime | Timestamp | Interval | +| --- | --- | --- | --- | --- | +| **Bool** | No | No | No | No | +| **INT** | Yes | Yes | Yes | Yes | +| **Uint** | Yes | Yes | Yes | Yes | +| **Float** | No | No | No | No | +| **Double** | No | No | No | No | +| **Decimal** | No | No | No | No | +| **String** | Yes | Yes | Yes | Yes | +| **Utf8** | Yes | Yes | Yes | Yes | +| **Json** | No | No | No | No | +| **Yson** | No | No | No | No | +| **Uuid** | No | No | No | No | +| **Date** | — | Yes | Yes | No | +| **Datetime** | Yes | — | Yes | No | +| **Timestamp** | Yes | Yes | — | No | +| **Interval** | No | No | No | — | — | + +#### Conversion to other data types + +| Type | String | Utf8 | Json | Yson | Uuid | +| --- | --- | --- | --- | --- | --- | +| **Bool** | Yes | No | No | No | No | +| **INT** | Yes | No | No | No | No | +| **Uint** | Yes | No | No | No | No | +| **Float** | Yes | No | No | No | No | +| **Double** | Yes | No | No | No | No | +| **Decimal** | Yes | No | No | No | No | +| **String** | — | Yes | Yes | Yes | Yes | +| **Utf8** | Yes | — | No | No | No | +| **Json** | Yes | Yes | — | No | No | +| **Yson** | Yes4 | No | No | No | No | +| **Uuid** | Yes | Yes | No | No | — | +| **Date** | Yes | Yes | No | No | No | +| **Datetime** | Yes | Yes | No | No | No | +| **Timestamp** | Yes | Yes | No | No | No | +| **Interval** | Yes | Yes | No | No | No | + +4 Using the built-in function [Yson::ConvertTo](../udf/list/yson.md#ysonconvertto). + +##### Examples + +{% include [x](../_includes/cast_examples.md) %} + +### Implicit casting {#implicit-cast} + +Implicit type casting that occurs in basic operations ( +-\*/) between different data types. The table cells specify the operation result type, if the operation is possible: + +#### Numeric types + +| Type | Int | Uint | Float | Double | +| --- | --- | --- | --- | --- | +| **INT** | — | `INT` | `Float` | `Double` | +| **Uint** | `INT` | — | `Float` | `Double` | +| **Float** | `Float` | `Float` | — | `Double` | +| **Double** | `Double` | `Double` | `Double` | — | + +#### Date and time types + +| Type | Date | Datetime | Timestamp | Interval | TzDate | TzDatetime | TzTimestamp | +| --- | --- | --- | --- | --- | --- | --- | --- | +| **Date** | — | — | — | `Date` | — | — | — | +| **Datetime** | — | — | — | `Datetime` | — | — | — | +| **Timestamp** | — | — | — | `Timestamp` | — | — | — | +| **Interval** | `Date` | `Datetime` | `Timestamp` | — | `TzDate` | `TzDatetime` | `TzTimestamp` | +| **TzDate** | — | — | — | `TzDate` | — | — | — | +| **TzDatetime** | — | — | — | `TzDatetime` | — | — | — | +| **TzTimestamp** | — | — | — | `TzTimestamp` | — | — | — | + diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/special.md b/ydb/docs/en/core/yql/reference/types/special.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/types/_includes/special.md rename to ydb/docs/en/core/yql/reference/types/special.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/toc_i.yaml b/ydb/docs/en/core/yql/reference/types/toc_i.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/types/toc_i.yaml rename to ydb/docs/en/core/yql/reference/types/toc_i.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/type_string.md b/ydb/docs/en/core/yql/reference/types/type_string.md similarity index 87% rename from ydb/docs/en/core/yql/reference/yql-core/types/_includes/type_string.md rename to ydb/docs/en/core/yql/reference/types/type_string.md index dd25b5330106..e8a0c54d7d05 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/type_string.md +++ b/ydb/docs/en/core/yql/reference/types/type_string.md @@ -4,12 +4,12 @@ Since YQL is a strongly typed language, the data type is important for many of its aspects. To make data type management easy, YQL has a data type definition convention in text format. It's mentioned in many places in the documentation. There's also a library that provides functions for building a data type based on a text description (for example, when manually defining the signature for the called value) or for serializing the data type into a string for debugging purposes. -Functions for data types are [described in the article](../../builtins/types.md). Below is the format of text representation of data types. +Functions for data types are [described in the article](../builtins/types.md). Below is the format of text representation of data types. ## General conventions {#rules} -* [Primitive data types](../primitive.md) are represented in text format simply by referencing their name. -* A complex data type is composed of other data types. If you depict this structure as a tree, it has [primitive data types](../primitive.md) as leaves and [containers](../containers.md) as other nodes. [You may treat special data types](../special.md) as exceptions, because they can function as both. +* [Primitive data types](primitive.md) are represented in text format simply by referencing their name. +* A complex data type is composed of other data types. If you depict this structure as a tree, it has [primitive data types](primitive.md) as leaves and [containers](containers.md) as other nodes. [You may treat special data types](special.md) as exceptions, because they can function as both. * The text representation repeats the structure of this tree from the root to the leaves: each node of the tree specifies the name of the current data type, and proceeding to a deeper level is denoted by different types of brackets. * Feel free to use spaces and line breaks if they improve readability. * If the ID contains something else except the Latin letters and numbers, put it in single quotes and use C-escaping. diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/datetime.md b/ydb/docs/en/core/yql/reference/udf/list/datetime.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/datetime.md rename to ydb/docs/en/core/yql/reference/udf/list/datetime.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/digest.md b/ydb/docs/en/core/yql/reference/udf/list/digest.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/digest.md rename to ydb/docs/en/core/yql/reference/udf/list/digest.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/histogram.md b/ydb/docs/en/core/yql/reference/udf/list/histogram.md similarity index 76% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/histogram.md rename to ydb/docs/en/core/yql/reference/udf/list/histogram.md index 60c27162d796..b1046f08afd3 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/histogram.md +++ b/ydb/docs/en/core/yql/reference/udf/list/histogram.md @@ -1,6 +1,6 @@ # Histogram -Set of auxiliary functions for the [HISTOGRAM aggregate function](../../../builtins/aggregation.md). In the signature description below, HistogramStruct refers to the result of the aggregate function `HISTOGRAM`, `LinearHistogram` or `LogarithmicHistogram` being a structure of a certain type. +Set of auxiliary functions for the [HISTOGRAM aggregate function](../../builtins/aggregation.md). In the signature description below, HistogramStruct refers to the result of the aggregate function `HISTOGRAM`, `LinearHistogram` or `LogarithmicHistogram` being a structure of a certain type. ## List of functions @@ -15,5 +15,5 @@ Set of auxiliary functions for the [HISTOGRAM aggregate function](../../../built * `Histogram::CalcUpperBoundSafe(HistogramStruct{Flags:AutoMap}, Double) -> Double` * `Histogram::CalcLowerBoundSafe(HistogramStruct{Flags:AutoMap}, Double) -> Double` -`Histogram::Print` has an optional numeric argument that sets the maximum length of the histogram columns (the length is in characters, since the histogram is rendered in ASCII art). Default: 25. This function is primarily intended for viewing histograms in the console{% if feature_webui %}. [The web interface](../../../interfaces/web.md) automatically makes an interactive visualization from them{% endif %}. +`Histogram::Print` has an optional numeric argument that sets the maximum length of the histogram columns (the length is in characters, since the histogram is rendered in ASCII art). Default: 25. This function is primarily intended for viewing histograms in the console{% if feature_webui %}. [The web interface](../../interfaces/web.md) automatically makes an interactive visualization from them{% endif %}. diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/hyperscan.md b/ydb/docs/en/core/yql/reference/udf/list/hyperscan.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/hyperscan.md rename to ydb/docs/en/core/yql/reference/udf/list/hyperscan.md diff --git a/ydb/docs/en/core/yql/reference/udf/list/index.md b/ydb/docs/en/core/yql/reference/udf/list/index.md new file mode 100644 index 000000000000..f6d5a0912b46 --- /dev/null +++ b/ydb/docs/en/core/yql/reference/udf/list/index.md @@ -0,0 +1,21 @@ +# Functions of built-in C++ libraries + +Many application functions that on the one hand are too specific to become part of the YQL core, and on the other hand might be useful to a wide range of users, are available through built-in C++ libraries. + + + +* [DateTime](datetime.md) +* [Digest](digest.md) +* [Histogram](histogram.md) +* [Hyperscan](hyperscan.md) +* [Ip](ip.md) +* [Knn](knn.md) +* [Math](math.md) +* [Pcre](pcre.md) +* [Pire](pire.md) +* [Re2](re2.md) +* [String](string.md) +* [Unicode](unicode.md) +* [Url](url.md) +* [Yson](yson.md) + diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/ip.md b/ydb/docs/en/core/yql/reference/udf/list/ip.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/ip.md rename to ydb/docs/en/core/yql/reference/udf/list/ip.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/knn.md b/ydb/docs/en/core/yql/reference/udf/list/knn.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/knn.md rename to ydb/docs/en/core/yql/reference/udf/list/knn.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/math.md b/ydb/docs/en/core/yql/reference/udf/list/math.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/math.md rename to ydb/docs/en/core/yql/reference/udf/list/math.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/pcre.md b/ydb/docs/en/core/yql/reference/udf/list/pcre.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/pcre.md rename to ydb/docs/en/core/yql/reference/udf/list/pcre.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/pire.md b/ydb/docs/en/core/yql/reference/udf/list/pire.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/pire.md rename to ydb/docs/en/core/yql/reference/udf/list/pire.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/re2.md b/ydb/docs/en/core/yql/reference/udf/list/re2.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/re2.md rename to ydb/docs/en/core/yql/reference/udf/list/re2.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/string.md b/ydb/docs/en/core/yql/reference/udf/list/string.md similarity index 98% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/string.md rename to ydb/docs/en/core/yql/reference/udf/list/string.md index 382620761dfb..73281c25148d 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/string.md +++ b/ydb/docs/en/core/yql/reference/udf/list/string.md @@ -134,7 +134,7 @@ Functions for ASCII strings: {% note alert %} -The functions from the String library don't support Cyrillic and can only work with ASCII characters. To work with UTF-8 encoded strings, use functions from [Unicode](../unicode.md). +The functions from the String library don't support Cyrillic and can only work with ASCII characters. To work with UTF-8 encoded strings, use functions from [Unicode](unicode.md). {% endnote %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/toc_base.yaml b/ydb/docs/en/core/yql/reference/udf/list/toc_base.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/toc_base.yaml rename to ydb/docs/en/core/yql/reference/udf/list/toc_base.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/toc_i.yaml b/ydb/docs/en/core/yql/reference/udf/list/toc_i.yaml similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/toc_i.yaml rename to ydb/docs/en/core/yql/reference/udf/list/toc_i.yaml diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/unicode.md b/ydb/docs/en/core/yql/reference/udf/list/unicode.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/unicode.md rename to ydb/docs/en/core/yql/reference/udf/list/unicode.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/url.md b/ydb/docs/en/core/yql/reference/udf/list/url.md similarity index 100% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/url.md rename to ydb/docs/en/core/yql/reference/udf/list/url.md diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/yson.md b/ydb/docs/en/core/yql/reference/udf/list/yson.md similarity index 97% rename from ydb/docs/en/core/yql/reference/yql-core/udf/list/yson.md rename to ydb/docs/en/core/yql/reference/udf/list/yson.md index 3949e8955a1d..c3c33d656656 100644 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/yson.md +++ b/ydb/docs/en/core/yql/reference/udf/list/yson.md @@ -2,7 +2,8 @@ -{% include [_includes/yson/intro_header.md](_includes/yson/intro_header.md) %} +YSON is a JSON-like data format developed at Yandex. + * Similarities with JSON: @@ -37,7 +38,7 @@ The module's functions must be considered as "building blocks" from which you ca * `Yson::Parse*** -> Yson::Lookup -> Yson::Serialize***`: Extracting the value of the specified subtree in the source YSON tree. * `Yson::Parse*** -> Yson::ConvertToList -> ListMap -> Yson::Lookup***`: Extracting items by a key from the YSON list. -{% include [_includes/yson/intro_footer.md](_includes/yson/intro_footer.md) %} + ## Examples @@ -243,7 +244,7 @@ Yson::YPathList(Resource<'Yson2.Node'>{Flags:AutoMap}, String) -> List), ",") -FROM users -``` - -These functions also have a short notation: `AGG_LIST` and `AGG_LIST_DISTINCT`. - -{% note alert %} - -Execution is **NOT** lazy, so when you use it, be sure that the list has a reasonable size (about a thousand items or less). To stay on the safe side, better use a second optional numeric argument that limits the number of items in the list. - -{% endnote %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/aggregate_by.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/aggregate_by.md deleted file mode 100644 index 09a1e5c11540..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/aggregate_by.md +++ /dev/null @@ -1,25 +0,0 @@ -## AGGREGATE_BY and MULTI_AGGREGATE_BY {#aggregate-by} - -Applying an [aggregation factory](../../basic.md#aggregationfactory) to all values of a column or expression. The `MULTI_AGGREGATE_BY` function requires that the value of a column or expression has a structure, tuple, or list, and applies the factory to each individual element, placing the result in a container of the same format. If different values of a column or expression contain lists of different length, the resulting list will have the smallest of the source lengths. - -1. Column, `DISTINCT` column or expression. -2. Factory. - -### Examples - -```yql -$count_factory = AggregationFactory("COUNT"); - -SELECT - AGGREGATE_BY(DISTINCT column, $count_factory) as uniq_count -FROM my_table; - -SELECT - MULTI_AGGREGATE_BY(nums, AggregationFactory("count")) as count, - MULTI_AGGREGATE_BY(nums, AggregationFactory("min")) as min, - MULTI_AGGREGATE_BY(nums, AggregationFactory("max")) as max, - MULTI_AGGREGATE_BY(nums, AggregationFactory("avg")) as avg, - MULTI_AGGREGATE_BY(nums, AggregationFactory("percentile", 0.9)) as p90 -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/bool_bit.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/bool_bit.md deleted file mode 100644 index cb622154b08e..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/bool_bit.md +++ /dev/null @@ -1,72 +0,0 @@ -## BOOL_AND, BOOL_OR and BOOL_XOR {#bool-and-or-xor} - -### Signature - -```yql -BOOL_AND(Bool?)->Bool? -BOOL_OR(Bool?)->Bool? -BOOL_XOR(Bool?)->Bool? -``` - -Apply the relevant logical operation (`AND`/`OR`/`XOR`) to all values in a Boolean column or expression. - -Unlike most other aggregate functions, these functions **don't skip** `NULL` during aggregation and use the following rules: - -- `true AND null == null` -- `false OR null == null` - -For `BOOL_AND`: - -- If at least one `NULL` value is present, the result is `NULL` regardless of `true` values in the expression. -- If at least one `false` value is present, the result changes to `false` regardless of `NULL` values in the expression. - -For `BOOL_OR`: - -- If at least one `NULL` value is present, the result changes to `NULL` regardless of `false` values in the expression. -- If at least one `true` value is present, the result changes to `true` regardless of `NULL` values in the expression. - -For `BOOL_XOR`: - -- The result is `NULL` if any `NULL` is found. - -Examples of such behavior can be found below. - -To skip `NULL` values during aggregation, use the `MIN`/`MAX` or `BIT_AND`/`BIT_OR`/`BIT_XOR` functions. - -### Examples - -```yql -$data = [ - <|nonNull: true, nonFalse: true, nonTrue: NULL, anyVal: true|>, - <|nonNull: false, nonFalse: NULL, nonTrue: NULL, anyVal: NULL|>, - <|nonNull: false, nonFalse: NULL, nonTrue: false, anyVal: false|>, -]; - -SELECT - BOOL_AND(nonNull) as nonNullAnd, -- false - BOOL_AND(nonFalse) as nonFalseAnd, -- NULL - BOOL_AND(nonTrue) as nonTrueAnd, -- false - BOOL_AND(anyVal) as anyAnd, -- false - BOOL_OR(nonNull) as nonNullOr, -- true - BOOL_OR(nonFalse) as nonFalseOr, -- true - BOOL_OR(nonTrue) as nonTrueOr, -- NULL - BOOL_OR(anyVal) as anyOr, -- true - BOOL_XOR(nonNull) as nonNullXor, -- true - BOOL_XOR(nonFalse) as nonFalseXor, -- NULL - BOOL_XOR(nonTrue) as nonTrueXor, -- NULL - BOOL_XOR(anyVal) as anyXor, -- NULL -FROM AS_TABLE($data); -``` - -## BIT_AND, BIT_OR and BIT_XOR {#bit-and-or-xor} - -Apply the relevant bitwise operation to all values of a numeric column or expression. - -### Examples - -```yql -SELECT - BIT_XOR(unsigned_numeric_value) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/corr_covar.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/corr_covar.md deleted file mode 100644 index 7cf0e9c18db6..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/corr_covar.md +++ /dev/null @@ -1,27 +0,0 @@ -## CORRELATION and COVARIANCE {#correlation-covariance} - -Correlation and covariance between two columns. - -Abbreviated versions are also available: `CORR` or `COVAR`. For covariance, there are also versions with the `SAMPLE`/`POPULATION` suffix that are similar to [VARIANCE](../../aggregation.md#variance) above. - -Unlike most other aggregate functions, they don't skip `NULL`, but accept it as 0. - -When you use [aggregation factories](../../basic.md#aggregationfactory), a `Tuple` containing two values is passed as the first [AGGREGATE_BY](../../aggregation.md#aggregateby) argument. - -### Examples - -```yql -SELECT - CORRELATION(numeric_column, another_numeric_column), - COVARIANCE(numeric_column, another_numeric_column) -FROM my_table; -``` - -```yql -$corr_factory = AggregationFactory("CORRELATION"); - -SELECT - AGGREGATE_BY(AsTuple(numeric_column, another_numeric_column), $corr_factory) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/count_distinct_estimate.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/count_distinct_estimate.md deleted file mode 100644 index 5d690c8c9fcc..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/count_distinct_estimate.md +++ /dev/null @@ -1,27 +0,0 @@ -## CountDistinctEstimate, HyperLogLog, and HLL {#countdistinctestimate} - -Approximating the number of unique values using the [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog) algorithm. Logically, it does the same thing as [COUNT(DISTINCT ...)](../../aggregation.md#count), but runs much faster at the cost of some error. - -Arguments: - -1. Estimated value -2. Accuracy (4 to 18 inclusive, 14 by default). - -By selecting accuracy, you can trade added resource and RAM consumption for decreased error. - -All the three functions are aliases at the moment, but `CountDistinctEstimate` may start using a different algorithm in the future. - -### Examples - -```yql -SELECT - CountDistinctEstimate(my_column) -FROM my_table; -``` - -```yql -SELECT - HyperLogLog(my_column, 4) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/histogram.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/histogram.md deleted file mode 100644 index b8f7eafa49c3..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/histogram.md +++ /dev/null @@ -1,119 +0,0 @@ -## HISTOGRAM {#histogram} - -Plotting an approximate histogram based on a numeric expression with automatic selection of buckets. - -[Auxiliary functions](../../../udf/list/histogram.md) - -### Basic settings - -You can limit the number of buckets using an optional argument. The default value is 100. Keep in mind that added accuracy costs you more computing resources and may negatively affect the query execution time. In extreme cases, it may affect your query success. - -### Support for weights - -You can specify a "weight" for each value used in the histogram. To do this, pass to the aggregate function the second argument with an expression for calculating the weight. The weight of `1.0` is always used by default. If you use non-standard weights, you may also use the third argument to limit the number of buckets. - -If you pass two arguments, the meaning of the second argument is determined by its type (if it's an integer literal, it limits the number of buckets, otherwise it's used as a weight). - -{% if tech %} - -### Algorithms - -* [Source whitepaper](http://jmlr.org/papers/volume11/ben-haim10a/ben-haim10a.pdf); - -Various modifications of the algorithm are available: - -```yql -AdaptiveDistanceHistogram -AdaptiveWeightHistogram -AdaptiveWardHistogram -BlockWeightHistogram -BlockWardHistogram -``` - -By default, `HISTOGRAM` is a synonym for `AdaptiveWardHistogram`. Both functions are equivalent and interchangeable in all contexts. - -The Distance, Weight, and Ward algorithms differ in the formulas that combine two points into one: - -```c++ - TWeightedValue CalcDistanceQuality(const TWeightedValue& left, const TWeightedValue& right) { - return TWeightedValue(right.first - left.first, left.first); - } - - TWeightedValue CalcWeightQuality(const TWeightedValue& left, const TWeightedValue& right) { - return TWeightedValue(right.second + left.second, left.first); - } - - TWeightedValue CalcWardQuality(const TWeightedValue& left, const TWeightedValue& right) { - const double N1 = left.second; - const double N2 = right.second; - const double mu1 = left.first; - const double mu2 = right.first; - return TWeightedValue(N1 * N2 / (N1 + N2) * (mu1 - mu2) * (mu1 - mu2), left.first); - } -``` - -Difference between Adaptive and Block: - -> Contrary to adaptive histogram, block histogram doesn't rebuild bins after each point is added. Instead, it accumulates points and if the amount of points overflows specified limits, it shrinks all the points at once to produce a histogram. Indeed, there exist two limits and two shrinkage operations: -> -> 1. FastGreedyShrink is fast but coarse. It is used to shrink from upper limit to intermediate limit (override FastGreedyShrink to set specific behaviour). -> 2. SlowShrink is slow, but produces finer histogram. It shrinks from the intermediate limit to the actual number of bins in a manner similar to that in adaptive histogram (set CalcQuality in 34constuctor) -> While FastGreedyShrink is used most of the time, SlowShrink is mostly used for histogram finalization - -{% endif %} - -### If you need an accurate histogram - -1. You can use the aggregate functions described below with fixed bucket grids: [LinearHistogram](#linearhistogram) or [LogarithmicHistogram](#linearhistogram). -2. You can calculate the bucket number for each row and apply to it [GROUP BY](../../../syntax/group_by.md). - -When you use [aggregation factories](../../basic.md#aggregationfactory), a `Tuple` containing a value and a weight is passed as the first [AGGREGATE_BY](../../aggregation.md#aggregateby) argument. - -### Examples - -```yql -SELECT - HISTOGRAM(numeric_column) -FROM my_table; -``` - -```yql -SELECT - Histogram::Print( - HISTOGRAM(numeric_column, 10), - 50 - ) -FROM my_table; -``` - -```yql -$hist_factory = AggregationFactory("HISTOGRAM"); - -SELECT - AGGREGATE_BY(AsTuple(numeric_column, 1.0), $hist_factory) -FROM my_table; -``` - -## LinearHistogram, LogarithmicHistogram, and LogHistogram {#linearhistogram} - -Plotting a histogram based on an explicitly specified fixed bucket scale. - -Arguments: - -1. Expression used to plot the histogram. All the following arguments are optional. -2. Spacing between the `LinearHistogram` buckets or the logarithm base for `LogarithmicHistogram`/`LogHistogram` (those are aliases). In both cases, the default value is 10. -3. Minimum value. By default, it's minus infinity. -4. Maximum value. By default, it's plus infinity. - -The format of the result is totally similar to [adaptive histograms](#histogram), so you can use the same [set of auxiliary functions](../../../udf/list/histogram.md). - -If the spread of input values is uncontrollably large, we recommend that you specify the minimum and maximum values to prevent potential failures due to high memory consumption. - -### Examples - -```yql -SELECT - LogarithmicHistogram(numeric_column, 2) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/max_min_by.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/max_min_by.md deleted file mode 100644 index 55f2e4f5e921..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/max_min_by.md +++ /dev/null @@ -1,40 +0,0 @@ -## MAX_BY and MIN_BY {#max-min-by} - -Return the value of the first argument for the table row where the second argument is minimum/maximum. - -You can optionally specify the third argument N that affects behavior if the table has multiple rows with the same minimum or maximum value: - -* If N is omitted, the value of one of the rows is returned, and the other rows are discarded. -* If N is specified, the list is returned with all values, but their number can't exceed N. All values after the number are discarded. - -When choosing N, we recommend that you don't exceed several hundreds or thousands to avoid issues with the limited memory available on {{ backend_name }} clusters. - -If your task needs absolutely all values, and their number is measured in dozens of thousands or more, then instead of those aggregate functions better use `JOIN` on the source table with a subquery doing `GROUP BY + MIN/MAX` on the desired columns of this table. - -{% note warning "Attention" %} - -If the second argument is always `NULL`, the aggregation result is `NULL`. - -{% endnote %} - -When you use [aggregation factories](../../basic.md#aggregationfactory), a `Tuple` containing a value and a key is passed as the first [AGGREGATE_BY](../../aggregation.md#aggregateby) argument. - -### Examples - -```yql -SELECT - MIN_BY(value, LENGTH(value)), - MAX_BY(value, key, 100) -FROM my_table; -``` - -```yql -$min_by_factory = AggregationFactory("MIN_BY"); -$max_by_factory = AggregationFactory("MAX_BY", 100); - -SELECT - AGGREGATE_BY(AsTuple(value, LENGTH(value)), $min_by_factory), - AGGREGATE_BY(AsTuple(value, key), $max_by_factory) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/percentile_median.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/percentile_median.md deleted file mode 100644 index 5bac2b8f608d..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/percentile_median.md +++ /dev/null @@ -1,17 +0,0 @@ -## PERCENTILE and MEDIAN {#percentile-median} - -Calculating percentiles using the amortized version of the [TDigest](https://github.com/tdunning/t-digest) algorithm. `MEDIAN`: An alias for `PERCENTILE(N, 0.5)`. - -{% note info "Restriction" %} - -The first argument (N) must be a table column name. If you need to bypass this restriction, use a subquery. The restriction is introduced to simplify calculations, since the implementation merges the calls with the same first argument (N) into a single pass. - -{% endnote %} - -```yql -SELECT - MEDIAN(numeric_column), - PERCENTILE(numeric_column, 0.99) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/session_start.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/session_start.md deleted file mode 100644 index 62e1db4f2a06..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/session_start.md +++ /dev/null @@ -1,6 +0,0 @@ -## SessionStart {#session-start} - -No arguments. It's allowed only if there is [SessionWindow](../../../syntax/group_by.md#session-window) in [GROUP BY](../../../syntax/group_by.md) / [PARTITION BY](../../../syntax/window.md#partition). -Returns the value of the `SessionWindow` key column. If `SessionWindow` has two arguments, it returns the minimum value of the first argument within the group/section. -In the case of the expanded version `SessionWindow`, it returns the value of the second element from the tuple returned by ``, for which the first tuple element is `True`. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/simple.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/simple.md deleted file mode 100644 index dd9eec890216..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/simple.md +++ /dev/null @@ -1,134 +0,0 @@ -## COUNT {#count} - -Counting the number of rows in the table (if `*` or constant is specified as the argument) or non-empty values in a table column (if the column name is specified as an argument). - -Like other aggregate functions, it can be combined with [GROUP BY](../../../syntax/group_by.md) to get statistics on the parts of the table that correspond to the values in the columns being grouped. {% if select_statement != "SELECT STREAM" %}Use the modifier [DISTINCT](../../../syntax/group_by.md#distinct) to count distinct values.{% endif %} - -### Examples - -```yql -SELECT COUNT(*) FROM my_table; -``` - -```yql -SELECT key, COUNT(value) FROM my_table GROUP BY key; -``` - -{% if select_statement != "SELECT STREAM" %} - -```yql -SELECT COUNT(DISTINCT value) FROM my_table; -``` - -{% endif %} - -## MIN and MAX {#min-max} - -Minimum or maximum value. - -As an argument, you may use an arbitrary computable expression with a numeric result. - -### Examples - -```yql -SELECT MIN(value), MAX(value) FROM my_table; -``` - -## SUM {#sum} - -Sum of the numbers. - -As an argument, you may use an arbitrary computable expression with a numeric result. - -Integers are automatically expanded to 64 bits to reduce the risk of overflow. - -```yql -SELECT SUM(value) FROM my_table; -``` - -## AVG {#avg} - -Arithmetic average. - -As an argument, you may use an arbitrary computable expression with a numeric result. - -Integer values and time intervals are automatically converted to Double. - -### Examples - -```yql -SELECT AVG(value) FROM my_table; -``` - -## COUNT_IF {#count-if} - -Number of rows for which the expression specified as the argument is true (the expression's calculation result is true). - -The value `NULL` is equated to `false` (if the argument type is `Bool?`). - -The function *does not* do the implicit type casting to Boolean for strings and numbers. - -### Examples - -```yql -SELECT - COUNT_IF(value % 2 == 1) AS odd_count -``` - -{% if select_statement != "SELECT STREAM" %} - -{% note info %} - -To count distinct values in rows meeting the condition, unlike other aggregate functions, you can't use the modifier [DISTINCT](../../../syntax/group_by.md#distinct) because arguments contain no values. To get this result, use in the subquery the built-in function [IF](../../../builtins/basic.md#if) with two arguments (to get `NULL` in else), and apply an outer [COUNT(DISTINCT ...)](#count) to its result. - -{% endnote %} - -{% endif %} - -## SUM_IF and AVG_IF {#sum-if} - -Sum or arithmetic average, but only for the rows that satisfy the condition passed by the second argument. - -Therefore, `SUM_IF(value, condition)` is a slightly shorter notation for `SUM(IF(condition, value))`, same for `AVG`. The argument's data type expansion is similar to the same-name functions without a suffix. - -### Examples - -```yql -SELECT - SUM_IF(value, value % 2 == 1) AS odd_sum, - AVG_IF(value, value % 2 == 1) AS odd_avg, -FROM my_table; -``` - -When you use [aggregation factories](../../basic.md#aggregationfactory), a `Tuple` containing a value and a predicate is passed as the first [AGGREGATE_BY](../../aggregation.md#aggregateby) argument. - -```yql -$sum_if_factory = AggregationFactory("SUM_IF"); -$avg_if_factory = AggregationFactory("AVG_IF"); - -SELECT - AGGREGATE_BY(AsTuple(value, value % 2 == 1), $sum_if_factory) AS odd_sum, - AGGREGATE_BY(AsTuple(value, value % 2 == 1), $avg_if_factory) AS odd_avg -FROM my_table; -``` - -## SOME {#some} - -Get the value for an expression specified as an argument, for one of the table rows. Gives no guarantee of which row is used. It's similar to the [any()]{% if lang == "en" %}(https://clickhouse.tech/docs/en/sql-reference/aggregate-functions/reference/any/){% else %}(https://clickhouse.tech/docs/ru/sql-reference/aggregate-functions/reference/any/){% endif %} function in ClickHouse. - -Because of no guarantee, `SOME` is computationally cheaper than [MIN / MAX](#min-max) often used in similar situations. - -### Examples - -```yql -SELECT - SOME(value) -FROM my_table; -``` - -{% note alert %} - -When the aggregate function `SOME` is called multiple times, it's **not** guaranteed that all the resulting values are taken from the same row of the source table. To get this guarantee, pack the values into any container and pass it to `SOME`. For example, in the case of a structure, you can apply [AsStruct](../../../builtins/basic.md#asstruct) - -{% endnote %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/stddev_variance.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/stddev_variance.md deleted file mode 100644 index 4e8e2802714f..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/stddev_variance.md +++ /dev/null @@ -1,22 +0,0 @@ -## STDDEV and VARIANCE {#stddev-variance} - -Standard deviation and variance in a column. Those functions use a [single-pass parallel algorithm](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm), whose result may differ from the more common methods requiring two passes through the data. - -By default, the sample variance and standard deviation are calculated. Several write methods are available: - -* with the `POPULATION` suffix/prefix, for example: `VARIANCE_POPULATION`, `POPULATION_VARIANCE` calculates the variance or standard deviation for the population. -* With the `SAMPLE` suffix/prefix or without a suffix, for example, `VARIANCE_SAMPLE`, `SAMPLE_VARIANCE`, `SAMPLE` calculate sample variance and standard deviation. - -Several abbreviated aliases are also defined, for example, `VARPOP` or `STDDEVSAMP`. - -If all the values passed are `NULL`, it returns `NULL`. - -### Examples - -```yql -SELECT - STDDEV(numeric_column), - VARIANCE(numeric_column) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/top_bottom.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/top_bottom.md deleted file mode 100644 index 5ea471ab1d53..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/top_bottom.md +++ /dev/null @@ -1,48 +0,0 @@ -## TOP and BOTTOM {#top-bottom} - -Return a list of the maximum/minimum values of an expression. The first argument is an expression, the second argument limits the number of items. - -### Examples - -```yql -SELECT - TOP(key, 3), - BOTTOM(value, 3) -FROM my_table; -``` - -```yql -$top_factory = AggregationFactory("TOP", 3); -$bottom_factory = AggregationFactory("BOTTOM", 3); - -SELECT - AGGREGATE_BY(key, $top_factory), - AGGREGATE_BY(value, $bottom_factory) -FROM my_table; -``` - -## TOP_BY and BOTTOM_BY {#top-bottom-by} - -Return a list of values of the first argument for the rows containing the maximum/minimum values of the second argument. The third argument limits the number of items in the list. - -When you use [aggregation factories](../../basic.md#aggregationfactory), a `Tuple` containing a value and a key is passed as the first [AGGREGATE_BY](../../aggregation.md#aggregateby) argument. In this case, the limit for the number of items is passed by the second argument at factory creation. - -### Examples - -```yql -SELECT - TOP_BY(value, LENGTH(value), 3), - BOTTOM_BY(value, key, 3) -FROM my_table; -``` - -```yql -$top_by_factory = AggregationFactory("TOP_BY", 3); -$bottom_by_factory = AggregationFactory("BOTTOM_BY", 3); - -SELECT - AGGREGATE_BY(AsTuple(value, LENGTH(value)), $top_by_factory), - AGGREGATE_BY(AsTuple(value, key), $bottom_by_factory) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/topfreq_mode.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/topfreq_mode.md deleted file mode 100644 index a97960874560..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/aggregation/topfreq_mode.md +++ /dev/null @@ -1,23 +0,0 @@ -## TOPFREQ and MODE {#topfreq-mode} - -Getting an **approximate** list of the most common values in a column with an estimation of their count. Returns a list of structures with two fields: - -* `Value`: the frequently occurring value that was found. -* `Frequency`: An estimated value occurrence in the table. - -Required argument: the value itself. - -Optional arguments: - -1. For `TOPFREQ`, the desired number of items in the result. `MODE` is an alias to `TOPFREQ` with this argument set to 1. For `TOPFREQ`, this argument is also 1 by default. -2. The number of items in the buffer used: lets you trade memory consumption for accuracy. Default: 100. - -### Examples - -```yql -SELECT - MODE(my_column), - TOPFREQ(my_column, 5, 1000) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/abs.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/abs.md deleted file mode 100644 index 6e9ab1fafbf5..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/abs.md +++ /dev/null @@ -1,10 +0,0 @@ -## Abs {#abs} - -The absolute value of the number. - -### Examples - -```yql -SELECT Abs(-123); -- 123 -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/aggr_factory.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/aggr_factory.md deleted file mode 100644 index 50465a1becab..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/aggr_factory.md +++ /dev/null @@ -1,79 +0,0 @@ -## AggregationFactory {#aggregationfactory} - -Create a factory for [aggregation functions](../../aggregation.md) to separately describe the methods of aggregation and data types subject to aggregation. - -Arguments: - -1. A string in double quotes with the name of an aggregate function, for example ["MIN"](../../aggregation.md#min). -2. Optional parameters of the aggregate function that are data-independent. For example, the percentile value in [PERCENTILE](../../aggregation.md#percentile). - -The resulting factory can be used as the second parameter of the function [AGGREGATE_BY](../../aggregation.md#aggregateby). -If the aggregate function is applied to two columns instead of one, as, for example, [MIN_BY](../../aggregation.md#minby), then in [AGGREGATE_BY](../../aggregation.md#aggregateby), the first argument passes a `Tuple` of two values. See more details in the description of the applicable aggregate function. - -### Examples - -```yql -$factory = AggregationFactory("MIN"); -SELECT - AGGREGATE_BY (value, $factory) AS min_value -- apply the MIN aggregation to the "value" column -FROM my_table; -``` - -## AggregateTransformInput {#aggregatetransform} - -`AggregateTransformInput()` converts an [aggregation factory](../../aggregation.md), for example, obtained using the [AggregationFactory](#aggregationfactory) function, to other factory, in which the specified transformation of input items is performed before starting aggregation. - -Arguments: - -1. Aggregation factory. -2. A lambda function with one argument that converts an input item. - -### Examples - -```yql -$f = AggregationFactory("sum"); -$g = AggregateTransformInput($f, ($x) -> (cast($x as Int32))); -$h = AggregateTransformInput($f, ($x) -> ($x * 2)); -SELECT ListAggregate([1,2,3], $f); -- 6 -SELECT ListAggregate(["1","2","3"], $g); -- 6 -SELECT ListAggregate([1,2,3], $h); -- 12 -``` - -## AggregateTransformOutput {#aggregatetransformoutput} - -`AggregateTransformOutput()` converts an [aggregation factory](../../aggregation.md), for example, obtained using the [AggregationFactory](#aggregationfactory) function, to other factory, in which the specified transformation of the result is performed after ending aggregation. - -Arguments: - -1. Aggregation factory. -2. A lambda function with one argument that converts the result. - -### Examples - -```yql -$f = AggregationFactory("sum"); -$g = AggregateTransformOutput($f, ($x) -> ($x * 2)); -SELECT ListAggregate([1,2,3], $f); -- 6 -SELECT ListAggregate([1,2,3], $g); -- 12 -``` - -## AggregateFlatten {#aggregateflatten} - -Adapts a factory for [aggregation functions](../../aggregation.md), for example, obtained using the [AggregationFactory](#aggregationfactory) function in a way that allows aggregation of list input items. This operation is similar to [FLATTEN LIST BY](../../../syntax/flatten.md): Each list item is aggregated. - -Arguments: - -1. Aggregation factory. - -### Examples - -```yql -$i = AggregationFactory("AGGREGATE_LIST_DISTINCT"); -$j = AggregateFlatten($i); -SELECT AggregateBy(x, $j) from ( - select [1,2] as x - union all - select [2,3] as x -); -- [1, 2, 3] -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/as_container.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/as_container.md deleted file mode 100644 index 487cf55f57d5..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/as_container.md +++ /dev/null @@ -1,38 +0,0 @@ -## AsTuple, AsStruct, AsList, AsDict, AsSet, AsListStrict, AsDictStrict and AsSetStrict {#as-container} - -Creates containers of the applicable types. For container literals, [operator notation](../../basic.md#containerliteral) is also supported. - -Specifics: - -* The container elements are passed in arguments. Hence, the number of elements in the resulting container is equal to the number of arguments passed, except when the dictionary keys repeat. -* `AsTuple` and `AsStruct` can be called without arguments, and also the arguments can have different types. -* The field names in `AsStruct` are set using `AsStruct(field_value AS field_name)`. -* Creating a list requires at least one argument if you need to output the element types. To create an empty list with the given type of elements, use the function [ListCreate](../../list.md#listcreate). You can create an empty list as an `AsList()` call without arguments. In this case, this expression will have the `EmptyList` type. -* Creating a dictionary requires at least one argument if you need to output the element types. To create an empty dictionary with the given type of elements, use the function [DictCreate](../../dict.md#dictcreate). You can create an empty dictionary as an `AsDict()` call without arguments, in this case, this expression will have the `EmptyDict` type. -* Creating a set requires at least one argument if you need to output element types. To create an empty set with the given type of elements, use the function [SetCreate](../../dict.md#setcreate). You can create an empty set as an `AsSet()` call without arguments, in this case, this expression will have the `EmptySet` type. -* `AsList` outputs the common type of elements in the list. A type error is raised in the case of incompatible types. -* `AsDict` separately outputs the common types for keys and values. A type error is raised in the case of incompatible types. -* `AsSet` outputs common types for keys. A type error is raised in the case of incompatible types. -* `AsListStrict`, `AsDictStrict`, `AsSetStrict` require the same type for their arguments. -* `AsDict` and `AsDictStrict` expect `Tuple` of two elements as arguments (key and value, respectively). If the keys repeat, only the value for the first key remains in the dictionary. -* `AsSet` and `AsSetStrict` expect keys as arguments. - -### Examples - -```yql -SELECT - AsTuple(1, 2, "3") AS `tuple`, - AsStruct( - 1 AS a, - 2 AS b, - "3" AS c - ) AS `struct`, - AsList(1, 2, 3) AS `list`, - AsDict( - AsTuple("a", 1), - AsTuple("b", 2), - AsTuple("c", 3) - ) AS `dict`, - AsSet(1, 2, 3) AS `set` -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/as_tagged.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/as_tagged.md deleted file mode 100644 index 326cdb98120a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/as_tagged.md +++ /dev/null @@ -1,17 +0,0 @@ -## AsTagged, Untag {#as-tagged} - -Wraps the value in the [Tagged data type](../../../types/special.md) with the specified tag, preserving the physical data type. `Untag`: The reverse operation. - -Required arguments: - -1. Value of any type. -2. Tag name. - -Returns a copy of the value from the first argument with the specified tag in the data type. - -Examples of use cases: - -* Returns to the client's web interface the media files from BASE64-encoded strings{% if feature_webui %}. Tag support in the YQL Web UI [is described here](../../../interfaces/web_tagged.md){% endif %}. -{% if feature_mapreduce %}* Prevent passing of invalid values at the boundaries of UDF calls.{% endif %} -* Additional refinements at the level of returned columns types. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/bitops.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/bitops.md deleted file mode 100644 index 9332c57b58c4..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/bitops.md +++ /dev/null @@ -1,19 +0,0 @@ -## ...Bit {#bitops} - -`TestBit()`, `ClearBit()`, `SetBit()` and `FlipBit()`: Test, clear, set, or flip a bit in an unsigned number using the specified bit sequence number. - -Arguments: - -1. An unsigned number that's subject to the operation. TestBit is also implemented for strings. -2. Number of the bit. - -TestBit returns `true/false`. The other functions return a copy of their first argument with the corresponding conversion. - -### Examples - -```yql -SELECT - TestBit(1u, 0), -- true - SetBit(8u, 0); -- 9 -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/byteat.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/byteat.md deleted file mode 100644 index 16233a1b0bb1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/byteat.md +++ /dev/null @@ -1,18 +0,0 @@ -## ByteAt {#byteat} - -Getting the byte value inside a string at an index counted from the beginning of the string. If an invalid index is specified, `NULL` is returned. - -Arguments: - -1. String: `String` or `Utf8`. -2. Index: `Uint32`. - -### Examples - -```yql -SELECT - ByteAt("foo", 0), -- 102 - ByteAt("foo", 1), -- 111 - ByteAt("foo", 9); -- NULL -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/callable.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/callable.md deleted file mode 100644 index 91db4e02f629..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/callable.md +++ /dev/null @@ -1,24 +0,0 @@ -## Callable {#callable} - -Create a callable value with the specified signature from a lambda function. It's usually used to put callable values into containers. - -Arguments: - -1. Type. -2. Lambda function. - -### Examples - -```yql -$lambda = ($x) -> { - RETURN CAST($x as String) -}; - -$callables = AsTuple( - Callable(Callable<(Int32)->String>, $lambda), - Callable(Callable<(Bool)->String>, $lambda), -); - -SELECT $callables.0(10), $callables.1(true); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/coalesce.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/coalesce.md deleted file mode 100644 index 02c1c5a75bea..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/coalesce.md +++ /dev/null @@ -1,32 +0,0 @@ -## COALESCE {#coalesce} - -Iterates through the arguments from left to right and returns the first non-empty argument found. To be sure that the result is non-empty (not of an [optional type](../../../types/optional.md)), the rightmost argument must be of this type (often a literal is used for this). With a single argument, returns this argument unchanged. - -Lets you pass potentially empty values to functions that can't handle them by themselves. - -A short format using the low-priority `??` operator is available (lower than the Boolean operations). You can use the `NVL` alias. - -### Examples - -```yql -SELECT COALESCE( - maybe_empty_column, - "it's empty!" -) FROM my_table; -``` - -```yql -SELECT - maybe_empty_column ?? "it's empty!" -FROM my_table; -``` - -```yql -SELECT NVL( - maybe_empty_column, - "it's empty!" -) FROM my_table; -``` - -All three examples above are equivalent. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/container_literal.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/container_literal.md deleted file mode 100644 index 12e4c994a58c..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/container_literal.md +++ /dev/null @@ -1,36 +0,0 @@ -## Container literals {#containerliteral} - -Some containers support operator notation for their literal values: - -* Tuple: `(value1, value2...)`; -* Structure: `<|name1: value1, name2: value2...|>`; -* List: `[value1, value2,...]`; -* Dictionary: `{key1: value1, key2: value2...}`; -* Set: `{key1, key2...}`. - -In every case, you can use an insignificant trailing comma. For a tuple with one element, this comma is required: `(value1,)`. -For field names in the structure literal, you can use an expression that can be calculated at evaluation time, for example, string literals or identifiers (including those enclosed in backticks). - -For nested lists, use [AsList](../../basic.md#as-container), for nested dictionaries, use [AsDict](../../basic.md#as-container), for nested sets, use [AsSet](../../basic.md#as-container), for nested tuples, use [AsTuple](../../basic.md#as-container), for nested structures, use [AsStruct](../../basic.md#as-container). - -### Examples - -```yql -$name = "computed " || "member name"; -SELECT - (1, 2, "3") AS `tuple`, - <| - `complex member name`: 2.3, - b: 2, - $name: "3", - "inline " || "computed member name": false - |> AS `struct`, - [1, 2, 3] AS `list`, - { - "a": 1, - "b": 2, - "c": 3, - } AS `dict`, - {1, 2, 3} AS `set` -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/current_tz.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/current_tz.md deleted file mode 100644 index 79f53d7002e6..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/current_tz.md +++ /dev/null @@ -1,49 +0,0 @@ -## CurrentTz... {#current-tz} - -`CurrentTzDate()`, `CurrentTzDatetime()`, and `CurrentTzTimestamp()`: Get the current date and/or time in the [IANA time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) specified in the first argument. The result data type is specified at the end of the function name. - -The arguments that follow are optional and work same as [RANDOM](../../basic.md#random). - -### Examples - -```yql -SELECT CurrentTzDate("Europe/Moscow"); -``` - -```yql -SELECT CurrentTzTimestamp("Europe/Moscow", TableRow()) FROM my_table; -``` - -## AddTimezone - -Adding the time zone information to the date/time in UTC. In the result of `SELECT` or after `CAST`, a `String` will be subject to the time zone rules used to calculate the time offset. - -Arguments: - -1. Date: the type is `Date`/`Datetime`/`Timestamp`. -2. [The IANA name of the time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). - -Result type: `TzDate`/`TzDatetime`/`TzTimestamp`, depending on the input data type. - -### Examples - -```yql -SELECT AddTimezone(Datetime("2018-02-01T12:00:00Z"), "Europe/Moscow"); -``` - -## RemoveTimezone - -Removing the time zone data and converting the value to date/time in UTC. - -Arguments: - -1. Date: the type is `TzDate`/`TzDatetime`/`TzTimestamp`. - -Result type: `Date`/`Datetime`/`Timestamp`, depending on the input data type. - -### Examples - -```yql -SELECT RemoveTimezone(TzDatetime("2018-02-01T12:00:00,Europe/Moscow")); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/current_utc.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/current_utc.md deleted file mode 100644 index 6473e9568bcb..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/current_utc.md +++ /dev/null @@ -1,16 +0,0 @@ -## CurrentUtc... {#current-utc} - -`CurrentUtcDate()`, `CurrentUtcDatetime()` and `CurrentUtcTimestamp()`: Getting the current date and/or time in UTC. The result data type is specified at the end of the function name. - -The arguments are optional and work same as [RANDOM](../../basic.md#random). - -### Examples - -```yql -SELECT CurrentUtcDate(); -``` - -```yql -SELECT CurrentUtcTimestamp(TableRow()) FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/data-type-literals.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/data-type-literals.md deleted file mode 100644 index 2f79350078bb..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/data-type-literals.md +++ /dev/null @@ -1,51 +0,0 @@ -## Literals of primitive types {#data-type-literals} - -For primitive types, you can create literals based on string literals. - -### Syntax - -`( [, ] )` - -Unlike `CAST("myString" AS MyType)`: - -* The check for literal's castability to the desired type occurs at validation. -* The result is non-optional. - -For the data types `Date`, `Datetime`, `Timestamp`, and `Interval`, literals are supported only in the format corresponding to [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). `Interval` has the following differences from the standard: - -* It supports the negative sign for shifts to the past. -* Microseconds can be expressed as fractional parts of seconds. -* You can't use units of measurement exceeding one week. -* The options with the beginning/end of the interval and with repetitions, are not supported. - -For the data types `TzDate`, `TzDatetime`, `TzTimestamp`, literals are also set in the format meeting [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601), but instead of the optional Z suffix, they specify the [IANA name of the time zone](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones), separated by comma (for example, GMT or Europe/Moscow). - -{% include [decimal args](../../../_includes/decimal_args.md) %} - -### Examples - -```yql -SELECT - Bool("true"), - Uint8("0"), - Int32("-1"), - Uint32("2"), - Int64("-3"), - Uint64("4"), - Float("-5"), - Double("6"), - Decimal("1.23", 5, 2), -- up to 5 decimal digits, with 2 after the decimal point - String("foo"), - Utf8("Hello"), - Yson("[3;%false]"), - Json(@@{"a":1,"b":null}@@), - Date("2017-11-27"), - Datetime("2017-11-27T13:24:00Z"), - Timestamp("2017-11-27T13:24:00.123456Z"), - Interval("P1DT2H3M4.567890S"), - TzDate("2017-11-27,Europe/Moscow"), - TzDatetime("2017-11-27T13:24:00,America/Los_Angeles"), - TzTimestamp("2017-11-27T13:24:00.123456,GMT"), - Uuid("f9d5cc3f-f1dc-4d9c-b97e-766e57ca4ccb"); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/ensure.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/ensure.md deleted file mode 100644 index 30cdae213c12..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/ensure.md +++ /dev/null @@ -1,44 +0,0 @@ -## Ensure... {#ensure} - -Checking for the user conditions: - -* `Ensure()`: Checking whether the predicate is true at query execution. -* `EnsureType()`: Checking that the expression type exactly matches the specified type. -* `EnsureConvertibleTo()`: A soft check of the expression type (with the same rules as for implicit type conversion). - -If the check fails, the entire query fails. - -Arguments: - -1. An expression that will result from a function call if the check is successful. It's also checked for the data type in the corresponding functions. -2. Ensure uses a Boolean predicate that is checked for being `true`. The other functions use the data type that can be obtained using the [relevant functions](../../types.md), or a string literal with a [text description of the type](../../../types/type_string.md). -3. An optional string with an error comment to be included in the overall error message when the query is complete. The data itself can't be used for type checks, since the data check is performed at query validation (or can be an arbitrary expression in the case of Ensure). - -To check the conditions based on the final calculation result, it's convenient to combine Ensure with [DISCARD SELECT](../../../syntax/discard.md). - -### Examples - -```yql -SELECT Ensure( - value, - value < 100, - "value out or range" -) AS value FROM my_table; -``` - -```yql -SELECT EnsureType( - value, - TypeOf(other_value), - "expected value and other_value to be of same type" -) AS value FROM my_table; -``` - -```yql -SELECT EnsureConvertibleTo( - value, - Double?, - "expected value to be numeric" -) AS value FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/enum.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/enum.md deleted file mode 100644 index 6a4b689c993a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/enum.md +++ /dev/null @@ -1,33 +0,0 @@ -## Enum {#enum} - -`Enum()` creates an enumeration value. - -Arguments: - -* A string with the field name -* Enumeration type - -### Example - -```yql -$enum_type = Enum; -SELECT - Enum("Foo", $enum_type) as Enum1Value, - Enum("Bar", $enum_type) as Enum2Value; -``` - -## AsEnum {#asenum} - -`AsEnum()` creates a value of [enumeration](../../../types/containers.md) including one element. This value can be implicitly cast to any enumeration containing such a name. - -Arguments: - -* A string with the name of an enumeration item - -### Example - -```yql -SELECT - AsEnum("Foo"); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/evaluate_expr_atom.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/evaluate_expr_atom.md deleted file mode 100644 index 890cf936249b..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/evaluate_expr_atom.md +++ /dev/null @@ -1,32 +0,0 @@ -## EvaluateExpr, EvaluateAtom {#evaluate_expr_atom} - -Evaluate an expression before the start of the main calculation and input its result to the query as a literal (constant). In many contexts, where only a constant would be expected in standard SQL (for example, in table names, in the number of rows in [LIMIT](../../../syntax/select/limit_offset.md), and so on), this functionality is implicitly enabled automatically. - -EvaluateExpr can be used where the grammar already expects an expression. For example, you can use it to: - -* Round the current time to days, weeks, or months and insert it into the query to ensure correct [query caching](../../../syntax/pragma.md#yt.querycachemode), although usually when [functions are used to get the current time](../../basic.md#current-utc), query caching is completely disabled. -* Run a heavy calculation with a small result once per query instead of once per job. - -{% if backend_name == "YT" %} - -EvaluateAtom lets you dynamically create an [atom](../../../types/special.md), but since atoms are mainly controlled from a lower [s-expressions](/docs/s_expressions/functions) level, it's generally not recommended to use this function directly. - -{% endif %} - -The only argument for both functions is the expression for calculation and substitution. - -Restrictions: - -* The expression must not trigger MapReduce operations. -* This functionality is fully locked in YQL over YDB. - -### Examples - -```yql -$now = CurrentUtcDate(); -SELECT EvaluateExpr( - DateTime::MakeDate(DateTime::StartOfWeek($now) - ) -); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/files.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/files.md deleted file mode 100644 index 677d9bbb6fa6..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/files.md +++ /dev/null @@ -1,62 +0,0 @@ -## FileContent and FilePath {#file-content-path} - -Both the [console](../../../interfaces/cli.md) and [web](../../../interfaces/web.md) interfaces let you "attach" arbitrary named files to your query. With these functions, you can use the name of the attached file to get its contents or the path in the sandbox, and then use it as you like in the query. - -The `FileContent` and `FilePath` argument is a string with an alias. - -### Examples - -```yql -SELECT "Content of " - || FilePath("my_file.txt") - || ":\n" - || FileContent("my_file.txt"); -``` - -## FolderPath {#folderpath} - -Getting the path to the root of a directory with several "attached" files with the common prefix specified. - -The argument is a string with a prefix among aliases. - -See also [PRAGMA File](../../../syntax/pragma.md#file) and [PRAGMA Folder](../../../syntax/pragma.md#folder). - -### Examples - -```yql -PRAGMA File("foo/1.txt", "http://url/to/somewhere"); -PRAGMA File("foo/2.txt", "http://url/to/somewhere/else"); -PRAGMA File("bar/3.txt", "http://url/to/some/other/place"); - -SELECT FolderPath("foo"); -- The directory at the return path will - -- include the files 1.txt and 2.txt downloaded from the above links -``` - -## ParseFile - -Get a list of values from the attached text file. It can be combined with [IN](../../../syntax/expressions.md#in), attaching the file by URL (see the instruction for attaching files in the {% if feature_webui %}[web interface](../../../interfaces/web.md#attach) and the {% endif %} [client](../../../interfaces/cli.md#attach)). - -Only one file format is supported: one value per line.{% if feature_udf_noncpp %} For something more sophisticated, for now you have to write a small UDF in [Python](../../../udf/python.md) or [JavaScript](../../../udf/javascript.md). {% endif %} - -Two required arguments: - -1. List cell type: only strings and numeric types are supported. -2. The name of the attached file. - -{% note info %} - -The return value is a lazy list. For repeat use, wrap it in the function [ListCollect](../../list.md#listcollect) - -{% endnote %} - -### Examples - -```yql -SELECT ListLength(ParseFile("String", "my_file.txt")); -``` - -```yql -SELECT * FROM my_table -WHERE int_column IN ParseFile("Int64", "my_file.txt"); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/find.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/find.md deleted file mode 100644 index 5a2964b91cf9..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/find.md +++ /dev/null @@ -1,58 +0,0 @@ -## FIND {#find} - -Finding the position of a substring in a string. - -Required arguments: - -* Source string; -* The substring being searched for. - -Optional arguments: - -* A position in bytes to start the search with (an integer or `NULL` by default that means "from the beginning of the source string"). - -Returns the first substring position found or `NULL` (meaning that the desired substring hasn't been found starting from the specified position). - -### Examples - -```yql -SELECT FIND("abcdefg_abcdefg", "abc"); -- 0 -``` - -```yql -SELECT FIND("abcdefg_abcdefg", "abc", 1); -- 8 -``` - -```yql -SELECT FIND("abcdefg_abcdefg", "abc", 9); -- null -``` - -## RFIND {#rfind} - -Reverse finding the position of a substring in a string, from the end to the beginning. - -Required arguments: - -* Source string; -* The substring being searched for. - -Optional arguments: - -* A position in bytes to start the search with (an integer or `NULL` by default, meaning "from the end of the source string"). - -Returns the first substring position found or `NULL` (meaning that the desired substring hasn't been found starting from the specified position). - -### Examples - -```yql -SELECT RFIND("abcdefg_abcdefg", "bcd"); -- 9 -``` - -```yql -SELECT RFIND("abcdefg_abcdefg", "bcd", 8); -- 1 -``` - -```yql -SELECT RFIND("abcdefg_abcdefg", "bcd", 0); -- null -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/if.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/if.md deleted file mode 100644 index 3267440f9bc1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/if.md +++ /dev/null @@ -1,17 +0,0 @@ -## IF {#if} - -Checks the condition: `IF(condition_expression, then_expression, else_expression)`. - -It's a simplified alternative for [CASE WHEN ... THEN ... ELSE ... END](../../../syntax/expressions.md#case). - -You may omit the `else_expression` argument. In this case, if the condition is false (`condition_expression` returned `false`), an empty value is returned with the type corresponding to `then_expression` and allowing for `NULL`. Hence, the result will have an [optional data type](../../../types/optional.md). - -### Examples - -```yql -SELECT - IF(foo > 0, bar, baz) AS bar_or_baz, - IF(foo > 0, foo) AS only_positive_foo -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/intro.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/intro.md deleted file mode 100644 index d8da1aff4f2e..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/intro.md +++ /dev/null @@ -1,4 +0,0 @@ -# Basic built-in functions - -Below are the general-purpose functions. For specialized functions, there are separate articles: [aggregate functions](../../aggregation.md){% if feature_window_functions %}, [window functions](../../window.md){% endif %}, and functions for [lists](../../list.md), [dictionaries](../../dict.md), [structures](../../struct.md), [data types](../../types.md){% if feature_codegen %}, and [code generation](../../codegen.md){% endif %}. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/length.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/length.md deleted file mode 100644 index 4bdbb2064f74..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/length.md +++ /dev/null @@ -1,19 +0,0 @@ -## LENGTH {#length} - -Returns the length of the string in bytes. This function is also available under the `LEN` name . - -### Examples - -```yql -SELECT LENGTH("foo"); -``` - -```yql -SELECT LEN("bar"); -``` - -{% note info %} - -To calculate the length of a string in Unicode characters, you can use the function [Unicode::GetLength](../../../udf/list/unicode.md).

To get the number of elements in the list, use the function [ListLength](../../list.md#listlength). - -{% endnote %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/max_min.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/max_min.md deleted file mode 100644 index 6deffb0650e8..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/max_min.md +++ /dev/null @@ -1,14 +0,0 @@ -## MAX_OF, MIN_OF, GREATEST, and LEAST {#max-min} - -Returns the minimum or maximum among N arguments. Those functions let you replace the SQL standard statement `CASE WHEN a < b THEN a ELSE b END` that would be too sophisticated for N more than two. - -The argument types must be mutually castable and accept `NULL`. - -`GREATEST` is a synonym for `MAX_OF` and `LEAST` is a synonym for `MIN_OF`. - -### Examples - -```yql -SELECT MIN_OF(1, 2, 3); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/metadata.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/metadata.md deleted file mode 100644 index fe2b988e9a62..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/metadata.md +++ /dev/null @@ -1,21 +0,0 @@ -## Access to the metadata of the current operation {#metadata} - -When you run YQL operations via the web interface or HTTP API, you get access to the following data: - -* `CurrentOperationId()`: The private ID of the operation. -* `CurrentOperationSharedId()`: The public ID of the operation. -* `CurrentAuthenticatedUser()`: The username of the current user. - -No arguments. - -If this data is missing, for example, when you run operations in the embedded mode, the functions return an empty string. - -### Examples - -```yql -SELECT - CurrentOperationId(), - CurrentOperationSharedId(), - CurrentAuthenticatedUser(); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/nanvl.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/nanvl.md deleted file mode 100644 index d894dde9d0fe..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/nanvl.md +++ /dev/null @@ -1,19 +0,0 @@ -## NANVL {#nanvl} - -Replaces the values of `NaN` (not a number) in expressions like `Float`, `Double`, or [Optional](../../../types/optional.md). - -Arguments: - -1. The expression where you want to make a replacement. -2. The value to replace `NaN`. - -If one of the arguments is `Double`, the result is`Double`, otherwise, it's `Float`. If one of the arguments is `Optional`, then the result is `Optional`. - -### Examples - -```yql -SELECT - NANVL(double_column, 0.0) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/optional_ops.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/optional_ops.md deleted file mode 100644 index 2e1f6ba5a970..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/optional_ops.md +++ /dev/null @@ -1,47 +0,0 @@ -## Just {#optional-ops} - -`Just()`: Change the value's data type to [optional](../../../types/optional.md) from the current data type (i.e.,`T` is converted to `T?`). - -The reverse operation is [Unwrap](#optional-ops). - -### Examples - -```yql -SELECT - Just("my_string"); -- String? -``` - -## Unwrap {#unwrap} - -`Unwrap()`: Converting the [optional](../../../types/optional.md) value of the data type to the relevant non-optional type, raising a runtime error if the data is `NULL`. This means that `T?` becomes `T`. - -If the value isn't [optional](../../../types/optional.md), then the function returns its first argument unchanged. - -Arguments: - -1. Value to be converted. -2. An optional string with a comment for the error text. - -Reverse operation is [Just](#optional-ops). - -### Examples - -```yql -$value = Just("value"); - -SELECT Unwrap($value, "Unexpected NULL for $value"); -``` - -## Nothing {#nothing} - -`Nothing()`: Create an empty value for the specified [Optional](../../../types/optional.md) data type. - -### Examples - -```yql -SELECT - Nothing(String?); -- an empty (NULL) value with the String? type -``` - -[Learn more about ParseType and other functions for data types](../../types.md). - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/pickle.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/pickle.md deleted file mode 100644 index dc9b9ec6df2a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/pickle.md +++ /dev/null @@ -1,19 +0,0 @@ -## Pickle, Unpickle {#pickle} - -`Pickle()` and `StablePickle()` serialize an arbitrary object into a sequence of bytes, if possible. Typical non-serializable objects are Callable and Resource. The serialization format is not versioned and can be used within a single query. For the Dict type, the StablePickle function pre-sorts the keys, and for Pickle, the order of dictionary elements in the serialized representation isn't defined. - -`Unpickle()` is the inverse operation (deserialization), where with the first argument being the data type of the result and the second argument is the string with the result of `Pickle()` or `StablePickle()`. - -### Examples - -```yql -SELECT * -FROM my_table -WHERE Digest::MurMurHash32( - Pickle(TableRow()) - ) %10 ==0; -- actually, it is better to use TABLESAMPLE - -$buf = Pickle(123); -SELECT Unpickle(Int32, $buf); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/random.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/random.md deleted file mode 100644 index e726bf7e9999..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/random.md +++ /dev/null @@ -1,73 +0,0 @@ -## Random... {#random} - -Generates a pseudorandom number: - -* `Random()`: A floating point number (Double) from 0 to 1. -* `RandomNumber()`: An integer from the complete Uint64 range. -* `RandomUuid()`: [Uuid version 4](https://tools.ietf.org/html/rfc4122#section-4.4). - -### Signatures - -```yql -Random(T1[, T2, ...])->Double -RandomNumber(T1[, T2, ...])->Uint64 -RandomUuid(T1[, T2, ...])->Uuid -``` - -No arguments are used for random number generation: they are only needed to control the time of the call. A new random number is returned at each call. Therefore: - -{% if ydb_non_deterministic_functions %} - -* If Random is called again within a **same query** and with a same set of arguments does not guarantee getting the same sets of random numbers. The values will be equal if the Random calls fall into the same execution phase. - -{% else %} - -* If Random is called again within a **same query** and with a same set of arguments, the same set of random numbers is returned. Keep in mind that we mean the arguments themselves (i.e., the text between parentheses) rather than their values. - -{% endif %} - -* Calling of Random with the same set of arguments in **different queries** returns different sets of random numbers. - -{% note warning %} - -If Random is used in [named expressions](../../../syntax/expressions.md#named-nodes), its one-time calculation is not guaranteed. Depending on the optimizers and runtime environment, it can be counted both once and multiple times. To make sure it's only counted once, materialize a named expression into a table. - -{% endnote %} - -Use cases: - -* `SELECT RANDOM(1);`: Get one random value for the entire query and use it multiple times (to get multiple random values, you can pass various constants of any type). -* `SELECT RANDOM(1) FROM table;`: The same random number for each row in the table. -* `SELECT RANDOM(1), RANDOM(2) FROM table;`: Two random numbers for each row of the table, all the numbers in each of the columns are the same. -* `SELECT RANDOM(some_column) FROM table;`: Different random numbers for each row in the table. -* `SELECT RANDOM(some_column), RANDOM(some_column) FROM table;`: Different random numbers for each row of the table, but two identical numbers within the same row. -* `SELECT RANDOM(some_column), RANDOM(some_column + 1) FROM table;` or `SELECT RANDOM(some_column), RANDOM(other_column) FROM table;`: Two columns, with different numbers in both. - -### Examples - -```yql -SELECT - Random(key) -- [0, 1) -FROM my_table; -``` - -```yql -SELECT - RandomNumber(key) -- [0, Max) -FROM my_table; -``` - -```yql -SELECT - RandomUuid(key) -- Uuid version 4 -FROM my_table; -``` - -```yql -SELECT - RANDOM(column) AS rand1, - RANDOM(column) AS rand2, -- same as rand1 - RANDOM(column, 1) AS randAnd1, -- different from rand1/2 - RANDOM(column, 2) AS randAnd2 -- different from randAnd1 -FROM my_table; -``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/s_expressions.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/s_expressions.md deleted file mode 100644 index 969b4531e6e1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/s_expressions.md +++ /dev/null @@ -1,6 +0,0 @@ -## YQL::, s-expressions {#s-expressions} - -For the full list of internal YQL functions, see the [documentation for s-expressions](/docs/s_expressions/functions), an alternative low-level YQL syntax. Any of the functions listed there can also be called from the SQL syntax by adding the `YQL::` prefix to its name. However, we don't recommend doing this, because this mechanism is primarily intended to temporarily bypass possible issues and for internal testing purposes. - -If the function is available in SQL syntax without the `YQL::` prefix, then its behavior may differ from the same-name function from the s-expressions documentation, if any. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/starts_ends_with.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/starts_ends_with.md deleted file mode 100644 index dfb984eaea30..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/starts_ends_with.md +++ /dev/null @@ -1,29 +0,0 @@ -## StartsWith, EndsWith {#starts_ends_with} - -Checking for a prefix or suffix in a string. - -Required arguments: - -* Source string; -* The substring being searched for. - -The arguments can be of the `String` or `Utf8` type and can be optional. - -### Examples - -```yql -SELECT StartsWith("abc_efg", "abc") AND EndsWith("abc_efg", "efg"); -- true -``` - -```yql -SELECT StartsWith("abc_efg", "efg") OR EndsWith("abc_efg", "abc"); -- false -``` - -```yql -SELECT StartsWith("abcd", NULL); -- null -``` - -```yql -SELECT EndsWith(NULL, Utf8("")); -- null -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/staticfold.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/staticfold.md deleted file mode 100644 index b83fda708626..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/staticfold.md +++ /dev/null @@ -1,31 +0,0 @@ -## StaticFold, StaticFold1 {#staticfold} - -```yql -StaticFold(obj:Struct/Tuple, initVal, updateLambda) -StaticFold1(obj:Struct/Tuple, initLambda, updateLambda) -``` - -Left fold over struct/tuple elements. -The folding of tuples is done in order from the element with the lower index to the element with the larger one; for structures, the order is not guaranteed. - -- `obj` - object to fold -- `initVal` - _(for StaticFold)_ initial fold state -- `initLambda` - _(for StaticFold1)_ lambda that produces initial fold state from the first element -- `updateLambda` - lambda that produces the new state (arguments are the next element and the previous state) - - -`StaticFold(<|key_1:$el_1, key_2:$el_2, ..., key_n:$el_n|>, $init, $f)` transforms into: - -```yql -$f($el_n, ...$f($el_2, $f($init, el_1))...) -``` - -`StaticFold1(<|key_1:$el_1, key_2:$el_2, ..., key_n:$el_n|>, $f0, $f)`: - -```yql -$f($el_n, ...$f($el_2, $f($f0($init), el_1))...) -``` - -`StaticFold1(<||>, $f0, $f)` returns `NULL`. - -Works with tuples in the same way. diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/staticmap.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/staticmap.md deleted file mode 100644 index 375c917404eb..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/staticmap.md +++ /dev/null @@ -1,24 +0,0 @@ -## StaticMap - -Transforms a structure or tuple by applying a lambda function to each item. - -Arguments: - -* Structure or tuple. -* Lambda for processing items. - -Result: a structure or tuple with the same number and naming of items as in the first argument, and with item data types determined by lambda results. - -### Examples - -```yql -SELECT * -FROM ( - SELECT - StaticMap(TableRow(), ($item) -> { - return CAST($item AS String); - }) - FROM my_table -) FLATTEN COLUMNS; -- converting all columns to rows -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/staticzip.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/staticzip.md deleted file mode 100644 index 566488a45749..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/staticzip.md +++ /dev/null @@ -1,16 +0,0 @@ -## StaticZip - -Merges structures or tuples element-by-element. All arguments (one or more) must be either structures with the same set of fields or tuples of the same length. -The result will be a structure or tuple, respectively. -Each item of the result is a tuple comprised of items taken from arguments. - -### Examples - -```yql -$one = <|k1:1, k2:2.0|>; -$two = <|k1:3.0, k2:4|>; - --- Adding two structures item-by-item -SELECT StaticMap(StaticZip($one, $two), ($tuple)->($tuple.0 + $tuple.1)) AS sum; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/substring.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/substring.md deleted file mode 100644 index ef5b9a5adff0..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/substring.md +++ /dev/null @@ -1,30 +0,0 @@ -## SUBSTRING {#substring} - -Returns a substring. - -Required arguments: - -* Source string; -* Position: The offset from the beginning of the string in bytes (integer) or `NULL` meaning "from the beginning". - -Optional arguments: - -* Substring length: The number of bytes starting from the specified position (an integer, or the default `NULL` meaning "up to the end of the source string"). - -Indexing starts from zero. If the specified position and length are beyond the string, returns an empty string. -If the input string is optional, the result is also optional. - -### Examples - -```yql -SELECT SUBSTRING("abcdefg", 3, 1); -- d -``` - -```yql -SELECT SUBSTRING("abcdefg", 3); -- defg -``` - -```yql -SELECT SUBSTRING("abcdefg", NULL, 3); -- abc -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/table_path_name_recindex.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/table_path_name_recindex.md deleted file mode 100644 index 4ede010bb1e0..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/table_path_name_recindex.md +++ /dev/null @@ -1,57 +0,0 @@ -## TablePath {#tablepath} - -Access to the current table name, which might be needed when you use [CONCAT](../../../syntax/select.md#concat), [RANGE](../../../syntax/select.md#range), and other related functions. - -No arguments. Returns a string with the full path or an empty string and warning when used in an unsupported context (for example, when working with a subquery or a range of 1000+ tables). - -{% note info %} - -The [TablePath](#tablepath), [TableName](#tablename), and [TableRecordIndex](#tablerecordindex) functions don't support temporary and anonymous tables (they return an empty string or 0 for [TableRecordIndex](#tablerecordindex)). -These functions are calculated when [executing](../../../syntax/select.md#selectexec) projections in `SELECT`, and by that time the current table may already be temporary. -To avoid such a situation, create a subquery for calculating these functions, as shown in the second example below. - -{% endnote %} - -### Examples - -```yql -SELECT TablePath() FROM CONCAT(table_a, table_b); -``` - -```yql -SELECT key, tpath_ AS path FROM (SELECT a.*, TablePath() AS tpath_ FROM RANGE(`my_folder`) AS a) -WHERE key IN $subquery; -``` - -## TableName {#tablename} - -Get the table name based on the table path. You can obtain the path using the [TablePath](#tablepath) function or as the `Path` column when using the table function [FOLDER](../../../syntax/select.md#folder). - -Optional arguments: - -* Path to the table, `TablePath()` is used by default (see also its limitations). -* Specifying the system ("yt") whose rules are used to determine the table name. You need to specify the system only if [USE](../../../syntax/select.md#use) doesn't specify the current cluster. - -### Examples - -```yql -USE hahn; -SELECT TableName() FROM CONCAT(table_a, table_b); -``` - -```yql -SELECT TableName(Path, "yt") FROM hahn.FOLDER(folder_name); -``` - -## TableRecordIndex {#tablerecordindex} - -Access to the current sequence number of a row in the physical source table, **starting from 1** (depends on the storage implementation). - -No arguments. When used in combination with [CONCAT](../../../syntax/select.md#concat), [RANGE](../../../syntax/select.md#range) and other similar mechanisms, numbering restarts for each input table. If used in an incorrect context, it returns 0. - -### Example - -```yql -SELECT TableRecordIndex() FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/table_row.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/table_row.md deleted file mode 100644 index f102e5588e7c..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/table_row.md +++ /dev/null @@ -1,10 +0,0 @@ -## TableRow{% if feature_join %}, JoinTableRow{% endif %} {#tablerow} - -Getting the entire table row as a structure. No arguments{% if feature_join %}. `JoinTableRow` in case of `JOIN` always returns a structure with table prefixes{% endif %}. - -### Example - -```yql -SELECT TableRow() FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/to_from_bytes.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/to_from_bytes.md deleted file mode 100644 index 2cfbcc55c13d..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/to_from_bytes.md +++ /dev/null @@ -1,15 +0,0 @@ -## ToBytes and FromBytes {#to-from-bytes} - -Conversion of [primitive data types](../../../types/primitive.md) to a string with their binary representation and back. Numbers are represented in the [little endian](https://en.wikipedia.org/wiki/Endianness#Little-endian) format. - -### Examples - -```yql -SELECT - ToBytes(123), -- "\u0001\u0000\u0000\u0000" - FromBytes( - "\xd2\x02\x96\x49\x00\x00\x00\x00", - Uint64 - ); -- 1234567890ul -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/variant.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/variant.md deleted file mode 100644 index 93d3148d6835..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/variant.md +++ /dev/null @@ -1,116 +0,0 @@ -## Variant {#variant} - -`Variant()` creates a variant value over a tuple or structure. - -Arguments: - -* Value -* String with a field name or tuple index -* Variant type - -### Example - -```yql -$var_type = Variant; - -SELECT - Variant(6, "foo", $var_type) as Variant1Value, - Variant(false, "bar", $var_type) as Variant2Value; -``` - -## AsVariant {#asvariant} - -`AsVariant()` creates a value of a [variant over a structure](../../../types/containers.md) including one field. This value can be implicitly converted to any variant over a structure that has a matching data type for this field name and might include more fields with other names. - -Arguments: - -* Value -* A string with the field name - -### Example - -```yql -SELECT - AsVariant(6, "foo") as VariantValue -``` - -## Visit, VisitOrDefault {#visit} - -Processes the possible values of a variant over a structure or tuple using the provided handler functions for each field/element of the variant. - -### Signature - -```yql -Visit(Variant, K1->R AS key1, K2->R AS key2, ...)->R -Visit(Variant, K1->R, K2->R, ...)->R - -VisitOrDefault(Variant{Flags:AutoMap}, R, [K1->R, [K2->R, ...]])->R -VisitOrDefault(Variant{Flags:AutoMap}, R, [K1->R AS key1, [K2->R AS key2, ...]])->R -``` - -### Arguments - -* For a variant over structure: accepts the variant as the positional argument and named arguments (handlers) corresponding to each field of the variant. -* For a variant over tuple: accepts the variant and handlers for each element of the variant as positional arguments. -* `VisitOrDefault` includes an additional positional argument (on the second place) for the default value, enabling the omission of certain handlers. - -### Example - -```yql -$vartype = Variant; -$handle_num = ($x) -> { return 2 * $x; }; -$handle_flag = ($x) -> { return If($x, 200, 10); }; -$handle_str = ($x) -> { return Unwrap(CAST(LENGTH($x) AS Int32)); }; - -$visitor = ($var) -> { return Visit($var, $handle_num AS num, $handle_flag AS flag, $handle_str AS str); }; -SELECT - $visitor(Variant(5, "num", $vartype)), -- 10 - $visitor(Just(Variant(True, "flag", $vartype))), -- Just(200) - $visitor(Just(Variant("somestr", "str", $vartype))), -- Just(7) - $visitor(Nothing(OptionalType($vartype))), -- Nothing(Optional) - $visitor(NULL) -- NULL -; -``` - -## VariantItem {#variantitem} - -Returns the value of a homogeneous variant (i.e., a variant containing fields/elements of the same type). - -### Signature - -```yql -VariantItem(Variant{Flags:AutoMap})->K -VariantItem(Variant{Flags:AutoMap})->K -``` - -### Example - -```yql -$vartype1 = Variant; -SELECT - VariantItem(Variant(7, "num2", $vartype1)), -- 7 - VariantItem(Just(Variant(5, "num1", $vartype1))), -- Just(5) - VariantItem(Nothing(OptionalType($vartype1))), -- Nothing(Optional) - VariantItem(NULL) -- NULL -; -``` - -## Way {#way} - -Returns an active field (active index) of a variant over a struct (tuple). - -### Signature - -```yql -Way(Variant{Flags:AutoMap})->Utf8 -Way(Variant{Flags:AutoMap})->Uint32 -``` - -### Example - -```yql -$vr = Variant(1, "0", Variant); -$vrs = Variant(1, "a", Variant); -SELECT Way($vr); -- 0 -SELECT Way($vrs); -- "a" -``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/version.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/version.md deleted file mode 100644 index 60664c76f8f4..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/version.md +++ /dev/null @@ -1,10 +0,0 @@ -## Version {#version} - -`Version()` returns a string describing the current version of the node processing the request. In some cases, such as during rolling upgrades, it might return different strings depending on which node processes the request. It does not accept any arguments. - -### Examples - -```yql -SELECT Version(); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/weakfield.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/weakfield.md deleted file mode 100644 index 38d20617136e..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/basic/weakfield.md +++ /dev/null @@ -1,17 +0,0 @@ -## WeakField {#weakfield} - -Fetches a table column from a strong schema, if it is in a strong schema, or from the `_other` and `_rest` fields. If the value is missing, it returns `NULL`. - -Syntax: `WeakField([
.], [, ])`. - -The default value is used only if the column is missing in the data schema. To use the default value in any case, use [COALESCE](#coalesce). - -### Examples - -```yql -SELECT - WeakField(my_column, String, "no value"), - WeakField(my_table.other_column, Int64) -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/index.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/index.md deleted file mode 100644 index b5fa068ca412..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/index.md +++ /dev/null @@ -1,25 +0,0 @@ -# Built-in YQL functions - -- [Basic](../basic.md) -- [Aggregate](../aggregation.md) - -{% if feature_window_functions %} - -- [Window](../window.md) - -{% endif %} - -- [For lists](../list.md) -- [For dictionaries](../dict.md) -- [For structures](../struct.md) -- [For types](../types.md) - -{% if feature_codegen %} - -- [For code generation](../codegen.md) - -{% endif %} - -- [For JSON](../json.md) -- [C++ libraries](../../udf/list/index.md) - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/aggregate.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/aggregate.md deleted file mode 100644 index a5bb92dd149a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/aggregate.md +++ /dev/null @@ -1,17 +0,0 @@ -## Aggregate functions {#aggregate-functions} - -All [aggregate functions](../../aggregation.md) can also be used as window functions. -In this case, each row includes an aggregation result obtained on a set of rows from the [window frame](../../../syntax/window.md#frame). - -### Examples - -```yql -SELECT - SUM(int_column) OVER w1 AS running_total, - SUM(int_column) OVER w2 AS total, -FROM my_table -WINDOW - w1 AS (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), - w2 AS (); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/cume_dist.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/cume_dist.md deleted file mode 100644 index df72ad5873d1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/cume_dist.md +++ /dev/null @@ -1,18 +0,0 @@ -## CUME_DIST - -Returns the relative position (> 0 and <= 1) of a row within a [partition](../../../syntax/window.md#partition). No arguments. - -### Signature - -```yql -CUME_DIST()->Double -``` - -### Examples - -```yql -SELECT - CUME_DIST() OVER w AS dist -FROM my_table -WINDOW w AS (ORDER BY key); -``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/first_last_value.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/first_last_value.md deleted file mode 100644 index a03f6df2503a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/first_last_value.md +++ /dev/null @@ -1,29 +0,0 @@ -## FIRST_VALUE / LAST_VALUE - -Access values from the first and last rows (using the `ORDER BY` clause for the window) of the [window frame](../../../syntax/window.md#frame). The only argument is the expression that you need to access. - -Optionally, `OVER` can be preceded by the additional modifier `IGNORE NULLS`. It changes the behavior of functions to the first or last **non-empty** (i.e., non-`NULL`) value among the window frame rows. The antonym of this modifier is `RESPECT NULLS`: it's the default behavior that can be omitted. - -### Signature - -```yql -FIRST_VALUE(T)->T? -LAST_VALUE(T)->T? -``` - -### Examples - -```yql -SELECT - FIRST_VALUE(my_column) OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` - -```yql -SELECT - LAST_VALUE(my_column) IGNORE NULLS OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/intro.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/intro.md deleted file mode 100644 index f1f627c3e934..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/intro.md +++ /dev/null @@ -1,4 +0,0 @@ -# List of window functions in YQL - -The syntax for calling window functions is detailed in a [separate article](../../../syntax/window.md). - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/lag_lead.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/lag_lead.md deleted file mode 100644 index 8e29730be1e3..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/lag_lead.md +++ /dev/null @@ -1,44 +0,0 @@ -## LAG / LEAD {#lag-lead} - -Accessing a value from a row in the [section](../../../syntax/window.md#partition) that lags behind (`LAG`) or leads (`LEAD`) the current row by a fixed number. The first argument specifies the expression to be accessed, and the second argument specifies the offset in rows. You may omit the offset. By default, the neighbor row is used: the previous or next, respectively (hence, 1 is assumed by default). For the rows having no neighbors at a given distance (for example, `LAG(expr, 3)` `NULL` is returned in the first and second rows of the section). - -### Signature - -```yql -LEAD(T[,Int32])->T? -LAG(T[,Int32])->T? -``` - -### Examples - -```yql -SELECT - int_value - LAG(int_value) OVER w AS int_value_diff -FROM my_table -WINDOW w AS (ORDER BY key); -``` - -```yql -SELECT item, odd, LAG(item, 1) OVER w as lag1 FROM ( - SELECT item, item % 2 as odd FROM ( - SELECT AsList(1, 2, 3, 4, 5, 6, 7) as item - ) - FLATTEN BY item -) -WINDOW w As ( - PARTITION BY odd - ORDER BY item -); - -/* Output: -item odd lag1 --------------------- -2 0 NULL -4 0 2 -6 0 4 -1 1 NULL -3 1 1 -5 1 3 -7 1 5 -*/ -``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/nth_value.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/nth_value.md deleted file mode 100644 index 7cc0dc0e9487..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/nth_value.md +++ /dev/null @@ -1,29 +0,0 @@ -## NTH_VALUE - -Access a value from a row specified by position in the window's `ORDER BY` order within [window frame](../../../syntax/window.md#frame). Arguments - the expression to access and the row number, starting with 1. - -Optionally, the `IGNORE NULLS` modifier can be specified before `OVER`, which causes rows with `NULL` in the first argument's value to be skipped. The antonym of this modifier is `RESPECT NULLS`, which is the default behavior and may be skipped. - -### Signature - -```yql -NTH_VALUE(T,N)->T? -``` - -### Examples - -```yql -SELECT - NTH_VALUE(my_column, 2) OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` - -```yql -SELECT - NTH_VALUE(my_column, 3) IGNORE NULLS OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` - - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/ntile.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/ntile.md deleted file mode 100644 index 52c772ff6221..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/ntile.md +++ /dev/null @@ -1,19 +0,0 @@ -## NTILE - -Distributes the rows of an ordered [partition](../../../syntax/window.md#partition) into a specified number of groups. The groups are numbered starting with one. For each row, the `NTILE` function returns the number of the group to which the row belongs. - -### Signature - -```yql -NTILE(Uint64)->Uint64 -``` - -### Examples - -```yql -SELECT - NTILE(10) OVER w AS group_num -FROM my_table -WINDOW w AS (ORDER BY key); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/rank_dense.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/rank_dense.md deleted file mode 100644 index 42732e8be379..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/rank_dense.md +++ /dev/null @@ -1,44 +0,0 @@ -## RANK / DENSE_RANK / PERCENT_RANK {#rank} - -Number the groups of neighboring rows in the [partition](../../../syntax/window.md#partition) with the same expression value in the argument. `DENSE_RANK` numbers the groups one by one, and `RANK` skips `(N - 1)` values, with `N` being the number of rows in the previous group. `PERCENT_RANK` returns the relative rank of the current row: $(RANK - 1)/(number of rows in the partition - 1)$. - -If there is no argument, it uses the order specified in the `ORDER BY` section in the window definition. -If the argument is omitted and `ORDER BY` is not specified, then all rows are considered equal to each other. - -{% note info %} - -Passing an argument to `RANK`/`DENSE_RANK`/`PERCENT_RANK` is a non-standard extension in YQL. - -{% endnote %} - -### Signature - -```text -RANK([T])->Uint64 -DENSE_RANK([T])->Uint64 -PERCENT_RANK([T])->Double -``` - -### Examples - -```yql -SELECT - RANK(my_column) OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` - -```yql -SELECT - DENSE_RANK() OVER w -FROM my_table -WINDOW w AS (ORDER BY my_column); -``` - -```yql -SELECT - PERCENT_RANK() OVER w -FROM my_table -WINDOW w AS (ORDER BY my_column); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/row_number.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/row_number.md deleted file mode 100644 index 4618327298ca..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/row_number.md +++ /dev/null @@ -1,19 +0,0 @@ -## ROW_NUMBER {#row_number} - -Row number within a [partition](../../../syntax/window.md#partition). No arguments. - -### Signature - -```yql -ROW_NUMBER()->Uint64 -``` - -### Examples - -```yql -SELECT - ROW_NUMBER() OVER w AS row_num -FROM my_table -WINDOW w AS (ORDER BY key); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/session_state.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/session_state.md deleted file mode 100644 index 241d78b7445f..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/_includes/window/session_state.md +++ /dev/null @@ -1,5 +0,0 @@ -## SessionState() {#session-state} - -A non-standard window function `SessionState()` (without arguments) lets you get the session calculation status from [SessionWindow](../../../syntax/group_by.md#session-window) for the current row. -It's allowed only if `SessionWindow()` is present in the `PARTITION BY` section in the window definition. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/aggregation.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/aggregation.md deleted file mode 100644 index 6200d2633f3f..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/aggregation.md +++ /dev/null @@ -1,31 +0,0 @@ -# Aggregate functions - -{% include [simple.md](_includes/aggregation/simple.md) %} - -{% include [count_distinct_estimate.md](_includes/aggregation/count_distinct_estimate.md) %} - -{% include [agg_list.md](_includes/aggregation/agg_list.md) %} - -{% include [max_min_by.md](_includes/aggregation/max_min_by.md) %} - -{% include [top_bottom.md](_includes/aggregation/top_bottom.md) %} - -{% include [topfreq_mode.md](_includes/aggregation/topfreq_mode.md) %} - -{% include [stddev_variance.md](_includes/aggregation/stddev_variance.md) %} - -{% include [corr_covar.md](_includes/aggregation/corr_covar.md) %} - -{% include [percentile_median.md](_includes/aggregation/percentile_median.md) %} - -{% include [histogram.md](_includes/aggregation/histogram.md) %} - -{% include [bool_bit.md](_includes/aggregation/bool_bit.md) %} - -{% if feature_window_functions %} - - {% include [session_start.md](_includes/aggregation/session_start.md) %} - -{% endif %} - -{% include [aggregate_by.md](_includes/aggregation/aggregate_by.md) %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/basic.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/basic.md deleted file mode 100644 index 0ebaebe9b8c1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/basic.md +++ /dev/null @@ -1,96 +0,0 @@ - -{% include [x](_includes/basic/intro.md) %} - -{% include [x](_includes/basic/coalesce.md) %} - -{% include [x](_includes/basic/length.md) %} - -{% include [x](_includes/basic/substring.md) %} - -{% include [x](_includes/basic/find.md) %} - -{% include [x](_includes/basic/starts_ends_with.md) %} - -{% include [x](_includes/basic/if.md) %} - -{% include [x](_includes/basic/nanvl.md) %} - -{% include [x](_includes/basic/random.md) %} - -{% include [x](_includes/basic/current_utc.md) %} - -{% include [x](_includes/basic/current_tz.md) %} - -{% include [x](_includes/basic/version.md) %} - -{% include [x](_includes/basic/max_min.md) %} - -{% include [x](_includes/basic/as_container.md) %} - -{% include [x](_includes/basic/container_literal.md) %} - -{% include [x](_includes/basic/variant.md) %} - -{% include [x](_includes/basic/enum.md) %} - -{% include [x](_includes/basic/as_tagged.md) %} - -{% if feature_bulk_tables %} - - {% include [x](_includes/basic/table_path_name_recindex.md) %} - -{% endif %} - -{% include [x](_includes/basic/table_row.md) %} - -{% if feature_mapreduce %} - - {% include [x](_includes/basic/files.md) %} - - {% include [x](_includes/basic/weakfield.md) %} - -{% endif %} - -{% include [x](_includes/basic/ensure.md) %} - -{% if feature_codegen %} - - {% include [x](_includes/basic/evaluate_expr_atom.md) %} - -{% endif %} - -{% include [x](_includes/basic/data-type-literals.md) %} - -{% if feature_webui %} - - {% include [x](_includes/basic/metadata.md) %} - -{% endif %} - -{% include [x](_includes/basic/to_from_bytes.md) %} - -{% include [x](_includes/basic/byteat.md) %} - -{% include [x](_includes/basic/bitops.md) %} - -{% include [x](_includes/basic/abs.md) %} - -{% include [x](_includes/basic/optional_ops.md) %} - -{% include [x](_includes/basic/callable.md) %} - -{% include [x](_includes/basic/pickle.md) %} - -{% include [x](_includes/basic/staticmap.md) %} - -{% include [x](_includes/basic/staticzip.md) %} - -{% include [x](_includes/basic/staticfold.md) %} - -{% include [x](_includes/basic/aggr_factory.md) %} - -{% if tech %} - - {% include [x](_includes/basic/s_expressions.md) %} - -{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/codegen.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/codegen.md deleted file mode 100644 index 2e056a320ac6..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/codegen.md +++ /dev/null @@ -1 +0,0 @@ -{% include [codegen.md](_includes/codegen.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/dict.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/dict.md deleted file mode 100644 index 30209a90f9e9..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/dict.md +++ /dev/null @@ -1 +0,0 @@ -{% include [dict.md](_includes/dict.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/index.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/index.md deleted file mode 100644 index aabc04374297..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/index.md +++ /dev/null @@ -1 +0,0 @@ -{% include [index.md](_includes/index.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/json.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/json.md deleted file mode 100644 index 35941753a761..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/json.md +++ /dev/null @@ -1 +0,0 @@ -{% include [json.md](_includes/json.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/list.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/list.md deleted file mode 100644 index c4126fa2cd14..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/list.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/list.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/struct.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/struct.md deleted file mode 100644 index 9990243edda7..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/struct.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/struct.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/types.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/types.md deleted file mode 100644 index 6c4e9a5a7811..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/types.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/types.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/builtins/window.md b/ydb/docs/en/core/yql/reference/yql-core/builtins/window.md deleted file mode 100644 index 62b1b2bf70be..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/builtins/window.md +++ /dev/null @@ -1,20 +0,0 @@ - -{% include [x](_includes/window/intro.md) %} - -{% include [x](_includes/window/aggregate.md) %} - -{% include [x](_includes/window/row_number.md) %} - -{% include [x](_includes/window/lag_lead.md) %} - -{% include [x](_includes/window/first_last_value.md) %} - -{% include [x](_includes/window/nth_value.md) %} - -{% include [x](_includes/window/rank_dense.md) %} - -{% include [x](_includes/window/ntile.md) %} - -{% include [x](_includes/window/cume_dist.md) %} - -{% include [x](_includes/window/session_state.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/Readme.txt b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/Readme.txt deleted file mode 100644 index 163838f91a7e..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/Readme.txt +++ /dev/null @@ -1 +0,0 @@ -Files inside this folder represent YQL base blocks, and may NOT contain product-conditional or corporate content. diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/action/begin.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/action/begin.md deleted file mode 100644 index b41eaa28ff4c..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/action/begin.md +++ /dev/null @@ -1,21 +0,0 @@ -## BEGIN .. END DO {#begin} - -Performing an action without declaring it (anonymous action). - -### Syntax - -1. `BEGIN`. -1. List of top-level expressions. -1. `END DO`. - -An anonymous action can't include any parameters. - -### Example - -```yql -DO BEGIN - SELECT 1; - SELECT 2 -- here and in the previous example, you might omit ';' before END -END DO -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/action/define_do.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/action/define_do.md deleted file mode 100644 index db476f2b9366..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/action/define_do.md +++ /dev/null @@ -1,51 +0,0 @@ -## DEFINE ACTION {#define-action} - -Specifies a named action that is a parameterizable block of multiple top-level expressions. - -### Syntax - -1. `DEFINE ACTION`: action definition. -1. [Action name](../../expressions.md#named-nodes) that will be used to access the defined action further in the query. -1. The values of parameter names are listed in parentheses. -1. `AS` keyword. -1. List of top-level expressions. -1. `END DEFINE`: The marker of the last expression inside the action. - -One or more of the last parameters can be marked with a question mark `?` as optional. If they are omitted during the call, they will be assigned the `NULL` value. - -## DO {#do} - -Executes an `ACTION` with the specified parameters. - -### Syntax - -1. `DO`: Executing an action. -1. The named expression for which the action is defined. -1. The values to be used as parameters are listed in parentheses. - -`EMPTY_ACTION`: An action that does nothing. - -{% if feature_mapreduce %} - -{% note info %} - -In large queries, you can use separate files for action definition and include them to the main query using [EXPORT](../../export_import.md#export) + [IMPORT](../../export_import.md#import) so that instead of one long text you can have several logical parts that are easier to navigate. An important nuance: the `USE my_cluster;` directive in the import query does not affect behavior of actions declared in other files. - -{% endnote %} - -{% endif %} - -### Example - -```yql -DEFINE ACTION $hello_world($name, $suffix?) AS - $name = $name ?? ($suffix ?? "world"); - SELECT "Hello, " || $name || "!"; -END DEFINE; - -DO EMPTY_ACTION(); -DO $hello_world(NULL); -DO $hello_world("John"); -DO $hello_world(NULL, "Earth"); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/action/evaluate.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/action/evaluate.md deleted file mode 100644 index ffa3390e6335..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/action/evaluate.md +++ /dev/null @@ -1,76 +0,0 @@ -## EVALUATE IF {#evaluate-if} - -`EVALUATE IF`: Executing an action depending on the condition. It's followed by: - -1. Condition. -2. [DO](#do) with the name and parameters of the action or an anonymous action. -3. An optional `ELSE` followed by the second `DO` for a situation where the condition is not met. - -## EVALUATE FOR {#evaluate-for} - -`EVALUATE FOR`: Executing an action for each item in the list. It's followed by: - -1. [A named expression](../../expressions.md#named-nodes) applied to each next element in the list. -2. `IN` keyword. -3. The above-declared named expression applied to the list the action is executed on. -4. [DO](#do) with the name and parameters of an action or an anonymous action. In the parameters, you can use both the current element from the first paragraph and any named expressions declared above, including the list itself. -5. An optional `ELSE` followed by the second `DO` for the situation when the list is empty. - -### Examples - -```yql -DEFINE ACTION $hello() AS - SELECT "Hello!"; -END DEFINE; - -DEFINE ACTION $bye() AS - SELECT "Bye!"; -END DEFINE; - -EVALUATE IF RANDOM(0) > 0.5 - DO $hello() -ELSE - DO $bye(); - -EVALUATE IF RANDOM(0) > 0.1 DO BEGIN - SELECT "Hello!"; -END DO; - -EVALUATE FOR $i IN AsList(1, 2, 3) DO BEGIN - SELECT $i; -END DO; -``` - -```yql --- copy the $input table to $count of new tables -$count = 3; -$input = "my_input"; -$inputs = ListReplicate($input, $count); -$outputs = ListMap( - ListFromRange(0, $count), - ($i) -> { - RETURN "tmp/out_" || CAST($i as String) - } -); -$pairs = ListZip($inputs, $outputs); - -DEFINE ACTION $copy_table($pair) as - $input = $pair.0; - $output = $pair.1; - INSERT INTO $output WITH TRUNCATE - SELECT * FROM $input; -END DEFINE; - -EVALUATE FOR $pair IN $pairs - DO $copy_table($pair) -ELSE - DO EMPTY_ACTION (); -- you may omit this ELSE, - -- do nothing is implied by default -``` - -{% note info %} - -Note that `EVALUATE` is run before the operation starts. Please also note that in `EVALUATE` you can't use [anonymous tables](../../select.md#temporary-tables). - -{% endnote %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/commit.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/commit.md deleted file mode 100644 index 57f171ccc40b..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/commit.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/select/commit.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md deleted file mode 100644 index bd959b7c1f93..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/create_table.md +++ /dev/null @@ -1,305 +0,0 @@ -# CREATE TABLE - -{% if feature_olap_tables %} - -{{ ydb-short-name }} supports two types of tables: - -* [Row-oriented](../../../../concepts/datamodel/table.md) -* [Column-oriented](../../../../concepts/datamodel/table.md#olap-data-types). - -When you create a table, the table type is specified by the `STORE` parameter, with `ROW` creating a [row-oriented table](#row) and `COLUMN` creating a [column](#olap-tables)-oriented table. If the `STORE` parameter is omitted, a row-oriented table is created by default. - -{% endif %} - -{% if feature_olap_tables %} - -## Row-oriented tables {#row} - -{% endif %} - -{% if feature_bulk_tables %} - -The table is created automatically during the first [INSERT INTO](insert_into.md){% if feature_mapreduce %} in the database specified in [USE](../use.md){% endif %}. The schema is determined automatically. - -{% else %} - -The `CREATE TABLE` call creates a {% if concept_table %}[table]({{ concept_table }}){% else %}table{% endif %} with the specified data schema{% if feature_map_tables %} and key columns (`PRIMARY KEY`){% endif %}. {% if feature_secondary_index == true %}It lets you define secondary indexes on the created table.{% endif %} - - CREATE [TEMPORARY | TEMP] TABLE table_name ( - column1 type1, -{% if feature_not_null == true %} column2 type2 NOT NULL,{% else %} column2 type2,{% endif %} - ... - columnN typeN, -{% if feature_secondary_index == true %} - INDEX index1_name GLOBAL ON ( column ), - INDEX index2_name GLOBAL ON ( column1, column2, ... ), -{% endif %} -{% if feature_map_tables %} - PRIMARY KEY ( column, ... ), - FAMILY column_family ( family_options, ... ) -{% else %} - ... -{% endif %} - ) -{% if feature_map_tables %} - WITH ( key = value, ... ) -{% endif %} - -{% if feature_olap_tables %}#{% endif %}## Columns {#row-columns} - -{% if feature_column_container_type == true %} - -In non-key columns, you can use any data types, but for key columns, only [primitive ones](../../types/primitive.md). When specifying complex types (for example, `List`), the type is enclosed in double quotes. - -{% else %} - -For the key and non-key columns, you can only use [primitive](../../types/primitive.md) data types. - -{% endif %} - -{% if feature_not_null == true %} - -Without additional modifiers, a column gets an [optional type](../../types/optional.md) and allows `NULL` values to be written. To create a non-optional type, use `NOT NULL`. - -{% else %} - -{% if feature_not_null_for_pk %} - -All columns are [optional](../../types/optional.md) by default and can be assigned NULL values. The `NOT NULL` limit can only be specified for columns that are part of the primary key.. - -{% else %} - -All columns allow writing `NULL` values, that is, they are [optional](../../types/optional.md). - -{% endif %} - -{% endif %} - -{% if feature_map_tables %} - -It is mandatory to specify the `PRIMARY KEY` with a non-empty list of columns. Those columns become part of the key in the listed order. - -{% endif %} - -### Example - - CREATE TABLE my_table ( -{% if feature_not_null_for_pk %} a Uint64 NOT NULL,{% else %} a Uint64,{% endif %} - b Bool, -{% if feature_not_null %} c Float NOT NULL,{% else %} c Float,{% endif %} -{% if feature_column_container_type %} d "List>"{% endif %} -{% if feature_map_tables %} - PRIMARY KEY (b, a) -{% endif %} - ) - -{% if feature_secondary_index %} - -{% if feature_olap_tables %}#{% endif %}## Secondary indexes {#secondary_index} - -The `INDEX` clause is used to define a {% if concept_secondary_index %}[secondary index]({{ concept_secondary_index }}){% else %}secondary index{% endif %} in a table: - -```yql -CREATE TABLE table_name ( - ... - INDEX GLOBAL [UNIQUE] [SYNC|ASYNC] ON ( ) COVER ( ), - ... -) -``` - -Where: - -* **Index_name** is the unique name of the index to be used to access data. -* **SYNC/ASYNC** indicates synchronous/asynchronous data writes to the index. If not specified, synchronous. -* **UNIQUE** indicates that the index should guarantee the uniqueness of the indexed column set, thereby enforcing the unique constraint. -* **Index_columns** is a list of comma-separated names of columns in the created table to be used for a search in the index. -* **Cover_columns** is a list of comma-separated names of columns in the created table, which will be stored in the index in addition to the search columns, making it possible to fetch additional data without accessing the table for it. - -#### Example - -```yql -CREATE TABLE my_table ( - a Uint64, - b Bool, - c Utf8, - d Date, - INDEX idx_d GLOBAL ON (d), - INDEX idx_ba GLOBAL ASYNC ON (b, a) COVER (c), - INDEX idx_bc GLOBAL UNIQUE SYNC ON (b, c), - PRIMARY KEY (a) -) -``` -{% endif %} - -{% if feature_temp_tables %} - -{% if feature_olap_tables %}#{%endif%}## Creating a temporary table {#temporary_tables} -```yql -CREATE TEMPORARY TABLE table_name ( - ... -); -``` - -{% include [temp-table-description.md](../../../../_includes/temp-table-description.md) %} - -{% endif %} - -{% if feature_map_tables and concept_table %} - -{% if feature_olap_tables %}#{% endif %}## Additional parameters {#row-additional} - -You can also specify a number of {{ backend_name }}-specific parameters for the table. When you create a table, those parameters are listed in the ```WITH``` clause: - -```yql -CREATE TABLE table_name (...) -WITH ( - key1 = value1, - key2 = value2, - ... -) -``` - -Here, key is the name of the parameter and value is its value. - -For a list of valid parameter names and values, see the [{{ backend_name }} table description]({{ concept_table }}). - -For example, this code will create a table with enabled automatic partitioning by partition size and the preferred size of each partition is 512 MB: - -```yql -CREATE TABLE my_table ( - id Uint64, - title Utf8, - PRIMARY KEY (id) -) -WITH ( - AUTO_PARTITIONING_BY_SIZE = ENABLED, - AUTO_PARTITIONING_PARTITION_SIZE_MB = 512 -); -``` - -{% if feature_olap_tables %}#{% endif %}## Column groups {#column-family} - -Columns of the same table can be grouped to set the following parameters: - -* `DATA`: A storage device type for the data in this column group. Acceptable values: ```ssd```, ```rot```. -* `COMPRESSION`: A data compression codec. Acceptable values: ```off```, ```lz4```. - -By default, all columns are in the same group named ```default```. If necessary, the parameters of this group can also be redefined. - -In the example below, for the created table, the ```family_large``` group of columns is added and set for the ```series_info``` column, and the parameters for the default group, which is set by ```default``` for all other columns, are also redefined. - -```yql -CREATE TABLE series_with_families ( - series_id Uint64, - title Utf8, - series_info Utf8 FAMILY family_large, - release_date Uint64, - PRIMARY KEY (series_id), - FAMILY default ( - DATA = "ssd", - COMPRESSION = "off" - ), - FAMILY family_large ( - DATA = "rot", - COMPRESSION = "lz4" - ) -); -``` - -{% note info %} - -Available types of storage devices depend on the {{ ydb-short-name }} cluster configuration. - -{% endnote %} - -{% endif %} - -{% endif %} - -{% if feature_olap_tables %} - -## Сolumn-oriented tables {#olap-tables} - -{% note warning %} - -Column-oriented {{ ydb-short-name }} tables are in the Preview mode. - -{% endnote %} - -The `CREATE TABLE` statement creates a [column-oriented](../../../../concepts/datamodel/table.md#olap-data-types) table with the specified data schema and key columns (`PRIMARY KEY`). - -```yql -CREATE TABLE table_name ( - column1 type1, - column2 type2 NOT NULL, - column2 type2, - ... - columnN typeN, - PRIMARY KEY ( column, ... ), - ... -) -PARTITION BY HASH(column1, column2, ...) -WITH ( - STORE = COLUMN, - key = value, - ... -) -``` - -### Columns {#olap-columns} - -Data types supported by column-oriented tables and constraints imposed on data types in primary keys or data columns are described in the [supported data types](../../../../concepts/datamodel/table.md#olap-data-types) section for column-oriented tables. - -Make sure to add the `PRIMARY KEY` and `PARTITION BY` clauses with a non-empty list of columns. - -If you omit modifiers, a column is assigned an [optional](../../types/optional.md) type and can accept `NULL` values. To create a non-optional type, use `NOT NULL`. - -#### Example - -```yql -CREATE TABLE my_table ( - a Uint64 NOT NULL, - b String, - c Float, - PRIMARY KEY (b, a) -) -PARTITION BY HASH(b) -WITH ( - STORE = COLUMN -) -``` - -### Additional parameters {#olap-additional} - -You can also specify a number of {{ backend_name }}-specific parameters for the table. When you create a table, those parameters are listed in the ```WITH``` clause: - -```yql -CREATE TABLE table_name (...) -WITH ( - key1 = value1, - key2 = value2, - ... -) -``` - -Here, `key` is the name of the parameter and `value` is its value. - -Supported parameters in column-oriented tables: - -* `AUTO_PARTITIONING_MIN_PARTITIONS_COUNT` sets the minimum physical number of partitions used to store data (see [{#T}](../../../../concepts/datamodel/table.md#olap-tables-partitioning)). - -For example, the following code creates a column-oriented table with ten partitions: - -```yql -CREATE TABLE my_table ( - id Uint64, - title Utf8, - PRIMARY KEY (id) -) -PARTITION BY HASH(id) -WITH ( - AUTO_PARTITIONING_MIN_PARTITIONS_COUNT = 10 -); -``` - -{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/discard.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/discard.md deleted file mode 100644 index 403003b21aae..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/discard.md +++ /dev/null @@ -1,31 +0,0 @@ -# DISCARD - -Calculates {% if select_command == "SELECT STREAM" %}[`SELECT STREAM`](../select_stream.md){% else %}[`SELECT`](../select/index.md){% endif %}{% if feature_mapreduce %}{% if reduce_command %}, [`{{ reduce_command }}`](../reduce.md){% endif %}, or [`{{ process_command }}`](../process.md){% endif %} without returning the result neither to the client or table.{% if feature_mapreduce %} You can't use it along with [INTO RESULT](../into_result.md).{% endif %} - -It's good to combine it with [`Ensure`](../../builtins/basic.md#ensure) to check the final calculation result against the user's criteria. - -{% if select_command != true or select_command == "SELECT" %} - -## Examples - -```yql -DISCARD SELECT 1; -``` - -```yql -INSERT INTO result_table WITH TRUNCATE -SELECT * FROM -my_table -WHERE value % 2 == 0; - -COMMIT; - -DISCARD SELECT Ensure( - 0, -- will discard result anyway - COUNT(*) > 1000, - "Too small result table, got only " || CAST(COUNT(*) AS String) || " rows" -) FROM result_table; -``` - -{% endif %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/as.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/as.md deleted file mode 100644 index c7496e0f6929..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/as.md +++ /dev/null @@ -1,44 +0,0 @@ -## AS {#as} - -Can be used in the following scenarios: - -* Adding a short name (alias) for columns or tables within the query. -* Using named arguments in function calls. -* To specify the target type in the case of explicit type casting, see [CAST](../../../syntax/expressions.md#cast). - -### Examples - -{% if select_command != "SELECT STREAM" %} - -```yql -SELECT key AS k FROM my_table; -``` - -```yql -SELECT t.key FROM my_table AS t; -``` - -```yql -SELECT - MyFunction(key, 123 AS my_optional_arg) -FROM my_table; -``` - -{% else %} - -```yql -SELECT STREAM key AS k FROM my_stream; -``` - -```yql -SELECT STREAM s.key FROM my_stream AS s; -``` - -```yql -SELECT STREAM - MyFunction(key, 123 AS my_optional_arg) -FROM my_stream; -``` - -{% endif %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/between.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/between.md deleted file mode 100644 index 403e5cb696ac..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/between.md +++ /dev/null @@ -1,11 +0,0 @@ -## BETWEEN {#between} - -Checking whether a value is in a range. It's equivalent to two conditions with `>=` and `<=` (range boundaries are included). Can be used with the `NOT` prefix to support inversion. - -### Examples - -```yql -SELECT * FROM my_table -WHERE key BETWEEN 10 AND 20; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/bitcast.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/bitcast.md deleted file mode 100644 index 42c849cdb90b..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/bitcast.md +++ /dev/null @@ -1,15 +0,0 @@ -## BITCAST {#bitcast} - -Performs a bitwise conversion of an integer value to the specified integer type. The conversion is always successful, but may lose precision or high-order bits. - -### Examples - -```yql -SELECT - BITCAST(100000ul AS Uint32), -- 100000 - BITCAST(100000ul AS Int16), -- -31072 - BITCAST(100000ul AS Uint16), -- 34464 - BITCAST(-1 AS Int16), -- -1 - BITCAST(-1 AS Uint16); -- 65535 -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/case.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/case.md deleted file mode 100644 index 3251f9d33eb9..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/case.md +++ /dev/null @@ -1,30 +0,0 @@ -## CASE {#case} - -Conditional expressions and branching. It's similar to `if`, `switch` and ternary operators in the imperative programming languages. -If the result of the `WHEN` expression is `true`, the value of the `CASE` expression becomes the result following the condition, and the rest of the `CASE` expression isn't calculated. If the condition is not met, all the `WHEN` clauses that follow are checked. If none of the `WHEN` clauses are met, the `CASE` value is assigned the result from the `ELSE` clause. -The `ELSE` branch is mandatory in the `CASE` expression. Expressions in `WHEN` are checked sequentially, from top to bottom. - -Since its syntax is quite sophisticated, it's often more convenient to use the built-in function [IF](../../../builtins/basic.md#if). - -### Examples - -```yql -SELECT - CASE - WHEN value > 0 - THEN "positive" - ELSE "negative" - END -FROM my_table; -``` - -```yql -SELECT - CASE value - WHEN 0 THEN "zero" - WHEN 1 THEN "one" - ELSE "not zero or one" - END -FROM my_table; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/cast.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/cast.md deleted file mode 100644 index a1c98dd0f8e9..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/cast.md +++ /dev/null @@ -1,16 +0,0 @@ -## CAST {#cast} - - - -Tries to cast the value to the specified type. The attempt may fail and return `NULL`. When used with numbers, it may lose precision or most significant bits. -{% if feature_column_container_type %} -For lists and dictionaries, it can either delete or replace with `NULL` the elements whose conversion failed. -For structures and tuples, it deletes elements that are omitted in the target type. -For more information about casting rules, see [here](../../../types/cast.md). -{% endif %} - -{% include [decimal_args](../../../_includes/decimal_args.md) %} - -### Examples - -{% include [cast_examples](../../../_includes/cast_examples.md) %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/check-match.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/check-match.md deleted file mode 100644 index 219a5b4f3510..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/check-match.md +++ /dev/null @@ -1,48 +0,0 @@ -## Matching a string by pattern {#check-match} - -`REGEXP` and `RLIKE` are aliases used to call [Re2::Grep](../../../udf/list/re2.md#match). `MATCH`: Same for [Re2::Match](../../../udf/list/re2.md#match). - -`LIKE` works as follows: - -* Patterns can include two special characters: - - * `%`: Zero or more of any characters. - * `_`: Exactly one of any character. - -All other characters are literals that represent themselves. - -* As opposed to `REGEXP`, `LIKE` must be matched exactly. For example, to search a substring, add `%` at the beginning and end of the pattern. -* `ILIKE` is a case-insensitive version of `LIKE`. -* If `LIKE` is applied to the key column of the sorted table and the pattern doesn't start with a special character, filtering by prefix drills down directly to the cluster level, which in some cases lets you avoid the full table scan. This optimization is disabled for `ILIKE`. -* To escape special characters, specify the escaped character after the pattern using the `ESCAPE '?'` keyword. Instead of `?` you can use any character except `%`, `_` and `\`. For example, if you use a question mark as an escape character, the expressions `?%`, `?_` and `??` will match their second character in the template: percent, underscore, and question mark, respectively. The escape character is undefined by default. - -The most popular way to use the `LIKE` and `REGEXP` keywords is to filter a table using the statements with the `WHERE` clause. However, there are no restrictions on using templates in this context: you can use them in most of contexts involving strings, for example, with concatenation by using `||`. - -### Examples - -```yql -SELECT * FROM my_table -WHERE string_column REGEXP '\\d+'; --- the second slash is required because --- all the standard string literals in SQL --- can accept C-escaped strings -``` - -```yql -SELECT - string_column LIKE '___!_!_!_!!!!!!' ESCAPE '!' - -- searches for a string of exactly 9 characters: - -- 3 arbitrary characters - -- followed by 3 underscores - -- and 3 exclamation marks -FROM my_table; -``` - -```yql -SELECT * FROM my_table -WHERE key LIKE 'foo%bar'; --- if the table is sorted by key, it will only scan the keys, --- starting with "foo", and then, among them, --- will leave only those that end in "bar" -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/concatenation.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/concatenation.md deleted file mode 100644 index b1fba9ca371d..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/concatenation.md +++ /dev/null @@ -1,14 +0,0 @@ -## String concatenation {#concatenation} - -Executed using the binary operator `||`. - -As with other binary operators, if the data on either side is `NULL`, the result is also `NULL`. - -Don't confuse this operator with a logical "or": in SQL, it's denoted by the `OR` keyword. It's also not worth doing concatenation using `+`. - -### Examples - -```yql -SELECT "fo" || "o"; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/in.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/in.md deleted file mode 100644 index 0a4d46e113b7..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/in.md +++ /dev/null @@ -1,46 +0,0 @@ -## IN {#in} - -Checking whether a value is inside of a set of values. It's logically equivalent to a chain of equality comparisons using `OR` but implemented more efficiently. - -{% note warning "Warning" %} - -Unlike a similar keyword in Python, in YQL `IN` **DOES NOT** search for a substring inside a string. To search for a substring, use the function [String::Contains](../../../udf/list/string.md) or [LIKE/REGEXP](../../../syntax/expressions.md#like) mentioned above. - -{% endnote %} - -Immediately after `IN`, you can specify the `COMPACT` modifier. -If `COMPACT` is not specified, then `IN` with a subquery is executed as a relevant `JOIN` (`LEFT SEMI` for `IN` and `LEFT ONLY` for `NOT IN`), if possible. -Using the `COMPACT` modifier forces the in-memory execution strategy: a hash table is immediately built from the contents of the right `IN` part in-memory, and then the left part is filtered. - -The `COMPACT` modifier must be used with care. Since the hash table is built in-memory, the query may fail if the right part of `IN` contains many large or different elements. - -{% if feature_mapreduce %} -Since YQL imposes a limit on the query size in bytes (it's about 1Mb), add large lists of values to your query by URLs and use the [ParseFile](../../../builtins/basic.md#parsefile) function. -{% endif %} - -### Examples - -```yql -SELECT column IN (1, 2, 3) -FROM my_table; -``` - -```yql -SELECT * FROM my_table -WHERE string_column IN ("a", "b", "c"); -``` - -```yql -$foo = AsList(1, 2, 3); -SELECT 1 IN $foo; -``` - -```yql -$values = (SELECT column + 1 FROM table); -SELECT * FROM my_table WHERE - -- filtering by an in-memory hash table for one_table - column1 IN COMPACT $values AND - -- followed by LEFT ONLY JOIN with other_table - column2 NOT IN (SELECT other_column FROM other_table); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/is-distinct-from.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/is-distinct-from.md deleted file mode 100644 index a3a194c2191a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/is-distinct-from.md +++ /dev/null @@ -1,12 +0,0 @@ -## IS \[NOT\] DISTINCT FROM {#is-distinct-from} - -Comparing of two values. Unlike the regular [comparison operators](../../../syntax/expressions.md#comparison-operators), NULLs are treated as equal to each other. -More precisely, the comparison is carried out according to the following rules: - -1. The operators `IS DISTINCT FROM`/`IS NOT DISTINCT FROM` are defined for those and only for those arguments for which the operators `!=` and `=` are defined. -2. The result of `IS NOT DISTINCT FROM` is equal to the logical negation of the `IS DISTINCT FROM` result for these arguments. -3. If the result of the `==` operator is not equal to zero for some arguments, then it is equal to the result of the `IS NOT DISTINCT FROM` operator for the same arguments. -4. If both arguments are empty `Optional` or `NULL`s, then the value of `IS NOT DISTINCT FROM` is `True`. -5. The result of `IS NOT DISTINCT FROM` for an empty `Optional` or `NULL` and filled-in `Optional` or non-`Optional` value is `False`. - -For values of composite types, these rules are used recursively. diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/is-null.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/is-null.md deleted file mode 100644 index 9b695869caa0..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/is-null.md +++ /dev/null @@ -1,11 +0,0 @@ -## IS \[NOT\] NULL {#is-null} - -Matching an empty value (`NULL`). Since `NULL` is a special value [equal to nothing](../../../types/optional.md#null_expr), the ordinary [comparison operators](../../../syntax/expressions.md#comparison-operators) can't be used to match it. - -### Examples - -```yql -SELECT key FROM my_table -WHERE value IS NOT NULL; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/items-access.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/items-access.md deleted file mode 100644 index f51da9db4328..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/items-access.md +++ /dev/null @@ -1,27 +0,0 @@ -## Accessing containers {#items-access} - -For accessing the values inside containers: - -* `Struct<>`, `Tuple<>` and `Variant<>`, use a **dot**. The set of keys (for the tuple and the corresponding variant — indexes) is known at the query compilation time. The key is **validated** before beginning the query execution. -* `List<>` and `Dict<>`, use **square brackets**. The set of keys (set of indexes for keys) is known only at the query execution time. The key is **not validated** before beginning the query execution. If no value is found, an empty value (NULL) is returned. - -[Description and list of available containers](../../../types/containers.md). - -When using this syntax to access containers within table columns, be sure to specify the full column name, including the table name or table alias separated by a dot (see the first example below). - -### Examples - -```yql -SELECT - t.struct.member, - t.tuple.7, - t.dict["key"], - t.list[7] -FROM my_table AS t; -``` - -```yql -SELECT - Sample::ReturnsStruct().member; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/lambda.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/lambda.md deleted file mode 100644 index 7dafc3192ff0..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/lambda.md +++ /dev/null @@ -1,33 +0,0 @@ -## Lambda functions {#lambda} - -Let you combine multiple expressions into a single callable value. - -List arguments in round brackets, following them by the arrow and lambda function body. The lambda function body includes either an expression in round brackets or curly brackets around an optional chain of [named expressions](../../../syntax/expressions.md#named-nodes) assignments and the call result after the `RETURN` keyword in the last expression. - -The scope for the lambda body: first the local named expressions, then arguments, then named expressions defined above by the lambda function at the top level of the query. - -Only use pure expressions inside the lambda body (those might also be other lambdas, possibly passed through arguments). However, you can't use [SELECT](../../select/index.md), [INSERT INTO](../../insert_into.md), or other top-level expressions. - -One or more of the last lambda parameters can be marked with a question mark as optional: if they haven't been specified when calling lambda, they are assigned the `NULL` value. - -### Examples - -```yql -$f = ($y) -> { - $prefix = "x"; - RETURN $prefix || $y; -}; - -$g = ($y) -> ("x" || $y); - -$h = ($x, $y?) -> ($x + ($y ?? 0)); - -SELECT $f("y"), $g("z"), $h(1), $h(2, 3); -- "xy", "xz", 1, 5 -``` - -```yql --- if the lambda result is calculated by a single expression, then you can use a more compact syntax: -$f = ($x, $_) -> ($x || "suffix"); -- the second argument is not used -SELECT $f("prefix_", "whatever"); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/named-nodes.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/named-nodes.md deleted file mode 100644 index e93e3c5ccd85..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/named-nodes.md +++ /dev/null @@ -1,93 +0,0 @@ -## Named expressions {#named-nodes} - -Complex queries may be sophisticated, containing lots of nested levels and/or repeating parts. In YQL, you can use named expressions to assign a name to an arbitrary expression or subquery. Named expressions can be referenced in other expressions or subqueries. In this case, the original expression/subquery is actually substituted at point of use. - -A named expression is defined as follows: - -```yql - = | ; -``` - -Here `` consists of a $ character and an arbitrary non-empty identifier (for example, `$foo`). - -If the expression on the right is a tuple, you can automatically unpack it by specifying several named expressions separated by commas on the left: - -```yql -, , ... = ; -``` - -In this case, the number of expressions must match the tuple size. - -Each named expression has a scope. It starts immediately after the definition of a named expression and ends at the end of the nearest enclosed namescope (for example, at the end of the query or at the end of the body of the [lambda function](../../../syntax/expressions.md#lambda), [ACTION](../../action.md#define-action){% if feature_subquery %}, [SUBQUERY](../../subquery.md#define-subquery){% endif %}{% if feature_mapreduce %}, or the cycle [EVALUATE FOR](../../action.md#evaluate-for){% endif %}). -Redefining a named expression with the same name hides the previous expression from the current scope. - -If the named expression has never been used, a warning is issued. To avoid such a warning, use the underscore as the first character in the ID (for example, `$_foo`). -The named expression `$_` is called an anonymous named expression and is processed in a special way: it works as if `$_` would be automatically replaced by `$_`. -Anonymous named expressions are convenient when you don't need the expression value. For example, to fetch the second element from a tuple of three elements, you can write: - -```yql -$_, $second, $_ = AsTuple(1, 2, 3); -select $second; -``` - -An attempt to reference an anonymous named expression results in an error: - -```yql -$_ = 1; -select $_; --- error: Unable to reference anonymous name $_ -export $_; --- An error: Can not export anonymous name $_ -``` - -{% if feature_mapreduce %} -Moreover, you can't import a named expression with an anonymous alias: - -```yql -import utils symbols $sqrt as $_; --- error: Can not import anonymous name $_ -``` - -{% endif %} -Anonymous argument names are also supported for [lambda functions](../../../syntax/expressions.md#lambda), [ACTION](../../action.md#define-action){% if feature_subquery %}, [SUBQUERY](../../subquery.md#define-subquery){% endif %}{% if feature_mapreduce %}, and in [EVALUATE FOR](../../action.md#evaluate-for){% endif %}. - -{% note info %} - -If named expression substitution results in completely identical subgraphs in the query execution graph, the graphs are combined to execute a subgraph only once. - -{% endnote %} - -### Examples - -```yql -$multiplier = 712; -SELECT - a * $multiplier, -- $multiplier is 712 - b * $multiplier, - (a + b) * $multiplier -FROM abc_table; -$multiplier = c; -SELECT - a * $multiplier -- $multiplier is column c -FROM abc_table; -``` - -```yql -$intermediate = ( - SELECT - value * value AS square, - value - FROM my_table -); -SELECT a.square * b.value -FROM $intermediate AS a -INNER JOIN $intermediate AS b -ON a.value == b.square; -``` - -```yql -$a, $_, $c = AsTuple(1, 5u, "test"); -- unpack a tuple -SELECT $a, $c; -``` - -```yql -$x, $y = AsTuple($y, $x); -- swap expression values -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/operators.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/operators.md deleted file mode 100644 index 0ec1c0b8ff25..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/operators.md +++ /dev/null @@ -1,87 +0,0 @@ -## Operators - -### Arithmetic operators {#math-operators} - -The operators `+`, `-`, `*`, `/`, `%` are defined for [primitive data types](../../../types/primitive.md) that are variations of numbers. - -For the Decimal data type, bankers rounding is used (to the nearest even integer). - -#### Examples - -```yql -SELECT 2 + 2; -``` - -```yql -SELECT 0.0 / 0.0; -``` - -### Comparison operators {#comparison-operators} - -The operators `=`, `==`, `!=`, `<>`, `>`, `<` are defined for: - -* Primitive data types except Yson and Json. -* Tuples and structures with the same set of fields. No order is defined for structures, but you can check for (non-)equality. Tuples are compared element-by-element left to right. - -#### Examples - -```yql -SELECT 2 > 1; -``` - -### Logical operators {#logic-operators} - -Use the operators `AND`, `OR`, `XOR` for logical operations on Boolean values (`Bool`). - -#### Examples* - -```yql -SELECT 3 > 0 AND false; -``` - -### Bitwise operators {#bit-operators} - -Bitwise operations on numbers: - -* `&`, `|`, `^`: AND, OR, and XOR, respectively. Don't confuse bitwise operations with the related keywords. The keywords `AND`, `OR`, and `XOR` are used *for Boolean values only*, but not for numbers. -* ` ~ `: A negation. -* `<`, `>`: Left or right shifts. -* `|<`, `>|`: Circular left or right shifts. - -#### Examples - -```yql -SELECT - key << 10 AS key, - ~value AS value -FROM my_table; -``` - -### Precedence and associativity of operators {#operator-priority} - -Operator precedence determines the order of evaluation of an expression that contains different operators. -For example, the expression `1 + 2 * 3` is evaluated as `1 + (2 * 3)` because the multiplication operator has a higher precedence than the addition operator. - -Associativity determines the order of evaluating expressions containing operators of the same type. -For example, the expression `1 + 2 + 3` is evaluated as `(1 + 2) + 3` because the addition operator is left-associative. -On the other hand, the expression `a ?? b ?? c` is evaluated as `a ?? (b ?? c)` because the `??` operator is right-associative - -The table below shows precedence and associativity of YQL operators. -The operators in the table are listed in descending order of precedence. - -| Priority | Operator | Description | Associativity | -| --- | --- | --- | --- | -| 1 | `a[], a.foo, a()` | Accessing a container item, calling a function | Left | -| 2 | `+a, -a, ~a, NOT a` | Unary operators: plus, minus, bitwise and logical negation | Right | -| 3 | `a\|\|b` | [String concatenation](../../../syntax/expressions.md#concatenation) | Left | -| 4 | `a*b, a/b, a%b` | Multiplication, division, remainder of division | Left | -| 5 | `a+b, a-b` | Addition/Subtraction | Left | -| 6 | `a ?? b` | Operator notation for [NVL/COALESCE](../../../builtins/basic.md#coalesce) | Right | -| 7 | `ab, a\|\|b,` `a\|b, a^b, a&b` | Shift operators and logical bit operators | Left | -| 8 | `ab` | Comparison | Left | -| 9 | `a IN b` | Occurrence of an element in a set | Left | -| 9 | `a==b, a=b, a!=b, a<>b,` `a is (not) distinct from b` | Comparison for (non-)equality | Left | -| 10 | `a XOR b` | Logical XOR | Left | -| 11 | `a AND b` | Logical AND | Left | -| 12 | `a OR b` | Logical OR | Left | - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/tables.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/tables.md deleted file mode 100644 index c9dc1288e801..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/expressions/tables.md +++ /dev/null @@ -1,69 +0,0 @@ -## Table expressions {#table-contexts} - -A table expression is an expression that returns a table. Table expressions in YQL are as follows: - -* Subqueries: `(SELECT key, subkey FROM T)` -* [Named subqueries](../../../syntax/expressions.md#named-nodes): `$foo = SELECT * FROM T;` (in this case, `$foo` is also a table expression) -{% if feature_subquery %} -* [Subquery templates](../../subquery.md#define-subquery): `DEFINE SUBQUERY $foo($name) AS ... END DEFINE;` (`$foo("InputTable")` is a table expression). -{% endif %} - -Semantics of a table expression depends on the context where it is used. In YQL, table expressions can be used in the following contexts: - -* Table context: after [FROM](../../select/from.md). In this case, table expressions work as expected: for example, `$input = SELECT a, b, c FROM T; SELECT * FROM $input` returns a table with three columns. The table context also occurs after [UNION ALL](../../select/union.md#unionall){% if feature_join %}, [JOIN](../../join.md#join){% endif %}{% if feature_mapreduce and process_command == "PROCESS" %}, [PROCESS](../../process.md#process), [REDUCE](../../reduce.md#reduce){% endif %}; -* Vector context: after [IN](../../../syntax/expressions.md#in). In this context, the table expression must contain exactly one column (the name of this column doesn't affect the expression result in any way). A table expression in a vector context is typed as a list (the type of the list element is the same as the column type in this case). Example: `SELECT * FROM T WHERE key IN (SELECT k FROM T1)`; -* A scalar context arises _in all the other cases_. As in a vector context, a table expression must contain exactly one column, but the value of the table expression is a scalar, that is, an arbitrarily selected value of this column (if no rows are returned, the result is `NULL`). Example: `$count = SELECT COUNT(*) FROM T; SELECT * FROM T ORDER BY key LIMIT $count / 2`; - -The order of rows in a table context, the order of elements in a vector context, and the rule for selecting a value from a scalar context (if multiple values are returned), aren't defined. This order also cannot be affected by `ORDER BY`: `ORDER BY` without `LIMIT` is ignored in table expressions with a warning, and `ORDER BY` with `LIMIT` defines a set of elements rather than the order within that set. - -{% if feature_mapreduce and process_command == "PROCESS" %} - -There is an exception to this rule. Named expression with [PROCESS](../../process.md#process), if used in a scalar context, behaves as in a table context: - -```yql -$input = SELECT 1 AS key, 2 AS value; -$process = PROCESS $input; - -SELECT FormatType(TypeOf($process)); -- $process is used in a scalar context, - -- but the SELECT result in this case is List - -SELECT $process[0].key; -- that returns 1 - -SELECT FormatType(TypeOf($input)); -- throws an error: $input in a scalar context must contain one column -``` - -{% note warning %} - -A common error is to use an expression in a scalar context rather than a table context or vector context. For example: - -```yql -$dict = SELECT key, value FROM T1; - -DEFINE SUBQUERY $merge_dict($table, $dict) AS -SELECT * FROM $table LEFT JOIN $dict USING(key); -END DEFINE; - -SELECT * FROM $merge_dict("Input", $dict); -- $dict is used in a scalar context in this case. - -- an error: exactly one column is expected in a scalar context -``` - -A correct notation in this case is: - -```yql -DEFINE SUBQUERY $dict() AS -SELECT key, value FROM T1; -END DEFINE; - -DEFINE SUBQUERY $merge_dict($table, $dict) AS -SELECT * FROM $table LEFT JOIN $dict() USING(key); -- Using the table expression $dict() - -- (Calling a subquery template) in a table context -END DEFINE; - -SELECT * FROM $merge_dict("Input", $dict); -- $dict - is a subquery template (rather than a table expression) - -- that is passed as an argument of a table expression -``` - -{% endnote %} - -{% endif %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_columns.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_columns.md deleted file mode 100644 index d6b39bd3bb44..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_columns.md +++ /dev/null @@ -1,20 +0,0 @@ -## FLATTEN COLUMNS {#flatten-columns} - -Converts a table where all columns must be structures to a table with columns corresponding to each element of each structure from the source columns. - -The names of the source column structures are not used and not returned in the result. Be sure that the structure element names aren't repeated in the source columns. - -### Example - -```yql -SELECT x, y, z -FROM ( - SELECT - AsStruct( - 1 AS x, - "foo" AS y), - AsStruct( - false AS z) -) FLATTEN COLUMNS; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_other_db.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_other_db.md deleted file mode 100644 index d88b205bac17..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_other_db.md +++ /dev/null @@ -1,8 +0,0 @@ -### Analogues of FLATTEN BY in other DBMS {#flatten-other-dmb} - -* PostgreSQL: `unnest` -* Hive: `LATERAL VIEW` -* MongoDB: `unwind` -* Google BigQuery: `FLATTEN` -* ClickHouse: `ARRAY JOIN / arrayJoin` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_type_by.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_type_by.md deleted file mode 100644 index 3ae0be461e22..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_type_by.md +++ /dev/null @@ -1,44 +0,0 @@ -### Specifying the container type {#flatten-by-specific-type} - -To specify the type of container to convert to, you can use: - -* `FLATTEN LIST BY` - - For `Optional>`, `FLATTEN LIST BY` will unpack the list, treating `NULL` as an empty list. - -* `FLATTEN DICT BY` - - For `Optional>`, `FLATTEN DICT BY` will unpack the dictionary, interpreting `NULL` as an empty dictionary. - -* `FLATTEN OPTIONAL BY` - - To filter the `NULL` values without serialization, specify the operation by using `FLATTEN OPTIONAL BY`. - -### Examples - -```yql -SELECT - t.item.0 AS key, - t.item.1 AS value, - t.dict_column AS original_dict, - t.other_column AS other -FROM my_table AS t -FLATTEN DICT BY dict_column AS item; -``` - -```yql -SELECT * FROM ( - SELECT - AsList(1, 2, 3) AS a, - AsList("x", "y", "z") AS b -) FLATTEN LIST BY (a, b); -``` - -```yql -SELECT * FROM ( - SELECT - "1;2;3" AS a, - AsList("x", "y", "z") AS b -) FLATTEN LIST BY (String::SplitToList(a, ";") as a, b); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/compact.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/compact.md deleted file mode 100644 index 855f99f66632..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/compact.md +++ /dev/null @@ -1,18 +0,0 @@ -## GROUP COMPACT BY - -Improves aggregation efficiency if the query author knows in advance that none of aggregation keys finds large amounts of data (i.e., with the order of magnitude exceeding a gigabyte or a million of rows). If this assumption fails to materialize, then the operation may fail with Out of Memory error or start running much slower compared to the non-COMPACT version. - -Unlike the usual GROUP BY, the Map-side combiner stage and additional Reduce are disabled for each field with [DISTINCT](../../../syntax/group_by.md#distinct) aggregation. - -### Example - -```yql -SELECT - key, - COUNT (DISTINCT value) AS count -- top 3 keys by the number of unique values -FROM my_table -GROUP COMPACT BY key -ORDER BY count DESC -LIMIT 3; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/distinct.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/distinct.md deleted file mode 100644 index 259a9d56ed18..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/distinct.md +++ /dev/null @@ -1,24 +0,0 @@ -## DISTINCT {#distinct} - -Applying [aggregate functions](../../../builtins/aggregation.md) only to distinct values of the column. - -{% note info %} - -Applying `DISTINCT` to calculated values is not currently implemented. For this purpose, you can use a [subquery](../../select/from.md) or the expression `GROUP BY ... AS ...`. - -{% endnote %} - -### Example - -```yql -SELECT - key, - COUNT (DISTINCT value) AS count -- top 3 keys by the number of unique values -FROM my_table -GROUP BY key -ORDER BY count DESC -LIMIT 3; -``` - -You can also use `DISTINCT` to fetch distinct rows using [`SELECT DISTINCT`](../../select/distinct.md). - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/general.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/general.md deleted file mode 100644 index bd6f208f7ab1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/general.md +++ /dev/null @@ -1,66 +0,0 @@ -## GROUP BY - -Group the `SELECT` results by the values of the specified columns or expressions. `GROUP BY` is often combined with [aggregate functions](../../../builtins/aggregation.md) (`COUNT`, `MAX`, `MIN`, `SUM`, `AVG`) to perform calculations in each group. - -### Syntax - -```yql -SELECT -- In SELECT, you can use: - column1, -- key columns specified in GROUP BY - key_n, -- named expressions specified in GROUP BY - column1 + key_n, -- arbitrary non-aggregate functions on them - Aggr_Func1( column2 ), -- aggregate functions containing any columns as arguments, - Aggr_Func2( key_n + column2 ), -- including named expressions specified in GROUP BY - ... -FROM table -GROUP BY - column1, column2, ..., - AS key_n -- When grouping by expression, you can set a name for it using AS, - -- and use it in SELECT -``` - -The query in the format `SELECT * FROM table GROUP BY k1, k2, ...` returns all columns listed in GROUP BY, i.e., is equivalent to `SELECT DISTINCT k1, k2, ... FROM table`. - -An asterisk can also be used as an argument for the `COUNT` aggregate function. `COUNT(*)` means "the count of rows in the group". - -{% note info %} - -Aggregate functions ignore `NULL` in their arguments, except for `COUNT`. - -{% endnote %} - -YQL also provides aggregation factories implemented by the functions [`AGGREGATION_FACTORY`](../../../builtins/basic.md#aggregationfactory) and [`AGGREGATE_BY`](../../../builtins/aggregation.md#aggregateby). - -### Examples - -```yql -SELECT key, COUNT(*) FROM my_table -GROUP BY key; -``` - -```yql -SELECT double_key, COUNT(*) FROM my_table -GROUP BY key + key AS double_key; -``` - -```yql -SELECT - double_key, -- OK: A key column - COUNT(*) AS group_size, -- OK: COUNT(*) - SUM(key + subkey) AS sum1, -- OK: An aggregate function - CAST(SUM(1 + 2) AS String) AS sum2, -- OK: An aggregate function with a constant argument - SUM(SUM(1) + key) AS sum3, -- ERROR: Nested aggregations are not allowed - key AS k1, -- ERROR: Using a non-key column named key without aggregation - key * 2 AS dk1, -- ERROR in YQL: using a non-key column named key without aggregation -FROM my_table -GROUP BY - key * 2 AS double_key, - subkey as sk, -``` - -{% note warning %} - -Specifying a name for a column or expression in `GROUP BY .. AS foo` it is an extension on top of YQL. Such a name becomes visible in `WHERE` despite the fact that filtering by `WHERE` is executed [before](../../select/where.md) the grouping. For example, if the `T` table includes two columns, `foo` and `bar`, then the query `SELECT foo FROM T WHERE foo > 0 GROUP BY bar AS foo` would actually filter data by the `bar` column from the source table. - -{% endnote %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/general_stream.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/general_stream.md deleted file mode 100644 index 0a2597b13753..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/general_stream.md +++ /dev/null @@ -1,59 +0,0 @@ -## GROUP BY ... HOP - -Group the table by the values of the specified columns or expressions and the time window. - -If GROUP BY is present in the query, then when selecting columns (between `SELECT STREAM ... FROM`) you can **only** use the following constructs: - -1. Columns by which grouping is performed (they are included in the `GROUP BY` argument). -2. Aggregate functions (see the next section). Columns by which **no** grouping is made can only be included as arguments for an aggregate function. -3. Functions that output the start and end time of the current window (`HOP_START` and `HOP_END`) -4. Arbitrary calculations combining paragraphs 1-3. - -You can group by the result of calculating an arbitrary expression from the source columns. In this case, to access the result of this expression, we recommend you to assign a name to it using `AS`, see the second example. - -Aggregate functions automatically skip `NULL` in their arguments. - -Among the columns by which grouping is performed, make sure to use the `HOP` construct to define the time window for grouping. - -```yql -HOP(time_extractor, hop, interval, delay) -``` - -The implemented version of the time window is called the **hopping window**. This is a window that moves forward in discrete intervals (the `hop` parameter). The total duration of the window is set by the `interval` parameter. To determine the time of each input event, the `time_extractor` parameter is used. This expression depends only on the input values of the stream's columns and must have the `Timestamp` type. It indicates where exactly to get the time value from input events. - -In each stream defined by the values of all the grouping columns, the window moves forward independently of other streams. Advancement of the window is totally dependent on the latest event of the stream. Since records in streams get somewhat mixed in time, the `delay` parameter has been added so you can delay the closing of the window by a specified period. Events arriving before the current window are ignored. - -The `interval` and `delay` parameters must be multiples of the `hop` parameter. Non-multiple intervals will be rounded down. - -To set `hop`, `interval` and `delay`, use a string expression compliant with [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). This is the format that is used to construct the built-in type `Interval` [from a string](../../../builtins/basic.md#data-type-literals). - -Functions with omitted `HOP_START` and `HOP_END` parameters, return a value of the `Timestamp` type and correspond to the start and end of the current window. - -The **tumbling window** known in other systems is a special case of a **hopping window** when `interval` == `hop`. - -## Examples - -```yql -SELECT STREAM - key, - COUNT(*) -FROM my_stream -GROUP BY - HOP(CAST(subkey AS Timestamp), "PT10S", "PT1M", "PT30S"), - key; --- hop = 10 seconds --- interval = 1 minute --- delay = 30 seconds -``` - -```yql -SELECT STREAM - double_key, - HOP_END() as time, - COUNT(*) as count -FROM my_stream -GROUP BY - key + key AS double_key, - HOP(ts, "PT1M", "PT1M", "PT1M"); -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/having.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/having.md deleted file mode 100644 index c67f10ce6769..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/having.md +++ /dev/null @@ -1,14 +0,0 @@ -## HAVING {#having} - -Filtering a `SELECT` based on the calculation results of [aggregate functions](../../../builtins/aggregation.md). The syntax is similar to [WHERE](../../select/where.md). - -### Example - -```yql -SELECT - key -FROM my_table -GROUP BY key -HAVING COUNT(value) > 100; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/having_stream.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/having_stream.md deleted file mode 100644 index a394f6cee091..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/having_stream.md +++ /dev/null @@ -1,14 +0,0 @@ -## HAVING {#having} - -Filtering a `SELECT STREAM` based on the calculation results of [aggregate functions](../../../builtins/aggregation.md). The syntax is similar to [WHERE](../../select_stream.md#where). - -### Examples - -```yql -SELECT STREAM - key -FROM my_table -GROUP BY key, HOP(ts, "PT1M", "PT1M", "PT1M") -HAVING COUNT(value) > 100; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/rollup_cube_sets.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/rollup_cube_sets.md deleted file mode 100644 index 4296c82d490e..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/rollup_cube_sets.md +++ /dev/null @@ -1,74 +0,0 @@ -## ROLLUP, CUBE, and GROUPING SETS {#rollup} - -The results of calculating the aggregate function as subtotals for the groups and overall totals over individual columns or whole table. - -### Syntax - -```yql -SELECT - c1, c2, -- the columns to group by - -AGGREGATE_FUNCTION(c3) AS outcome_c -- an aggregate function (SUM, AVG, MIN, MAX, COUNT) - -FROM table_name - -GROUP BY - GROUP_BY_EXTENSION(c1, c2) -- an extension of GROUP BY: ROLLUP, CUBE, or GROUPING SETS -``` - -* `ROLLUP` groups the column values in the order they are listed in the arguments (strictly from left to right), generates subtotals for each group and the overall total. -* `CUBE` groups the values for every possible combination of columns, generates the subtotals for each group and the overall total. -* `GROUPING SETS` sets the groups for subtotals. - -You can combine `ROLLUP`, `CUBE` and `GROUPING SETS`, separating them by commas. - -### GROUPING {#grouping} - -The values of columns not used in calculations are replaced with `NULL` in the subtotal. In the overall total, the values of all columns are replaced by `NULL`. `GROUPING`: A function that allows you to distinguish the source `NULL` values from the `NULL` values added while calculating subtotals and overall totals. - -`GROUPING` returns a bit mask: - -* `0`: If `NULL` is used for the original empty value. -* `1`: If `NULL` is added for a subtotal or overall total. - -### Example - -```yql -SELECT - column1, - column2, - column3, - - CASE GROUPING( - column1, - column2, - column3, - ) - WHEN 1 THEN "Subtotal: column1 and column2" - WHEN 3 THEN "Subtotal: column1" - WHEN 4 THEN "Subtotal: column2 and column3" - WHEN 6 THEN "Subtotal: column3" - WHEN 7 THEN "Grand total" - ELSE "Individual group" - END AS subtotal, - - COUNT(*) AS rows_count - -FROM my_table - -GROUP BY - ROLLUP( - column1, - column2, - column3 - ), - GROUPING SETS( - (column2, column3), - (column3) - -- if you add here (column2) as well, then together - -- the ROLLUP and GROUPING SETS would produce a result - -- similar to CUBE - ) -; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/session_window.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/session_window.md deleted file mode 100644 index 95150f13559a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/group_by/session_window.md +++ /dev/null @@ -1,70 +0,0 @@ -## GROUP BY ... SessionWindow() {#session-window} - -YQL supports grouping by session. To standard expressions in `GROUP BY`, you can add a special `SessionWindow` function: - -```yql -SELECT - user, - session_start, - SessionStart() AS same_session_start, -- It's same as session_start - COUNT(*) AS session_size, - SUM(value) AS sum_over_session, -FROM my_table -GROUP BY user, SessionWindow(, ) AS session_start -``` - -The following happens in this case: - -1. The input table is partitioned by the grouping keys specified in `GROUP BY`, ignoring SessionWindow (in this case, it's based on `user`). - - If `GROUP BY` includes nothing more than SessionWindow, then the input table gets into one partition. - -2. Each partition is split into disjoint subsets of rows (sessions). - - For this, the partition is sorted in the ascending order of the `time_expr` expression. - The session limits are drawn between neighboring items of the partition, that differ in their `time_expr` values by more than `timeout_expr`. - -3. The sessions obtained in this way are the final partitions on which aggregate functions are calculated. - -The `SessionWindow()` key column (in the example, it's `session_start`) has the value "the minimum `time_expr` in the session". -If `GROUP BY` includes SessionWindow(), you can use a special aggregate function -[SessionStart](../../../builtins/aggregation.md#session-start). - -An extended version of SessionWindow with four arguments is also supported: - -`SessionWindow(, , , )` - -Where: - -* ``: An expression used to sort the source partition -* ``: A lambda function to initialize the state of session calculation. It has the signature `(TableRow())->State`. It's called once for the first (following the sorting order) element of the source partition -* ``: A lambda function to update the status of session calculation and define the session limits. It has the signature `(TableRow(), State)->Tuple`. It's called for every item of the source partition, except the first one. The new value of state is calculated based on the current row of the table and the previous state. If the first item in the return tuple is `True`, then a new session starts from the _current_ row. The key of the new session is obtained by applying `` to the second item in the tuple. -* ``: A lambda function for calculating the session key (the "value" of SessionWindow() that is also accessible via SessionStart()). The function has the signature `(TableRow(), State)->SessionKey`. It's called for the first item in the partition (after ``) and those items for which `` has returned `True` in the first item in the tuple. Please note that to start a new session, you should make sure that `` has returned a value different from the previous session key. Sessions having the same keys are not merged. For example, if `` returns the sequence `0, 1, 0, 1`, then there will be four different sessions. - -Using the extended version of SessionWindow, you can, for example, do the following: divide a partition into sessions, as in the SessionWindow use case with two arguments, but with the maximum session length limited by a certain constant: - -### Example - -```yql -$max_len = 1000; -- is the maximum session length. -$timeout = 100; -- is the timeout (timeout_expr in a simplified version of SessionWindow). - -$init = ($row) -> (AsTuple($row.ts, $row.ts)); -- is the session status: tuple from 1) value of the temporary column ts in the session's first line and 2) in the current line -$update = ($row, $state) -> { - $is_end_session = $row.ts - $state.0 > $max_len OR $row.ts - $state.1 > $timeout; - $new_state = AsTuple(IF($is_end_session, $row.ts, $state.0), $row.ts); - return AsTuple($is_end_session, $new_state); -}; -$calculate = ($row, $state) -> ($row.ts); -SELECT - user, - session_start, - SessionStart() AS same_session_start, -- It's same as session_start - COUNT(*) AS session_size, - SUM(value) AS sum_over_session, -FROM my_table -GROUP BY user, SessionWindow(ts, $init, $update, $calculate) AS session_start -``` - -You can use `SessionWindow` in `GROUP BY` only once. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/insert_hints.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/insert_hints.md deleted file mode 100644 index 9effcc34beb6..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/insert_hints.md +++ /dev/null @@ -1,17 +0,0 @@ -{% if feature_insert_with_truncate %} - -Inserts can be made with one or more modifiers. A modifier is specified after the `WITH` keyword following the table name: `INSERT INTO ... WITH SOME_HINT`. -If a modifier has a value, it's indicated after the `=` sign: `INSERT INTO ... WITH SOME_HINT=value`. -If necessary, specify multiple modifiers, they should be enclosed in parentheses: `INSERT INTO ... WITH (SOME_HINT1=value, SOME_HINT2, SOME_HINT3=value)`. - -To clear the table of existing data before writing new data to it, add the modifier: `INSERT INTO ... WITH TRUNCATE`. - -### Examples - -```yql -INSERT INTO my_table WITH TRUNCATE -SELECT key FROM my_table_source; -``` - -{% endif %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/into_result.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/into_result.md deleted file mode 100644 index 6300e1db0c2b..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/into_result.md +++ /dev/null @@ -1,16 +0,0 @@ -# INTO RESULT - -Lets you set a custom label for [SELECT](../select/index.md){% if feature_mapreduce and process_command == "PROCESS" %}, [PROCESS](../process.md), or [REDUCE](../reduce.md){% endif %}. It can't be used along with [DISCARD](../discard.md). - -## Examples - -```yql -SELECT 1 INTO RESULT foo; -``` - -```yql -SELECT * FROM -my_table -WHERE value % 2 == 0 -INTO RESULT `Result name`; -``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/debug.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/debug.md deleted file mode 100644 index 8b7cb79647b9..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/debug.md +++ /dev/null @@ -1,41 +0,0 @@ -{% if tech %} - -## Debugging and auxiliary settings {#debug} - -{% if feature_webui %} - -### `DirectRead` - -| Value type | Default | -| --- | --- | -| Flag | false | - -An auxiliary setting for previewing tables in the [HTTP API](../../../interfaces/http.md) (both for the web interface and console client). -{% endif %} - -### `config.flags("ValidateUdf", "Lazy")` - -| Value type | Default | -| --- | --- | -| String: None/Lazy/Greedy | None | - -Validating whether UDF results match the declared signature. The Greedy mode enforces materialization of lazy containers, although the Lazy mode doesn't. - -### `{{ backend_name_lower }}.DefaultCluster` - -| Value type | Default | -| --- | --- | -| A string with the cluster name | hahn | - -Selecting a cluster for calculations that don't access tables. - -### `config.flags("Diagnostics")` - -| Value type | Default | -| --- | --- | -| Flag | false | - -Getting diagnostic information from YQL as an additional result of a query. - -{% endif %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/definition.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/definition.md deleted file mode 100644 index 82d94b00861e..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/definition.md +++ /dev/null @@ -1,39 +0,0 @@ -## Definition - -Redefinition of settings. - -### Syntax - -`PRAGMA x.y = "z";` or `PRAGMA x.y("z", "z2", "z3");`: - -* `x`: (optional) The category of the setting. -* `y`: The name of the setting. -* `z`: (optional for flags) The value of the setting. The following suffixes are acceptable: - - * `Kb`, `Mb`, `Gb`: For the data amounts. - * `sec`, `min`, `h`, `d`: For the time values. - -### Examples - -```yql -PRAGMA AutoCommit; -``` - -```yql -PRAGMA TablePathPrefix = "home/yql"; -``` - -```yql -PRAGMA Warning("disable", "1101"); -``` - -With some exceptions, you can return the settings values to their default states using `PRAGMA my_pragma = default;`. - -For the full list of available settings, [see the table below](../../pragma.md#pragmas). - -### Scope {#pragmascope} - -Unless otherwise specified, a pragma affects all the subsequent expressions up to the end of the module where it's used. If necessary and logically possible, you can change the value of this setting several times within a given query to make it different at different execution steps. - -There are also special scoped pragmas with the scope defined by the same rules as the scope of [named expressions](../../expressions.md#named-nodes). Unlike scoped pragmas, regular pragmas can only be used in the global scope (not inside lambda functions, `ACTION`{% if feature_subquery %}, `SUBQUERY`{% endif %}, etc.). - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/files.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/files.md deleted file mode 100644 index 83552172ec3c..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/files.md +++ /dev/null @@ -1,108 +0,0 @@ -{% if feature_mapreduce %} - -## Working with files - -### File - -| Value type | Default | Static/
dynamic | -| --- | --- | --- | -| Two string arguments: alias and URL | — | Static | - -Attach a file to the query by URL. For attaching files you can use the built-in functions [FilePath and FileContent](../../../builtins/basic.md#filecontent). This `PRAGMA` is a universal alternative to attaching files using built-in mechanisms from the [web](../../../interfaces/web.md#attach) or [console](../../../interfaces/cli.md#attach) clients. - -YQL reserves the right to cache files at the URL for an indefinite period, hence, if there is a significant change in the content behind it, we strongly recommended to modify the URL by adding/editing dummy parameters. - -### Folder - -| Value type | Default | Static/
dynamic | -| --- | --- | --- | -| Two string arguments: prefix and URL | — | Static | - -Attach a set of files to the query by URL. Works similarly to adding multiple files via [`PRAGMA File`](#file) by direct links to files with aliases obtained by combining a prefix with a file name using `/`. - -### Library - -| Value type | Default | Static/
dynamic | -| --- | --- | --- | -| One or two arguments: the file name and an optional URL | — | Static | - -Treat the specified attached file as a library from which you can do [IMPORT](../../export_import.md). The syntax type for the library is determined from the file extension: - -* `.sql`: For the YQL dialect of SQL (recommended). -* `.yql`: For [s-expressions](/docs/s_expressions). - -Example with a file attached to the query: - -```yql -PRAGMA library("a.sql"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -If the URL is specified, the library is downloaded from the URL rather than from the pre-attached file as in the following example: - -```yql -PRAGMA library("a.sql","{{ corporate-paste }}/5618566/text"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -In this case, you can use text parameter value substitution in the URL: - -```yql -DECLARE $_ver AS STRING; -- "5618566" -PRAGMA library("a.sql","{{ corporate-paste }}/{$_ver}/text"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -### Package - -| Value type | Default | Static /
dynamic | -| --- | --- | --- | -| Two or three arguments: package name, URL and optional token | — | Static | - -Attach a hierarchical set of files to the query by URL, treating them as a package with a given name - an interconnected set of libraries. - -Package name is expected to be given as ``project_name.package_name``; from package's libraries you can do [IMPORT](../../export_import.md) with a module name like ``pkg.project_name.package_name.maybe.nested.module.name``. - -Example for a package with flat hierarchy which consists of two libraries - foo.sql and bar.sql: - -```yql -PRAGMA package("project.package", "{{ corporate-yt }}/{{ corporate-yt-cluster }}/path/to/package"); -IMPORT pkg.project.package.foo SYMBOLS $foo; -IMPORT pkg.project.package.bar SYMBOLS $bar; -SELECT $foo, $bar; -``` - -You can also use text parameter value substitution in the URL: - -```yql -DECLARE $_path AS STRING; -- "path" -PRAGMA package("project.package","{{ corporate-yt }}/{{ corporate-yt-cluster }}/{$_path}/to/package"); -IMPORT pkg.project.package.foo SYMBOLS $foo; -IMPORT pkg.project.package.bar SYMBOLS $bar; -SELECT $foo, $bar; -``` - -### OverrideLibrary - -| Value type | Default | Static/
dynamic | -| --- | --- | --- | -| One argument: the file name | — | Static | - -Treat the specified attached file as a library and override with it one of package's libraries. - -File name is expected to be given as ``project_name/package_name/maybe/nested/module/name.EXTENSION``, extensions analagous to [PRAGMA Library](#library) are supported. - -Example: - -```yql -PRAGMA package("project.package", "{{ corporate-yt }}/{{ corporate-yt-cluster }}/path/to/package"); -PRAGMA override_library("project/package/maybe/nested/module/name.sql"); - -IMPORT pkg.project.package.foo SYMBOLS $foo; -SELECT $foo; -``` - -{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/global.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/global.md deleted file mode 100644 index 097599690134..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/global.md +++ /dev/null @@ -1,246 +0,0 @@ -## Global {#pragmas} - -### AutoCommit {#autocommit} - -| Value type | Default | -| --- | --- | -| Flag | false | - -Automatically run [COMMIT](../../commit.md) after every statement. - -### TablePathPrefix {#table-path-prefix} - -| Value type | Default | -| --- | --- | -| String | — | - -Add the specified prefix to the cluster table paths. It uses standard file system path concatenation, supporting parent folder `..` referencing and requiring no trailing slash. For example, - -`PRAGMA TablePathPrefix = "home/yql"; -SELECT * FROM test;` - -The prefix is not added if the table name is an absolute path (starts with /). - -### UseTablePrefixForEach {#use-table-prefix-for-each} - -| Value type | Default | -| --- | --- | -| Flag | false | - -EACH uses [TablePathPrefix](#table-path-prefix) for each list item. - -### Warning {#warning} - -| Value type | Default | -| --- | --- | -| 1. Action
2. Warning code or "*" | — | - -Action: - -* `disable`: Disable. -* `error`: Treat as an error. -* `default`: Revert to the default behavior. - -The warning code is returned with the text itself (it's displayed on the right side of the web interface). - -#### Example - -`PRAGMA Warning("error", "*");` -`PRAGMA Warning("disable", "1101");` -`PRAGMA Warning("default", "4503");` - -In this case, all the warnings are treated as errors, except for the warning `1101` (that will be disabled) and `4503` (that will be processed by default, that is, remain a warning). Since warnings may be added in new YQL releases, use `PRAGMA Warning("error", "*");` with caution (at least cover such queries with autotests). - -{% include [issue_protos.md](issue_protos.md) %} - -{% if feature_mapreduce %} - -### DqEngine {#dqengine} - -| Value type | Default | -| --- | --- | -| disable/auto/force string | "auto" | - -When set to "auto", it enables a new compute engine. Computing is made, whenever possible, without creating map/reduce operations. When the value is "force", computing is made by the new engine unconditionally. -{% endif %} - -{% if feature_join %} - -### SimpleColumns {#simplecolumns} - -`SimpleColumns` / `DisableSimpleColumns` - -| Value type | Default | -| --- | --- | -| Flag | true | - -When you use `SELECT foo.* FROM ... AS foo`, remove the `foo.` prefix from the names of the result columns. - -It can be also used with a [JOIN](../../join.md), but in this case it may fail in the case of a name conflict (that can be resolved by using [WITHOUT](../../select/without.md) and renaming columns). For JOIN in SimpleColumns mode, an implicit Coalesce is made for key columns: the query `SELECT * FROM T1 AS a JOIN T2 AS b USING(key)` in the SimpleColumns mode works same as `SELECT a.key ?? b.key AS key, ... FROM T1 AS a JOIN T2 AS b USING(key)`. - -### CoalesceJoinKeysOnQualifiedAll - -`CoalesceJoinKeysOnQualifiedAll` / `DisableCoalesceJoinKeysOnQualifiedAll` - -| Value type | Default | -| --- | --- | -| Flag | true | - -Controls implicit Coalesce for the key `JOIN` columns in the SimpleColumns mode. If the flag is set, the Coalesce is made for key columns if there is at least one expression in the format `foo.*` or `*` in SELECT: for example, `SELECT a.* FROM T1 AS a JOIN T2 AS b USING(key)`. If the flag is not set, then Coalesce for JOIN keys is made only if there is an asterisk '*' after `SELECT` - -### StrictJoinKeyTypes - -`StrictJoinKeyTypes` / `DisableStrictJoinKeyTypes` - -| Value type | Default | -| --- | --- | -| Flag | false | - -If the flag is set, then [JOIN](../../join.md) will require strict matching of key types. -By default, JOIN preconverts keys to a shared type, which might result in performance degradation. -StrictJoinKeyTypes is a [scoped](../../pragma.md#pragmascope) setting. - -{% endif %} - -### AnsiInForEmptyOrNullableItemsCollections - -| Value type | Default | -| --- | --- | -| Flag | false | - -This pragma brings the behavior of the `IN` operator in accordance with the standard when there's `NULL` in the left or right side of `IN`. The behavior of `IN` when on the right side there is a Tuple with elements of different types also changed. Examples: - -`1 IN (2, 3, NULL) = NULL (was Just(False))` -`NULL IN () = Just(False) (was NULL)` -`(1, null) IN ((2, 2), (3, 3)) = Just(False) (was NULL)` - -For more information about the `IN` behavior when operands include `NULL`s, see [here](../../expressions.md#in). You can explicitly select the old behavior by specifying the pragma `DisableAnsiInForEmptyOrNullableItemsCollections`. If no pragma is set, then a warning is issued and the old version works. - -### AnsiRankForNullableKeys - -| Value type | Default | -| --- | --- | -| Flag | false | - -Aligns the RANK/DENSE_RANK behavior with the standard if there are optional types in the window sort keys or in the argument of such window functions. It means that: - -* The result type is always Uint64 rather than Uint64?. -* NULLs in keys are treated as equal to each other (the current implementation returns NULL). - -You can explicitly select the old behavior by using the `DisableAnsiRankForNullableKeys` pragma. If no pragma is set, then a warning is issued and the old version works. - -### AnsiCurrentRow - -| Value type | Default | -| --- | --- | -| Flag | false | - -Aligns the implicit setting of a window frame with the standard if there is ORDER BY. -If AnsiCurrentRow is not set, then the `(ORDER BY key)` window is equivalent to `(ORDER BY key ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. -The standard also requires that this window behave as `(ORDER BY key RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. -The difference is in how `CURRENT ROW` is interpreted. In `ROWS` mode `CURRENT ROW` is interpreted literally: the current row in a partition. -In `RANGE` mode, the end of the `CURRENT ROW` frame means "the last row in a partition with a sort key equal to the current row". - -### AnsiOrderByLimitInUnionAll - -| Value type | Default | -| --- | --- | -| Flag | false | - -Aligns the UNION ALL behavior with the standard if there is `ORDER BY/LIMIT/DISCARD/INSERT INTO` in the combined subqueries. It means that: - -* `ORDER BY/LIMIT/INSERT INTO` are allowed only after the last subquery. -* `DISCARD` is allowed only before the first subquery. -* The specified operators apply to the `UNION ALL` result (unlike the current behavior when they apply only to the subquery). -* To apply an operator to a subquery, enclose the subquery in parentheses. - -You can explicitly select the old behavior by using the `DisableAnsiOrderByLimitInUnionAll` pragma. If no pragma is set, then a warning is issued and the old version works. - -### OrderedColumns {#orderedcolumns} - -`OrderedColumns`/`DisableOrderedColumns` - -Output the [column order](../../select/order_by.md) in SELECT/JOIN/UNION ALL and preserve it when writing the results. The order of columns is undefined by default. - -### PositionalUnionAll {#positionalunionall} - -Enable the standard column-by-column execution for [UNION ALL](../../select/union.md#unionall). This automatically enables -[ordered columns](#orderedcolumns). - -### RegexUseRe2 - -| Value type | Default | -| --- | --- | -| Flag | false | - -Use Re2 UDF instead of Pcre to execute SQL the `REGEX`,`MATCH`,`RLIKE` statements. Re2 UDF can properly handle Unicode characters, unlike the default Pcre UDF. - -### ClassicDivision - -| Value type | Default | -| --- | --- | -| Flag | true | - -In the classical version, the result of integer division remains integer (by default). -If disabled, the result is always Double. -ClassicDivision is a [scoped](../../pragma.md#pragmascope) setting. - -### UnicodeLiterals - -`UnicodeLiterals`/`DisableUnicodeLiterals` - -| Value type | Default | -| --- | --- | -| Flag | false | - -When this mode is enabled, string literals without suffixes like "foo"/'bar'/@@multiline@@ will be of type `Utf8`, when disabled - `String`. -UnicodeLiterals is a [scoped](../../pragma.md#pragmascope) setting. - -### WarnUntypedStringLiterals - -`WarnUntypedStringLiterals`/`DisableWarnUntypedStringLiterals` - -| Value type | Default | -| --- | --- | -| Flag | false | - -When this mode is enabled, a warning will be generated for string literals without suffixes like "foo"/'bar'/@@multiline@@. It can be suppressed by explicitly choosing the suffix `s` for the `String` type, or `u` for the `Utf8` type. -WarnUntypedStringLiterals is a [scoped](../../pragma.md#pragmascope) setting. - -### AllowDotInAlias - -| Value type | Default | -| --- | --- | -| Flag | false | - -Enable dot in names of result columns. This behavior is disabled by default, since the further use of such columns in JOIN is not fully implemented. - -### WarnUnnamedColumns - -| Value type | Default | -| --- | --- | -| Flag | false | - -Generate a warning if a column name was automatically generated for an unnamed expression in `SELECT` (in the format `column[0-9]+`). - -### GroupByLimit - -| Value type | Default | -| --- | --- | -| Positive number | 32 | - -Increasing the limit on the number of dimensions in [GROUP BY](../../group_by.md). - -{% if feature_group_by_rollup_cube %} - -### GroupByCubeLimit - -| Value type | Default | -| --- | --- | -| Positive number | 5 | - -Increasing the limit on the number of dimensions in [GROUP BY](../../group_by.md#rollup-cube-group-sets). - -Use this option with care, because the computational complexity of the query grows exponentially with the number of dimensions. - -{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/issue_protos.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/issue_protos.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/ydb.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/ydb.md deleted file mode 100644 index 5c480414f1e2..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/ydb.md +++ /dev/null @@ -1,24 +0,0 @@ -{% if tech %} - -## YDB - -### `ydb.CostBasedOptimizationLevel` {#costbasedoptimizationlevel} - -| Level | Description | -| ----- | ------------------------ | -| 0 | Cost-based optimizer is disabled. | -| 1 | Cost-based optimizer is disabled, but estimates are computed and available. | -| 2 | Cost-based optimizer is enabled only for queries that include [column-oriented tables](../../../../../concepts/glossary.md#column-oriented-table). | -| 3 | Cost-based optimizer is enabled for all queries, but `LookupJoin` is preferred for row-oriented tables. | -| 4 | Cost-based optimizer is enabled for all queries. | - -### `kikimr.IsolationLevel` - -| Value type | Default | -| --- | --- | -| Serializable, ReadCommitted, ReadUncommitted, or ReadStale. | Serializable | - -An experimental pragma that allows you to reduce the isolation level of the current YDB transaction. - -{% endif %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/yson.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/yson.md deleted file mode 100644 index 50058c132f17..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/pragma/yson.md +++ /dev/null @@ -1,28 +0,0 @@ -## Yson - -Managing the default behavior of Yson UDF, for more information, see the [documentation](../../../udf/list/yson.md) and, in particular, [Yson::Options](../../../udf/list/yson.md#ysonoptions). - -### `yson.AutoConvert` - -| Value type | Default | -| --- | --- | -| Flag | false | - -Automatic conversion of values to the required data type in all Yson UDF calls, including implicit calls. - -### `yson.Strict` - -| Value type | Default | -| --- | --- | -| Flag | true | - -Strict mode control in all Yson UDF calls, including implicit calls. If the value is omitted or is `"true"`, it enables the strict mode. If the value is `"false"`, it disables the strict mode. - -### `yson.DisableStrict` - -| Value type | Default | -| --- | --- | -| Flag | false | - -An inverted version of `yson.Strict`. If the value is omitted or is `"true"`, it disables the strict mode. If the value is `"false"`, it enables the strict mode. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/replace_into.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/replace_into.md deleted file mode 100644 index 5d7ca5bc758a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/replace_into.md +++ /dev/null @@ -1,42 +0,0 @@ -# REPLACE INTO - -{% if oss == true and backend_name == "YDB" %} - -{% note warning %} - -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} - -{% include [ways_add_data_to_olap](../../../../_includes/ways_add_data_to_olap.md) %} - -{% endnote %} - -{% endif %} - -Saves data to a table, overwriting the rows based on the primary key.{% if feature_mapreduce %} The table is searched by name in the database specified by the [USE](../use.md) operator.{% endif %} If the given primary key is missing, a new row is added to the table. If the given `PRIMARY_KEY` exists, the row is overwritten. The values of columns not involved in the operation are replaced by their default values. - -{% note info %} - -Unlike [`INSERT INTO`](../insert_into.md) and [`UPDATE`](../update.md), the queries [`UPSERT INTO`](../upsert_into.md) and `REPLACE INTO` don't need to pre-fetch the data, hence they run faster. - -{% endnote %} - -## Examples - -* Setting values for `REPLACE INTO` using `VALUES`. - - ```yql - REPLACE INTO my_table (Key1, Key2, Value2) VALUES - (1u, "One", 101), - (2u, "Two", 102); - COMMIT; - ``` - -* Fetching values for `REPLACE INTO` using a `SELECT`. - - ```yql - REPLACE INTO my_table - SELECT Key AS Key1, "Empty" AS Key2, Value AS Value1 - FROM my_table1; - COMMIT; - ``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/calc.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/calc.md deleted file mode 100644 index d779c2ecdba1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/calc.md +++ /dev/null @@ -1,16 +0,0 @@ -# SELECT - -Returns the result of evaluating the expressions specified after `SELECT`. - -It can be used in combination with other operations to obtain other effect. - -## Examples - -```yql -SELECT "Hello, world!"; -``` - -```yql -SELECT 2 + 2; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/column_order.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/column_order.md deleted file mode 100644 index 7fac840ccb57..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/column_order.md +++ /dev/null @@ -1,31 +0,0 @@ -## Column order in YQL {#orderedcolumns} - -The standard SQL is sensitive to the order of columns in projections (that is, in `SELECT`). While the order of columns must be preserved in the query results or when writing data to a new table, some SQL constructs use this order. -This applies, for example, to [UNION ALL](../../select/union.md#union_all) and positional [ORDER BY](../../select/order_by.md) (ORDER BY ordinal). - -The column order is ignored in YQL by default: - -* The order of columns in the output tables and query results is undefined -* The data scheme of the `UNION ALL` result is output by column names rather than positions - -If you enable `PRAGMA OrderedColumns;`, the order of columns is preserved in the query results and is derived from the order of columns in the input tables using the following rules: - -* `SELECT`: an explicit column enumeration dictates the result order. -* `SELECT` with an asterisk (`SELECT * FROM ...`) inherits the order from its input. - -{% if feature_join %} - -* The order of columns after [JOIN](../../join.md): First output the left-hand columns, then the right-hand ones. If the column order in any of the sides in the `JOIN` output is undefined, the column order in the result is also undefined. - -{% endif %} - -* The order in `UNION ALL` depends on the [UNION ALL](../../select/union.md#union_all) execution mode. -* The column order for [AS_TABLE](../../select/from_as_table.md) is undefined. - -{% note warning %} - -In the YT table schema, key columns always precede non-key columns. The order of key columns is determined by the order of the composite key. -When `PRAGMA OrderedColumns;` is enabled, non-key columns preserve their output order. - -{% endnote %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/combining_queries.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/combining_queries.md deleted file mode 100644 index f650aeefcfac..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/combining_queries.md +++ /dev/null @@ -1,26 +0,0 @@ -### Combining queries {#combining-queries} - -Results of several SELECT statements (or subqueries) can be combined using `UNION` and `UNION ALL` keywords. - -```yql -query1 UNION [ALL] query2 (UNION [ALL] query3 ...) -``` - -Union of more than two queries is interpreted as a left-associative operation, that is - -```yql -query1 UNION query2 UNION ALL query3 -``` - -is interpreted as - -```yql -(query1 UNION query2) UNION ALL query3 -``` - -If the underlying queries have one of the `ORDER BY/LIMIT/DISCARD/INTO RESULT` operators, the following rules apply: - -* `ORDER BY/LIMIT/INTO RESULT` is only allowed after the last query -* `DISCARD` is only allowed before the first query -* the operators apply to the `UNION [ALL]` as a whole, instead of referring to one of the queries -* to apply the operator to one of the queries, enclose the query in parantheses diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/execution.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/execution.md deleted file mode 100644 index 142a4a4e07b2..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/execution.md +++ /dev/null @@ -1,32 +0,0 @@ -## SELECT execution procedure {#selectexec} - -The `SELECT` query result is calculated as follows: - -* Determine the set of input tables by evaluating the [FROM](../../select/from.md) clauses. -* Apply [SAMPLE](../../select/sample.md)/[TABLESAMPLE](../../select/sample.md) to input tables. -* Execute [FLATTEN COLUMNS](../../flatten.md#flatten-columns) or [FLATTEN BY](../../flatten.md); aliases set in `FLATTEN BY` become visible after this point. - -{% if feature_join %} - -* Execute every [JOIN](../../join.md). - -{% endif %} - -* Add to (or replace in) the data the columns listed in [GROUP BY ... AS ...](../../group_by.md). -* Execute [WHERE](../../select/where.md) — Discard all the data mismatching the predicate. -* Execute [GROUP BY](../../group_by.md), evaluate aggregate functions. -* Apply the filter [HAVING](../../group_by.md#having). - -{% if feature_window_functions %} - -* Evaluate [window functions](../../window.md); - -{% endif %} - -* Evaluate expressions in `SELECT`. -* Assign names set by aliases to expressions in `SELECT`. -* Apply top-level [DISTINCT](../../select/distinct.md) to the resulting columns. -* Execute similarly every subquery inside [UNION ALL](../../select/union.md#union_all), combine them (see [PRAGMA AnsiOrderByLimitInUnionAll](../../pragma.md#pragmas)). -* Perform sorting with [ORDER BY](../../select/order_by.md). -* Apply [OFFSET and LIMIT](../../select/limit_offset.md) to the result. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/union.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/union.md deleted file mode 100644 index f4ee7f11c58c..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/union.md +++ /dev/null @@ -1,13 +0,0 @@ -## UNION {#union} - -Union of the results of the underlying queries, with duplicates removed. -Behavior is identical to using `UNION ALL` followed by `SELECT DISTINCT *`. -Refer to [UNION ALL](../../select/union.md#union-all) for more details. - -### Examples - -```yql -SELECT key FROM T1 -UNION -SELECT key FROM T2 -- returns the set of distinct keys in the tables -``` diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/union_all_rules.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/union_all_rules.md deleted file mode 100644 index 7c41e08bf824..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/union_all_rules.md +++ /dev/null @@ -1,5 +0,0 @@ -* The resulting table includes all columns that were found in at least one of the input tables. -* If a column wasn't present in all the input tables, then it's automatically assigned the [optional data type](../../../types/optional.md) (that can accept `NULL`). -* If a column in different input tables had different types, then the shared type (the broadest one) is output. -* If a column in different input tables had a heterogeneous type, for example, string and numeric, an error is raised. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/where.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/where.md deleted file mode 100644 index bdcc977ce84d..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/_includes/select/where.md +++ /dev/null @@ -1,11 +0,0 @@ -# WHERE - -Filtering rows in the `SELECT` result based on a condition in {% if backend_name == "YDB" %}[row-oriented](../../../../../concepts/datamodel/table.md#row-oriented-tables) or [column-oriented](../../../../../concepts/datamodel/table.md#column-oriented-tables){% else %} tables{% endif %}. - -## Example - -```yql -SELECT key FROM my_table -WHERE value > 0; -``` - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/action.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/action.md deleted file mode 100644 index 2ddce04ead2a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/action.md +++ /dev/null @@ -1,11 +0,0 @@ -# ACTION - -{% include [x](_includes/action/define_do.md) %} - -{% include [x](_includes/action/begin.md) %} - -{% if feature_mapreduce %} - - {% include [x](_includes/action/evaluate.md) %} - -{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/commit.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/commit.md deleted file mode 100644 index 1915c2f9fce7..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/commit.md +++ /dev/null @@ -1 +0,0 @@ -{% include [commit](./_includes/select/commit.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table.md deleted file mode 100644 index afc4f96ab9e1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/create_table.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/create_table.md) %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/declare.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/declare.md deleted file mode 100644 index a0a3f0bb8ac1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/declare.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/declare/general.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/delete.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/delete.md deleted file mode 100644 index a454969c1458..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/delete.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/delete.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/discard.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/discard.md deleted file mode 100644 index c927bbe5b167..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/discard.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/discard.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/drop_table.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/drop_table.md deleted file mode 100644 index 7df1a53de191..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/drop_table.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/drop_table.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/export_import.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/export_import.md deleted file mode 100644 index 874d843a7b72..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/export_import.md +++ /dev/null @@ -1,2 +0,0 @@ -{% include [x](_includes/export_import.md) %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/expressions.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/expressions.md deleted file mode 100644 index e3bce9d7ddd8..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/expressions.md +++ /dev/null @@ -1,32 +0,0 @@ -# Expressions - -{% include [x](_includes/expressions/concatenation.md) %} - -{% include [x](_includes/expressions/check-match.md) %} - -{% include [x](_includes/expressions/operators.md) %} - -{% include [x](_includes/expressions/is-null.md) %} - -{% include [x](_includes/expressions/is-distinct-from.md) %} - -{% include [x](_includes/expressions/between.md) %} - -{% include [x](_includes/expressions/in.md) %} - -{% include [x](_includes/expressions/as.md) %} - -{% include [x](_includes/expressions/cast.md) %} - -{% include [x](_includes/expressions/bitcast.md) %} - -{% include [x](_includes/expressions/case.md) %} - -{% include [x](_includes/expressions/named-nodes.md) %} - -{% include [x](_includes/expressions/tables.md) %} - -{% include [x](_includes/expressions/lambda.md) %} - -{% include [x](_includes/expressions/items-access.md) %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/flatten.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/flatten.md deleted file mode 100644 index 4068bae5b7e1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/flatten.md +++ /dev/null @@ -1,7 +0,0 @@ -{% include [x](_includes/flatten/flatten_by.md) %} - -{% include [x](_includes/flatten/flatten_type_by.md) %} - -{% include [x](_includes/flatten/flatten_other_db.md) %} - -{% include [x](_includes/flatten/flatten_columns.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/group_by.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/group_by.md deleted file mode 100644 index 8fa86c988cdb..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/group_by.md +++ /dev/null @@ -1,27 +0,0 @@ -{% if select_command == "SELECT STREAM" %} - -{% include [x](_includes/group_by/general_stream.md) %} - -{% include [x](_includes/group_by/having_stream.md) %} - -{% else %} - -{% include [x](_includes/group_by/general.md) %} - -{% include [x](_includes/group_by/session_window.md) %} - -{% if feature_group_by_rollup_cube %} - -{% include [x](_includes/group_by/rollup_cube_sets.md) %} - -{% endif %} - -{% include [x](_includes/group_by/distinct.md) %} - -{% include [x](_includes/group_by/compact.md) %} - -{% include [x](_includes/group_by/having.md) %} - -{% endif %} - - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/insert_into.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/insert_into.md deleted file mode 100644 index 07b749b03799..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/insert_into.md +++ /dev/null @@ -1,3 +0,0 @@ -{% include [x](_includes/insert_into.md) %} - -{% include [x](_includes/insert_hints.md) %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/into_result.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/into_result.md deleted file mode 100644 index 2c4b4bc4e71a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/into_result.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/into_result.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/join.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/join.md deleted file mode 100644 index 8974a13de711..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/join.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/join.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/lexer.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/lexer.md deleted file mode 100644 index 1b7534021033..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/lexer.md +++ /dev/null @@ -1,3 +0,0 @@ - -{% include [x](_includes/lexer.md) %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/not_yet_supported.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/not_yet_supported.md deleted file mode 100644 index a5646c7fcd0c..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/not_yet_supported.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/not_yet_supported.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/pragma.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/pragma.md deleted file mode 100644 index 5249455c7d3f..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/pragma.md +++ /dev/null @@ -1,13 +0,0 @@ -# PRAGMA - -{% include [x](_includes/pragma/definition.md) %} - -{% include [x](_includes/pragma/global.md) %} - -{% include [x](_includes/pragma/yson.md) %} - -{% include [x](_includes/pragma/files.md) %} - -{% include [x](_includes/pragma/ydb.md) %} - -{% include [x](_includes/pragma/debug.md) %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/process.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/process.md deleted file mode 100644 index f92036e8134a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/process.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/process.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/reduce.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/reduce.md deleted file mode 100644 index 7bd83ef5f7e2..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/reduce.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/reduce.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/replace_into.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/replace_into.md deleted file mode 100644 index ad55a961190e..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/replace_into.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/replace_into.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select.md deleted file mode 100644 index 140549fcede2..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select.md +++ /dev/null @@ -1,64 +0,0 @@ -# SELECT syntax - -{% include [x](_includes/select/calc.md) %} - -{% include [x](_includes/select/from.md) %} - -{% if feature_secondary_index %} - - {% include [x](_includes/select/secondary_index.md) %} - -{% endif %} - -{% include [x](_includes/select/with.md) %} - -{% include [x](_includes/select/where.md) %} - -{% include [x](_includes/select/order_by.md) %} - -{% include [x](_includes/select/limit_offset.md) %} - -{% include [x](_includes/select/assume_order_by.md) %} - -{% include [x](_includes/select/sample.md) %} - -{% include [x](_includes/select/distinct.md) %} - -{% include [x](_includes/select/execution.md) %} - -{% include [x](_includes/select/column_order.md) %} - -{% include [x](_includes/select/combining_queries.md) %} - -{% include [x](_includes/select/union_all.md) %} - -{% include [x](_includes/select/union.md) %} - -{% include [x](_includes/select/commit.md) %} - -{% if feature_bulk_tables %} - - {% include [x](_includes/select/functional_tables.md) %} - - {% include [x](_includes/select/folder.md) %} - -{% endif %} - -{% include [x](_includes/select/without.md) %} - -{% include [x](_includes/select/from_select.md) %} - -{% if feature_mapreduce %} - - {% include [x](_includes/select/view.md) %} - -{% endif %} - -{% if feature_temp_table %} - - {% include [x](_includes/select/temporary_table.md) %} - -{% endif %} - -{% include [x](_includes/select/from_as_table.md) %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/assume_order_by.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/assume_order_by.md deleted file mode 100644 index 084e7e7c1ff7..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/assume_order_by.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/assume_order_by.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/concat.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/concat.md deleted file mode 100644 index 9a8c4ab36041..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/concat.md +++ /dev/null @@ -1 +0,0 @@ -{% include [concat](../_includes/select/functional_tables.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/distinct.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/distinct.md deleted file mode 100644 index 0f27bb32d78c..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/distinct.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/distinct.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/folder.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/folder.md deleted file mode 100644 index ef425dd99856..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/folder.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/folder.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/from.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/from.md deleted file mode 100644 index 84c88f1d165a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/from.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/from.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/from_as_table.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/from_as_table.md deleted file mode 100644 index f840fecb5d66..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/from_as_table.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/from_as_table.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/from_select.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/from_select.md deleted file mode 100644 index 557bbeb8d469..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/from_select.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/from_select.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/index.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/index.md deleted file mode 100644 index 06d90d80e185..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/index.md +++ /dev/null @@ -1,57 +0,0 @@ - - -{% include [x](../_includes/select/calc.md) %} - -{% include [x](../_includes/select/execution.md) %} - -{% include [x](../_includes/select/column_order.md) %} - -{% include [x](../_includes/select/combining_queries.md) %} - -## Clauses supported in SELECT - -* [FROM](from.md) -* [FROM AS_TABLE](from_as_table.md) -* [FROM SELECT](from_select.md) -* [DISTINCT](distinct.md) -* [UNIQUE DISTINCT](unique_distinct_hints.md) -* [UNION](union.md) -* [WITH](with.md) -* [WITHOUT](without.md) -* [WHERE](where.md) -* [ORDER BY](order_by.md) -* [ASSUME ORDER BY](assume_order_by.md) -* [LIMIT OFFSET](limit_offset.md) -* [SAMPLE](sample.md) -* [TABLESAMPLE](sample.md) - -{% if yt %} - -* [FOLDER](folder.md) -* [WalkFolders](walk_folders.md) - -{% endif %} - -{% if feature_mapreduce %} - -* [VIEW](view.md) - -{% endif %} - -{% if feature_temp_table %} - -* [TEMPORARY TABLE](temporary_table.md) - -{% endif %} - -{% if feature_bulk_tables %} - -* [CONCAT](concat.md) - -{% endif %} - -{% if feature_secondary_index %} - -* [VIEW INDEX](secondary_index.md) - -{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/limit_offset.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/limit_offset.md deleted file mode 100644 index bc0ca29fdf63..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/limit_offset.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/limit_offset.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/order_by.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/order_by.md deleted file mode 100644 index 01b1606a4b0d..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/order_by.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/order_by.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/sample.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/sample.md deleted file mode 100644 index 5996bdd2b8da..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/sample.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/sample.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/secondary_index.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/secondary_index.md deleted file mode 100644 index a31ea8141e18..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/secondary_index.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/secondary_index.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/temporary_table.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/temporary_table.md deleted file mode 100644 index 8e456affcca5..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/temporary_table.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/temporary_table.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/union.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/union.md deleted file mode 100644 index 62aa310ce460..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/union.md +++ /dev/null @@ -1,11 +0,0 @@ -# Combining subquery results (UNION) - -{% if oss == true and backend_name == "YDB" %} - -{% include [olap_warning_note](../../../../_includes/not_allow_for_olap_note.md) %} - -{% endif %} - -{% include [union](../_includes/select/union.md)%} - -{% include [union](../_includes/select/union_all.md)%} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/unique_distinct_hints.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/unique_distinct_hints.md deleted file mode 100644 index 68332b95e095..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/unique_distinct_hints.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/unique_distinct_hints.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/view.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/view.md deleted file mode 100644 index 7774fb111619..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/view.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/view.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/walk_folders.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/walk_folders.md deleted file mode 100644 index ef16e58eaa12..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/walk_folders.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/walk_folders.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/where.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/where.md deleted file mode 100644 index 7457706fa51a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/where.md +++ /dev/null @@ -1 +0,0 @@ -{% include [where](../_includes/select/where.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/with.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/with.md deleted file mode 100644 index 21a0c2d75548..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/with.md +++ /dev/null @@ -1 +0,0 @@ -{% include [with](../_includes/select/with.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/without.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select/without.md deleted file mode 100644 index c51b77df6529..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select/without.md +++ /dev/null @@ -1 +0,0 @@ -{% include [without](../_includes/select/without.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/select_stream.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/select_stream.md deleted file mode 100644 index 285d0df84077..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/select_stream.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/select_stream.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/subquery.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/subquery.md deleted file mode 100644 index fe76cea2328d..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/subquery.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/subquery.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/update.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/update.md deleted file mode 100644 index fbb88a10d7c1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/update.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/update.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/upsert_into.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/upsert_into.md deleted file mode 100644 index 6fddab60f24b..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/upsert_into.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/upsert_into.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/use.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/use.md deleted file mode 100644 index d35121c3930a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/use.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/use.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/values.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/values.md deleted file mode 100644 index a5473cf9284a..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/values.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/values.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/syntax/window.md b/ydb/docs/en/core/yql/reference/yql-core/syntax/window.md deleted file mode 100644 index c07321d69e7e..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/syntax/window.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/window.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/toc_m.yaml b/ydb/docs/en/core/yql/reference/yql-core/toc_m.yaml deleted file mode 100644 index 35ad87ba4d80..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/toc_m.yaml +++ /dev/null @@ -1,2 +0,0 @@ -items: -- include: { mode: merge, path: yql-product/toc_product.yaml } diff --git a/ydb/docs/en/core/yql/reference/yql-core/toc_product.yaml b/ydb/docs/en/core/yql/reference/yql-core/toc_product.yaml deleted file mode 100644 index 9781b330eea1..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/toc_product.yaml +++ /dev/null @@ -1,9 +0,0 @@ -title: YQL over {{ backend_name }} -# href: index.md -items: -- name: Data types - include: { mode: link, path: types/toc_i.yaml } -- name: Syntax - include: { mode: link, path: syntax/toc_i.yaml } -- name: Built-in functions - include: { mode: link, path: builtins/toc_i.yaml } diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/datatypes_primitive_datetime.md b/ydb/docs/en/core/yql/reference/yql-core/types/_includes/datatypes_primitive_datetime.md deleted file mode 100644 index 8f96cc3504aa..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/datatypes_primitive_datetime.md +++ /dev/null @@ -1,10 +0,0 @@ -| Type | Description | Notes | -| ----- | ----- | ----- | -| `Date` | Date, precision to the day | Range of values for all time types except `Interval`: From 00:00 01.01.1970 to 00:00 01.01.2106. Internal `Date` representation: Unsigned 16-bit integer | -| `Datetime` | Date/time, precision to the second | Internal representation: Unsigned 32-bit integer | -| `Timestamp` | Date/time, precision to the microsecond | Internal representation: Unsigned 64-bit integer | -| `Interval` | Time interval (signed), precision to microseconds | Value range: From -136 years to +136 years. Internal representation: Signed 64-bit integer. {% if feature_map_tables %}Can't be used in the primary key{% endif %} | -| `TzDate` | Date with time zone label, precision to the day | Not supported in table columns | -| `TzDateTime` | Date/time with time zone label, precision to the second | Not supported in table columns | -| `TzTimestamp` | Date/time with time zone label, precision to the microsecond | Not supported in table columns | - diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/datatypes_primitive_number.md b/ydb/docs/en/core/yql/reference/yql-core/types/_includes/datatypes_primitive_number.md deleted file mode 100644 index f2e782f7ded9..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/datatypes_primitive_number.md +++ /dev/null @@ -1,17 +0,0 @@ -| Type | Description | Notes | -| ----- | ----- | ----- | -| `Bool` | Boolean value. | -| `Int8` | A signed integer.
Acceptable values: from -27 to 27–1. | -| `Int16` | A signed integer.
Acceptable values: from –215 to 215–1. | -| `Int32` | A signed integer.
Acceptable values: from –231 to 231–1. | -| `Int64` | A signed integer.
Acceptable values: from –263 to 263–1. | -| `Uint8` | An unsigned integer.
Acceptable values: from 0 to 28–1. | -| `Uint16` | An unsigned integer.
Acceptable values: from 0 to 216–1. | -| `Uint32` | An unsigned integer.
Acceptable values: from 0 to 232–1. | -| `Uint64` | An unsigned integer.
Acceptable values: from 0 to 264–1. | -| `Float` | A real number with variable precision, 4 bytes in size. | {% if feature_map_tables %}Can't be used in the primary key{% endif %} | -| `Double` | A real number with variable precision, 8 bytes in size. | {% if feature_map_tables %}Can't be used in the primary key{% endif %} | -| `Decimal` | A real number with the specified precision, up to 35 decimal digits | {% if feature_map_tables %}When used in table columns, the precision is fixed: Decimal(22,9){% endif %} | -{% if feature_map_tables %} -|`DyNumber` | A binary representation of a real number with an accuracy of up to 38 digits.
Acceptable values: positive numbers from 1×10-130 up to 1×10126–1, negative numbers from -1×10126–1 to -1×10-130, and 0.
Compatible with the `Number` type in AWS DynamoDB. It's not recommended for {{ backend_name_lower }}-native applications. | | -{% endif %} diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/datatypes_primitive_string.md b/ydb/docs/en/core/yql/reference/yql-core/types/_includes/datatypes_primitive_string.md deleted file mode 100644 index 767e48873c58..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/datatypes_primitive_string.md +++ /dev/null @@ -1,27 +0,0 @@ -| Type | Description | Notes | -| ----- | ----- | ----- | -| `String` | A string that can contain any binary data | -| `Utf8` | Text encoded in [UTF-8](https://en.wikipedia.org/wiki/UTF-8) | -| `Json` | [JSON](https://en.wikipedia.org/wiki/JSON) represented as text | Doesn't support matching{% if feature_map_tables %}, can't be used in the primary key{% endif %} | -| `JsonDocument` | [JSON](https://en.wikipedia.org/wiki/JSON) in an indexed binary representation | Doesn't support matching{% if feature_map_tables %}, can't be used in the primary key{% endif %} | -| `Yson` | [YSON](../../udf/list/yson.md) in a textual or binary representation. | Doesn't support matching{% if feature_map_tables %}, can't be used in the primary key{% endif %} | -| `Uuid` | Universally unique identifier [UUID](https://tools.ietf.org/html/rfc4122) | - -{% note info "Cell size restrictions" %} - -The maximum value size for a {% if feature_map_tables %}non-key {% endif %} column cell with any string data type is 8 MB. - -{% endnote %} - -Unlike the `JSON` data type that stores the original text representation passed by the user, `JsonDocument` uses an indexed binary representation. An important difference from the point of view of semantics is that `JsonDocument` doesn't preserve formatting, the order of keys in objects, or their duplicates. - -Thanks to the indexed view, `JsonDocument` lets you bypass the document model using `JsonPath` without the need to parse the full content. This helps efficiently perform operations from the [JSON API](../../builtins/json.md), reducing delays and cost of user queries. Execution of `JsonDocument` queries can be up to several times more efficient depending on the type of load. - -Due to the added redundancy, `JsonDocument` is less effective in storage. The additional storage overhead depends on the specific content, but is 20-30% of the original volume on average. Saving data in `JsonDocument` format requires additional conversion from the textual representation, which makes writing it less efficient. However, for most read-intensive scenarios that involve processing data from JSON, this data type is preferred and recommended. - -{% note warning %} - -To store numbers (JSON Number) in `JsonDocument`, as well as for arithmetic operations on them in the [JSON API](../../builtins/json.md), the [Double](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) type is used. Precision might be lost when non-standard representations of numbers are used in the source JSON document. - -{% endnote %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/primitive.md b/ydb/docs/en/core/yql/reference/yql-core/types/_includes/primitive.md deleted file mode 100644 index 5e30b2808bce..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/primitive.md +++ /dev/null @@ -1,122 +0,0 @@ -# Primitive data types - - - -The terms "simple", "primitive", and "elementary" data types are used synonymously. - -## Numeric types {#numeric} - -{% include [datatypes](datatypes_primitive_number.md) %} - -## String types {#string} - -{% include [datatypes](datatypes_primitive_string.md) %} - -## Date and time {#datetime} - -{% include [datatypes](datatypes_primitive_datetime.md) %} - -{% include [x](tz_date_types.md) %} - -## Casting between data types {#cast} - -### Explicit casting {#explicit-cast} - -Explicit casting using [CAST](../../syntax/expressions.md#cast): - -#### Casting to numeric types - -| Type | Bool | Int | Uint | Float | Double | Decimal | -| --- | --- | --- | --- | --- | --- | --- | -| **Bool** | — | Yes1 | Yes1 | Yes1 | Yes1 | No | Yes | No | -| **INT** | Yes2 | — | Yes3 | Yes | Yes | Yes | -| **Uint** | Yes2 | Yes | — | Yes | Yes | Yes | -| **Float** | Yes2 | Yes | Yes | — | Yes | No | -| **Double** | Yes2 | Yes | Yes | Yes | — | No | -| **Decimal** | No | Yes | Yes | Yes | Yes | — | -| **String** | Yes | Yes | Yes | Yes | Yes | Yes | -| **Utf8** | Yes | Yes | Yes | Yes | Yes | Yes | -| **Json** | No | No | No | No | No | No | -| **Yson** | Yes4 | Yes4 | Yes4 | Yes4 | Yes4 | Yes4 | -| **Uuid** | No | No | No | No | No | No | -| **Date** | No | Yes | Yes | Yes | Yes | No | Yes | -| **Datetime** | No | Yes | Yes | Yes | Yes | No | -| **Timestamp** | No | Yes | Yes | Yes | Yes | No | -| **Interval** | No | Yes | Yes | Yes | Yes | No | - -1 `True` is converted to `1` and `False` to `0`. -2 Any value other than `0` is converted to `True`, `0` is converted to `False`. -3 Possible only in the case of a non-negative value. -4 Using the built-in function [Yson::ConvertTo](../../udf/list/yson.md#ysonconvertto). - -#### Converting to date and time data types - -| Type | Date | Datetime | Timestamp | Interval | -| --- | --- | --- | --- | --- | -| **Bool** | No | No | No | No | -| **INT** | Yes | Yes | Yes | Yes | -| **Uint** | Yes | Yes | Yes | Yes | -| **Float** | No | No | No | No | -| **Double** | No | No | No | No | -| **Decimal** | No | No | No | No | -| **String** | Yes | Yes | Yes | Yes | -| **Utf8** | Yes | Yes | Yes | Yes | -| **Json** | No | No | No | No | -| **Yson** | No | No | No | No | -| **Uuid** | No | No | No | No | -| **Date** | — | Yes | Yes | No | -| **Datetime** | Yes | — | Yes | No | -| **Timestamp** | Yes | Yes | — | No | -| **Interval** | No | No | No | — | — | - -#### Conversion to other data types - -| Type | String | Utf8 | Json | Yson | Uuid | -| --- | --- | --- | --- | --- | --- | -| **Bool** | Yes | No | No | No | No | -| **INT** | Yes | No | No | No | No | -| **Uint** | Yes | No | No | No | No | -| **Float** | Yes | No | No | No | No | -| **Double** | Yes | No | No | No | No | -| **Decimal** | Yes | No | No | No | No | -| **String** | — | Yes | Yes | Yes | Yes | -| **Utf8** | Yes | — | No | No | No | -| **Json** | Yes | Yes | — | No | No | -| **Yson** | Yes4 | No | No | No | No | -| **Uuid** | Yes | Yes | No | No | — | -| **Date** | Yes | Yes | No | No | No | -| **Datetime** | Yes | Yes | No | No | No | -| **Timestamp** | Yes | Yes | No | No | No | -| **Interval** | Yes | Yes | No | No | No | - -4 Using the built-in function [Yson::ConvertTo](../../udf/list/yson.md#ysonconvertto). - -##### Examples - -{% include [x](../../_includes/cast_examples.md) %} - -### Implicit casting {#implicit-cast} - -Implicit type casting that occurs in basic operations ( +-\*/) between different data types. The table cells specify the operation result type, if the operation is possible: - -#### Numeric types - -| Type | Int | Uint | Float | Double | -| --- | --- | --- | --- | --- | -| **INT** | — | `INT` | `Float` | `Double` | -| **Uint** | `INT` | — | `Float` | `Double` | -| **Float** | `Float` | `Float` | — | `Double` | -| **Double** | `Double` | `Double` | `Double` | — | - -#### Date and time types - -| Type | Date | Datetime | Timestamp | Interval | TzDate | TzDatetime | TzTimestamp | -| --- | --- | --- | --- | --- | --- | --- | --- | -| **Date** | — | — | — | `Date` | — | — | — | -| **Datetime** | — | — | — | `Datetime` | — | — | — | -| **Timestamp** | — | — | — | `Timestamp` | — | — | — | -| **Interval** | `Date` | `Datetime` | `Timestamp` | — | `TzDate` | `TzDatetime` | `TzTimestamp` | -| **TzDate** | — | — | — | `TzDate` | — | — | — | -| **TzDatetime** | — | — | — | `TzDatetime` | — | — | — | -| **TzTimestamp** | — | — | — | `TzTimestamp` | — | — | — | - diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/tz_date_types.md b/ydb/docs/en/core/yql/reference/yql-core/types/_includes/tz_date_types.md deleted file mode 100644 index 04b495c55398..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/_includes/tz_date_types.md +++ /dev/null @@ -1,19 +0,0 @@ -### Supporting types with a time zone label - -Time zone label for the `TzDate`, `TzDatetime`, `TzTimestamp` types is an attribute that is used: - -* When converting ([CAST](../../syntax/expressions.md#cast), [DateTime::Parse](../../udf/list/datetime.md#parse), [DateTime::Format](../../udf/list/datetime.md#format)) to a string and from a string. -* In [DateTime::Split](../../udf/list/datetime.md#split), a timezone component is added to `Resource`. - -The point in time for these types is stored in UTC, and the timezone label doesn't participate in any other calculations in any way. For example: - -```yql -SELECT -- these expressions are always true for any timezones: the timezone doesn't affect the point in time. - AddTimezone(CurrentUtcDate(), "Europe/Moscow") == - AddTimezone(CurrentUtcDate(), "America/New_York"), - AddTimezone(CurrentUtcDatetime(), "Europe/Moscow") == - AddTimezone(CurrentUtcDatetime(), "America/New_York"); -``` - -Keep in mind that when converting between `TzDate` and `TzDatetime`, or `TzTimestamp` the date's midnight doesn't follow the local time zone, but midnight in UTC for the date in UTC. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/cast.md b/ydb/docs/en/core/yql/reference/yql-core/types/cast.md deleted file mode 100644 index c4581473ba98..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/cast.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/cast.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/containers.md b/ydb/docs/en/core/yql/reference/yql-core/types/containers.md deleted file mode 100644 index 94779f7479bc..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/containers.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/containers.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/json.md b/ydb/docs/en/core/yql/reference/yql-core/types/json.md deleted file mode 100644 index 489138d77682..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/json.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/json.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/optional.md b/ydb/docs/en/core/yql/reference/yql-core/types/optional.md deleted file mode 100644 index 14aa7f1082f7..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/optional.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/optional.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/primitive.md b/ydb/docs/en/core/yql/reference/yql-core/types/primitive.md deleted file mode 100644 index 4ed6b08c3cb5..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/primitive.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/primitive.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/special.md b/ydb/docs/en/core/yql/reference/yql-core/types/special.md deleted file mode 100644 index d6049995bee8..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/special.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/special.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/types/type_string.md b/ydb/docs/en/core/yql/reference/yql-core/types/type_string.md deleted file mode 100644 index 90f907a13518..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/types/type_string.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/type_string.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/index/intro.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/index/intro.md deleted file mode 100644 index 6ca0040a5225..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/index/intro.md +++ /dev/null @@ -1,4 +0,0 @@ -# Functions of built-in C++ libraries - -Many application functions that on the one hand are too specific to become part of the YQL core, and on the other hand might be useful to a wide range of users, are available through built-in C++ libraries. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/index/list.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/index/list.md deleted file mode 100644 index 29f034c1a037..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/index/list.md +++ /dev/null @@ -1,14 +0,0 @@ -* [DateTime](../../datetime.md) -* [Digest](../../digest.md) -* [Histogram](../../histogram.md) -* [Hyperscan](../../hyperscan.md) -* [Ip](../../ip.md) -* [Knn](../../knn.md) -* [Math](../../math.md) -* [Pcre](../../pcre.md) -* [Pire](../../pire.md) -* [Re2](../../re2.md) -* [String](../../string.md) -* [Unicode](../../unicode.md) -* [Url](../../url.md) -* [Yson](../../yson.md) \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/yson/intro_footer.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/yson/intro_footer.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/yson/intro_header.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/yson/intro_header.md deleted file mode 100644 index f2b39dec3b67..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/yson/intro_header.md +++ /dev/null @@ -1,2 +0,0 @@ -YSON is a JSON-like data format developed at Yandex. - diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/yson/ypath_overlay.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/_includes/yson/ypath_overlay.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/histogram.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/histogram.md deleted file mode 100644 index 4a98bfefe7a4..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/histogram.md +++ /dev/null @@ -1 +0,0 @@ -{% include[x](_includes/histogram.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/index.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/index.md deleted file mode 100644 index 7b4e51e9bd95..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/index.md +++ /dev/null @@ -1,4 +0,0 @@ -{% include [x](_includes/index/intro.md) %} - -{% include [x](_includes/index/list.md) %} - diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/string.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/string.md deleted file mode 100644 index 3af9fa2dde1e..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/string.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/string.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/unicode.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/unicode.md deleted file mode 100644 index 2a2d7aebd6d5..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/unicode.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/unicode.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-core/udf/list/url.md b/ydb/docs/en/core/yql/reference/yql-core/udf/list/url.md deleted file mode 100644 index 07f8fc410cf5..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-core/udf/list/url.md +++ /dev/null @@ -1 +0,0 @@ -{% include [url.md](_includes/url.md) %} \ No newline at end of file diff --git a/ydb/docs/en/core/yql/reference/yql-product/toc_product.yaml b/ydb/docs/en/core/yql/reference/yql-product/toc_product.yaml deleted file mode 100644 index a573aa88c591..000000000000 --- a/ydb/docs/en/core/yql/reference/yql-product/toc_product.yaml +++ /dev/null @@ -1,7 +0,0 @@ -items: -- name: Data types - include: { mode: link, path: types/toc_i.yaml } -- name: Syntax - include: { mode: link, path: syntax/toc_i.yaml } -- name: Built-in functions - include: { mode: link, path: builtins/toc_i.yaml } diff --git a/ydb/docs/ru/core/concepts/_includes/ttl.md b/ydb/docs/ru/core/concepts/_includes/ttl.md index 0f45d7aacc0a..e760f2dcdce7 100644 --- a/ydb/docs/ru/core/concepts/_includes/ttl.md +++ b/ydb/docs/ru/core/concepts/_includes/ttl.md @@ -54,7 +54,7 @@ eviction_time = valueof(ttl_column) + evict_after_seconds * наносекунды. * Нельзя указать несколько TTL-колонок. -* Нельзя удалить TTL-колонку. Если это все же требуется, сначала нужно [выключить TTL](../../recipes/yql/ttl.md#disable) на таблице. +* Нельзя удалить TTL-колонку. Если это все же требуется, сначала нужно [выключить TTL](../../yql/reference/recipes/ttl.md#disable) на таблице. * В качестве типа внешнего хранилища доступен только {{ objstorage-name }}. * Действие `DELETE` может быть задано только для последнего тира. @@ -62,6 +62,6 @@ eviction_time = valueof(ttl_column) + evict_after_seconds Управление настройками TTL в настоящий момент возможно с использованием: -* [YQL](../../recipes/yql/ttl.md). +* [YQL](../../yql/reference/recipes/ttl.md). * [Консольного клиента {{ ydb-short-name }}](../../recipes/ydb-cli/ttl.md). * {{ ydb-short-name }} {% if oss %}C++, {% endif %}Go и Python [SDK](../../recipes/ydb-sdk/ttl.md). diff --git a/ydb/docs/ru/core/concepts/glossary.md b/ydb/docs/ru/core/concepts/glossary.md index a06bc9980e01..fa60455417d0 100644 --- a/ydb/docs/ru/core/concepts/glossary.md +++ b/ydb/docs/ru/core/concepts/glossary.md @@ -249,7 +249,7 @@ ### YQL {#yql} -**YQL ({{ ydb-short-name }} Query Language)** — это высокоуровневый язык для работы с системой. Он является диалектом [ANSI SQL](https://en.wikipedia.org/wiki/SQL). Существует много материалов, посвящённых YQL, включая [туториал](../dev/yql-tutorial/index.md), [справочник](../yql/reference/syntax/index.md) и [рецепты](../recipes/yql/index.md). +**YQL ({{ ydb-short-name }} Query Language)** — это высокоуровневый язык для работы с системой. Он является диалектом [ANSI SQL](https://en.wikipedia.org/wiki/SQL). Существует много материалов, посвящённых YQL, включая [туториал](../dev/yql-tutorial/index.md), [справочник](../yql/reference/syntax/index.md) и [рецепты](../yql/reference/recipes/index.md). ### Федеративные запросы {#federated-queries} diff --git a/ydb/docs/ru/core/postgresql/interoperability.md b/ydb/docs/ru/core/postgresql/interoperability.md index e869f3f33ecc..8ef8c41284dc 100644 --- a/ydb/docs/ru/core/postgresql/interoperability.md +++ b/ydb/docs/ru/core/postgresql/interoperability.md @@ -80,7 +80,7 @@ Таблица соответствия типов данных YQL, при их использовании в PostgreSQL запросах: -{% include [topg](../yql/reference/udf/list/_includes/topg.md) %} +{% include [topg](../yql/reference/_includes/topg.md) %} ### Использование данных таблиц, созданных в PostgreSQL синтаксисе, в синтаксисе YQL {#frompg} diff --git a/ydb/docs/ru/core/recipes/index.md b/ydb/docs/ru/core/recipes/index.md index 96dfa3788289..6dda2e081b8d 100644 --- a/ydb/docs/ru/core/recipes/index.md +++ b/ydb/docs/ru/core/recipes/index.md @@ -4,4 +4,4 @@ * [{#T}](ydb-sdk/index.md) * [{#T}](ydb-cli/index.md) -* [{#T}](yql/index.md) \ No newline at end of file +* [{#T}](../yql/reference/recipes/index.md) diff --git a/ydb/docs/ru/core/recipes/toc_p.yaml b/ydb/docs/ru/core/recipes/toc_p.yaml index 47e84fad2c65..19bb3ca8a069 100644 --- a/ydb/docs/ru/core/recipes/toc_p.yaml +++ b/ydb/docs/ru/core/recipes/toc_p.yaml @@ -11,4 +11,4 @@ items: - name: YQL include: mode: link - path: yql/toc_p.yaml + path: ../yql/reference/recipes/toc_i.yaml diff --git a/ydb/docs/ru/core/recipes/ydb-cli/ttl.md b/ydb/docs/ru/core/recipes/ydb-cli/ttl.md index 18573f8c74ef..6ebf888e7476 100644 --- a/ydb/docs/ru/core/recipes/ydb-cli/ttl.md +++ b/ydb/docs/ru/core/recipes/ydb-cli/ttl.md @@ -20,7 +20,7 @@ $ {{ ydb-cli }} -e -d table ttl set --column modified_at - {% include [OLTP_not_allow_note](../../_includes/not_allow_for_oltp_note.md) %} -Для включения вытеснения требуется объект [external data source](../../concepts/datamodel/external_data_source.md), описывающий подключение к внешнему хранилищу. Пример создания объекта можно найти в [рецептах YQL](../yql/ttl.md#enable-tiering-on-existing-tables). +Для включения вытеснения требуется объект [external data source](../../concepts/datamodel/external_data_source.md), описывающий подключение к внешнему хранилищу. Пример создания объекта можно найти в [рецептах YQL](../../yql/reference/recipes/ttl.md#enable-tiering-on-existing-tables). Следующий пример демонстрирует включение вытеснения данных через вызов YQL-запроса из {{ ydb-short-name }} CLI. Строки таблицы `mytable` будут переноситься в бакет, описанный во внешнем источнике данных `/Root/s3_cold_data`, спустя час после наступления времени, записанного в колонке `created_at`, а спустя 24 часа будут удаляться. diff --git a/ydb/docs/ru/core/recipes/ydb-sdk/ttl.md b/ydb/docs/ru/core/recipes/ydb-sdk/ttl.md index a011111da078..f16bb54b786d 100644 --- a/ydb/docs/ru/core/recipes/ydb-sdk/ttl.md +++ b/ydb/docs/ru/core/recipes/ydb-sdk/ttl.md @@ -84,7 +84,7 @@ {% include [OLTP_not_allow_note](../../_includes/not_allow_for_oltp_note.md) %} -Для включения вытеснения требуется объект [external data source](../../concepts/datamodel/external_data_source.md), описывающий подключение к внешнему хранилищу. Создание объекта external data source возможно через [YQL](../yql/ttl.md#enable-tiering-on-existing-tables) и {{ ydb-short-name }} CLI. +Для включения вытеснения требуется объект [external data source](../../concepts/datamodel/external_data_source.md), описывающий подключение к внешнему хранилищу. Создание объекта external data source возможно через [YQL](../../yql/reference/recipes/ttl.md#enable-tiering-on-existing-tables) и {{ ydb-short-name }} CLI. В следующем примере строки таблицы `mytable` будут переноситься в бакет, описанный во внешнем источнике данных `/Root/s3_cold_data`, спустя час после наступления времени, записанного в колонке `created_at`, а спустя 24 часа будут удаляться: diff --git a/ydb/docs/ru/core/yql/reference/yql-core/_includes/cast_examples.md b/ydb/docs/ru/core/yql/reference/_includes/cast_examples.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/_includes/cast_examples.md rename to ydb/docs/ru/core/yql/reference/_includes/cast_examples.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/_includes/decimal_args.md b/ydb/docs/ru/core/yql/reference/_includes/decimal_args.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/_includes/decimal_args.md rename to ydb/docs/ru/core/yql/reference/_includes/decimal_args.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/frompg.md b/ydb/docs/ru/core/yql/reference/_includes/frompg.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/frompg.md rename to ydb/docs/ru/core/yql/reference/_includes/frompg.md diff --git a/ydb/docs/ru/core/yql/reference/_includes/index/intro.md b/ydb/docs/ru/core/yql/reference/_includes/index/intro.md deleted file mode 100644 index 5c0cbf6f43f8..000000000000 --- a/ydb/docs/ru/core/yql/reference/_includes/index/intro.md +++ /dev/null @@ -1,22 +0,0 @@ -# YQL - Обзор - -*YQL* ({{ ydb-short-name }} Query Language) — универсальный декларативный язык запросов к YDB, диалект SQL. YQL создавался для работы с большими распределенными базами данных, и поэтому обладает рядом отличий от стандарта SQL. - -{% if oss == true and backend_name == "YDB" %} - -Инструменты работы с {{ ydb-short-name }} поддерживают интерфейсы отправки YQL-запросов и получения результатов их исполнения: - -{% include [yql/ui_prompt.md](yql/ui_prompt.md) %} - -- [{{ ydb-short-name }} CLI](../../../../reference/ydb-cli/index.md) -- [{{ ydb-short-name }} SDK](../../../../reference/ydb-sdk/index.md) - -В данном разделе документации находится справочник по YQL, который включает разделы: - -- [Типы данных](../../types/index.md) с описанием типов данных, применяемых в YQL -- [Синтаксис](../../syntax/index.md) с полным перечнем команд YQL -- [Встроенные функции](../../builtins/index.md) с описанием доступных встроенных функций - -Также вы можете пройти серию уроков, знакомящих вас с основными командами YQL, в разделе [Туториал YQL](../../../../dev/yql-tutorial/index.md). - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/_includes/index/start.md b/ydb/docs/ru/core/yql/reference/_includes/index/start.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/ru/core/yql/reference/_includes/index/yql/ui_prompt.md b/ydb/docs/ru/core/yql/reference/_includes/index/yql/ui_prompt.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/initial_groups_and_users.md b/ydb/docs/ru/core/yql/reference/_includes/initial_groups_and_users.md similarity index 69% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/initial_groups_and_users.md rename to ydb/docs/ru/core/yql/reference/_includes/initial_groups_and_users.md index 3145e0ee9250..0630ca75f6a3 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/initial_groups_and_users.md +++ b/ydb/docs/ru/core/yql/reference/_includes/initial_groups_and_users.md @@ -1,5 +1,5 @@ {{ ydb-short-name }} может иметь набор групп и пользователей уже с момента начального развёртывания. -Подробнее см. [{#T}](../../../../reference/configuration/index.md#security-bootstrap) и [{#T}](../../../../security/builtin-security.md). +Подробнее см. [{#T}](../../../reference/configuration/index.md#security-bootstrap) и [{#T}](../../../security/builtin-security.md). Такие пользователи и группы ничем не отличаются от пользователей и групп, созданных позже. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/permissions/permissions_list.md b/ydb/docs/ru/core/yql/reference/_includes/permissions_list.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/permissions/permissions_list.md rename to ydb/docs/ru/core/yql/reference/_includes/permissions_list.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/topg.md b/ydb/docs/ru/core/yql/reference/_includes/topg.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/topg.md rename to ydb/docs/ru/core/yql/reference/_includes/topg.md diff --git a/ydb/docs/ru/core/yql/reference/builtins/aggregation.md b/ydb/docs/ru/core/yql/reference/builtins/aggregation.md new file mode 100644 index 000000000000..7a976d7a27ec --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/builtins/aggregation.md @@ -0,0 +1,824 @@ +# Агрегатные функции + +## COUNT {#count} + +### Сигнатура + +```yql +COUNT(*)->Uint64 +COUNT(T)->Uint64 +COUNT(T?)->Uint64 +``` + +Подсчет количества строк в строковой или колоночной таблице (если в качестве аргумента указана `*` или константа) или непустых значений в столбце таблицы (если в качестве аргумента указано имя столбца). + +Как и другие агрегатные функции, может использоваться в сочетании с [GROUP BY](../syntax/group_by.md) для получения статистики по частям таблицы, соответствующим значениям в столбцах, по которым идет группировка. {% if select_statement != "SELECT STREAM" %}А модификатор [DISTINCT](../syntax/group_by.md#distinct) позволяет посчитать число уникальных значений.{% endif %} + +### Примеры + +```yql +SELECT COUNT(*) FROM my_table; +``` + +```yql +SELECT key, COUNT(value) FROM my_table GROUP BY key; +``` +{% if select_statement != "SELECT STREAM" %} + +```yql +SELECT COUNT(DISTINCT value) FROM my_table; +``` +{% endif %} + +## MIN и MAX {#min-max} + +### Сигнатура + +```yql +MIN(T?)->T? +MIN(T)->T? +MAX(T?)->T? +MAX(T)->T? +``` + +Минимальное или максимальное значение. + +В качестве аргумента допустимо произвольное вычислимое выражение с результатом, допускающим сравнение значений. + +### Примеры + +```yql +SELECT MIN(value), MAX(value) FROM my_table; +``` + +## SUM {#sum} + +### Сигнатура + +```yql +SUM(Unsigned?)->Uint64? +SUM(Signed?)->Int64? +SUM(Interval?)->Interval? +SUM(Decimal(N, M)?)->Decimal(35, M)? +``` + +Сумма чисел. + +В качестве аргумента допустимо произвольное вычислимое выражение с числовым результатом или типом `Interval`. + +Целые числа автоматически расширяются до 64 бит, чтобы уменьшить риск переполнения. + +```yql +SELECT SUM(value) FROM my_table; +``` + +## AVG {#avg} + +### Сигнатура + +```yql +AVG(Double?)->Double? +AVG(Interval?)->Interval? +AVG(Decimal(N, M)?)->Decimal(N, M)? +``` + +Арифметическое среднее. + +В качестве аргумента допустимо произвольное вычислимое выражение с числовым результатом или типом `Interval`. + +Целочисленные значения и интервалы времени автоматически приводятся к Double. + +### Примеры + +```yql +SELECT AVG(value) FROM my_table; +``` + +## COUNT_IF {#count-if} + +### Сигнатура + +```yql +COUNT_IF(Bool?)->Uint64? +``` + +Количество строк, для которых указанное в качестве аргумента выражение истинно (результат вычисления выражения — true). + +Значение `NULL` приравнивается к `false` (в случае, если тип аргумента `Bool?`). + +Функция *не* выполняет неявного приведения типов к булевым для строк и чисел. + +### Примеры + +```yql +SELECT + COUNT_IF(value % 2 == 1) AS odd_count +``` + +{% if select_statement != "SELECT STREAM" %} + +{% note info %} + +Если нужно посчитать число уникальных значений на строках, где выполняется условие, то в отличие от остальных агрегатных функций модификатор [DISTINCT](../syntax/group_by.md#distinct) тут не поможет, так как в аргументах нет никаких значений. Для получения данного результата, стоит воспользоваться в подзапросе встроенной функцией [IF](basic.md#if) с двумя аргументами (чтобы в else получился `NULL`), а снаружи сделать [COUNT(DISTINCT ...)](#count) по её результату. + +{% endnote %} + +{% endif %} + +## SUM_IF и AVG_IF {#sum-if} + +### Сигнатура + +```yql +SUM_IF(Unsigned?, Bool?)->Uint64? +SUM_IF(Signed?, Bool?)->Int64? +SUM_IF(Interval?, Bool?)->Interval? + +AVG_IF(Double?, Bool?)->Double? +``` + +Сумма или арифметическое среднее, но только для строк, удовлетворяющих условию, переданному вторым аргументом. + +Таким образом, `SUM_IF(value, condition)` является чуть более короткой записью для `SUM(IF(condition, value))`, аналогично для `AVG`. Расширение типа данных аргумента работает так же аналогично одноименным функциям без суффикса. + +### Примеры + +```yql +SELECT + SUM_IF(value, value % 2 == 1) AS odd_sum, + AVG_IF(value, value % 2 == 1) AS odd_avg, +FROM my_table; +``` + +При использовании [фабрики агрегационной функции](basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](#aggregate-by) передается `Tuple` из значения и предиката. + +```yql +$sum_if_factory = AggregationFactory("SUM_IF"); +$avg_if_factory = AggregationFactory("AVG_IF"); + +SELECT + AGGREGATE_BY(AsTuple(value, value % 2 == 1), $sum_if_factory) AS odd_sum, + AGGREGATE_BY(AsTuple(value, value % 2 == 1), $avg_if_factory) AS odd_avg +FROM my_table; +``` + +## SOME {#some} + +### Сигнатура + +```yql +SOME(T?)->T? +SOME(T)->T? +``` + +Получить значение указанного в качестве аргумента выражения для одной из строк таблицы. Не дает никаких гарантий о том, какая именно строка будет использована. + +Из-за отсутствия гарантий `SOME` вычислительно дешевле, чем часто использующиеся в подобных ситуациях [MIN и MAX](#min-max). + +### Примеры + +```yql +SELECT + SOME(value) +FROM my_table; +``` + +{% note alert %} + +При вызове агрегатной функции `SOME` несколько раз **не** гарантируется, что все значения результатов будут взяты с одной строки исходной таблицы. Для получения данной гарантии, нужно запаковать значения в какой-либо из контейнеров и передавать в `SOME` уже его. Например, для структуры это можно сделать с помощью [AsStruct](basic.md#asstruct) + +{% endnote %} + +## CountDistinctEstimate, HyperLogLog и HLL {#countdistinctestimate} + +### Сигнатура + +```yql +CountDistinctEstimate(T)->Uint64? +HyperLogLog(T)->Uint64? +HLL(T)->Uint64? +``` + +Примерная оценка числа уникальных значений по алгоритму [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog). Логически делает то же самое, что и [COUNT(DISTINCT ...)](#count), но работает значительно быстрее ценой некоторой погрешности. + +Аргументы: + +1. Значение для оценки; +2. Точность (от 4 до 18 включительно, по умолчанию 14). + +Выбор точности позволяет разменивать дополнительное потребление вычислительных ресурсов и оперативной памяти на уменьшение погрешности. + +На данный момент все три функции являются алиасами, но в будущем `CountDistinctEstimate` может начать использовать другой алгоритм. + +### Примеры + +```yql +SELECT + CountDistinctEstimate(my_column) +FROM my_table; +``` + +```yql +SELECT + HyperLogLog(my_column, 4) +FROM my_table; +``` + + + +## AGGREGATE_LIST {#agg-list} + +### Сигнатура + +```yql +AGGREGATE_LIST(T? [, limit:Uint64])->List +AGGREGATE_LIST(T [, limit:Uint64])->List +AGGREGATE_LIST_DISTINCT(T? [, limit:Uint64])->List +AGGREGATE_LIST_DISTINCT(T [, limit:Uint64])->List +``` + +Получить все значения столбца в виде списка. В сочетании с `DISTINCT` возвращает только уникальные значения. Опциональный второй параметр задает максимальное количество получаемых значений. Значение 0 равносильно отсутствию лимита. + +Если заранее известно, что уникальных значений не много, то лучше воспользоваться агрегатной функцией `AGGREGATE_LIST_DISTINCT`, которая строит тот же результат в памяти (которой при большом числе уникальных значений может не хватить). + +Порядок элементов в результирующем списке зависит от реализации и снаружи не задается. Чтобы получить упорядоченный список, необходимо отсортировать результат, например с помощью [ListSort](list.md#listsort). + +Чтобы получить список нескольких значений с одной строки, важно *НЕ* использовать функцию `AGGREGATE_LIST` несколько раз, а сложить все нужные значения в контейнер, например через [AsList](basic.md#aslist) или [AsTuple](basic.md#astuple) и передать этот контейнер в один вызов `AGGREGATE_LIST`. + +Например, можно использовать в сочетании с `DISTINCT` и функцией [String::JoinFromList](../udf/list/string.md) (аналог `','.join(list)` из Python) для распечатки в строку всех значений, которые встретились в столбце после применения [GROUP BY](../syntax/group_by.md). + +### Примеры + +```yql +SELECT + AGGREGATE_LIST( region ), + AGGREGATE_LIST( region, 5 ), + AGGREGATE_LIST( DISTINCT region ), + AGGREGATE_LIST_DISTINCT( region ), + AGGREGATE_LIST_DISTINCT( region, 5 ) +FROM users +``` + +```yql +-- Аналог GROUP_CONCAT из MySQL +SELECT + String::JoinFromList(CAST(AGGREGATE_LIST(region, 2) AS List), ",") +FROM users +``` + +Существует также короткая форма записи этих функций - `AGG_LIST` и `AGG_LIST_DISTINCT`. + +{% note alert %} + +Выполняется **НЕ** ленивым образом, поэтому при использовании нужно быть уверенным, что список получится разумных размеров, примерно в пределах тысячи элементов. Чтобы подстраховаться, можно воспользоваться вторым опциональным числовым аргументом, который включает ограничение на число элементов в списке. + +{% endnote %} + + +## MAX_BY и MIN_BY {#max-min-by} + +### Сигнатура + +```yql +MAX_BY(T1?, T2)->T1? +MAX_BY(T1, T2)->T1? +MAX_BY(T1, T2, limit:Uint64)->List? + +MIN_BY(T1?, T2)->T1? +MIN_BY(T1, T2)->T1? +MIN_BY(T1, T2, limit:Uint64)->List? +``` + +Вернуть значение первого аргумента для строки таблицы, в которой второй аргумент оказался минимальным/максимальным. + +Опционально можно указать третий аргумент N, который влияет на поведение в случае, если в таблице есть несколько строк с одинаковым минимальным или максимальным значением: + +* Если N не указано — будет возвращено значение одной из строк, а остальные отбрасываются. +* Если N указано — будет возвращен список со всеми значениями, но не более N, все значения после достижения указанного числа отбрасываются. + +При выборе значения N рекомендуется не превышать порядка сотен или тысяч, чтобы не возникало проблем с ограниченной доступной памятью на кластерах {{ backend_name }}. + +Если для задачи обязательно нужны все значения, и их количество может измеряться десятками тысяч и больше, то вместо данных агрегационных функций следует использовать `JOIN` исходной таблицы с подзапросом, где по ней же сделан `GROUP BY + MIN/MAX` на интересующих вас колонках. + +{% note warning %} + +Если второй аргумент всегда `NULL`, то результатом агрегации будет `NULL`. + +{% endnote %} + +При использовании [фабрики агрегационной функции](basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](#aggregate-by) передается `Tuple` из значения и ключа. + +### Примеры + +```yql +SELECT + MIN_BY(value, LENGTH(value)), + MAX_BY(value, key, 100) +FROM my_table; +``` + +```yql +$min_by_factory = AggregationFactory("MIN_BY"); +$max_by_factory = AggregationFactory("MAX_BY", 100); + +SELECT + AGGREGATE_BY(AsTuple(value, LENGTH(value)), $min_by_factory), + AGGREGATE_BY(AsTuple(value, key), $max_by_factory) +FROM my_table; +``` + + +## TOP и BOTTOM {#top-bottom} + +### Сигнатура + +```yql +TOP(T?, limit:Uint32)->List +TOP(T, limit:Uint32)->List +BOTTOM(T?, limit:Uint32)->List +BOTTOM(T, limit:Uint32)->List +``` + +Вернуть список максимальных/минимальных значений выражения. Первый аргумент - выражение, второй - ограничение на количество элементов. + +### Примеры + +```yql +SELECT + TOP(key, 3), + BOTTOM(value, 3) +FROM my_table; +``` + +```yql +$top_factory = AggregationFactory("TOP", 3); +$bottom_factory = AggregationFactory("BOTTOM", 3); + +SELECT + AGGREGATE_BY(key, $top_factory), + AGGREGATE_BY(value, $bottom_factory) +FROM my_table; +``` + +## TOP_BY и BOTTOM_BY {#top-bottom-by} + +### Сигнатура + +```yql +TOP_BY(T1, T2, limit:Uint32)->List +BOTTOM_BY(T1, T2, limit:Uint32)->List +``` + +Вернуть список значений первого аргумента для строк с максимальными/минимальными значениями второго аргумента. Третий аргумент - ограничение на количество элементов в списке. + +При использовании [фабрики агрегационной функции](basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](#aggregate-by) передается `Tuple` из значения и ключа. Ограничение на количество элементов в этом случае передаётся вторым аргументом при создании фабрики. + +### Примеры + +```yql +SELECT + TOP_BY(value, LENGTH(value), 3), + BOTTOM_BY(value, key, 3) +FROM my_table; +``` + +```yql +$top_by_factory = AggregationFactory("TOP_BY", 3); +$bottom_by_factory = AggregationFactory("BOTTOM_BY", 3); + +SELECT + AGGREGATE_BY(AsTuple(value, LENGTH(value)), $top_by_factory), + AGGREGATE_BY(AsTuple(value, key), $bottom_by_factory) +FROM my_table; +``` + + +## TOPFREQ и MODE {#topfreq-mode} + +### Сигнатура + +```yql +TOPFREQ(T [, num:Uint32 [, bufSize:Uint32]])->List> +MODE(T [, num:Uint32 [, bufSize:Uint32]])->List> +``` + +Получение **приближенного** списка самых часто встречающихся значений колонки с оценкой их числа. Возвращают список структур с двумя полями: + +* `Value`— найденное часто встречающееся значение; +* `Frequency` — оценка числа упоминаний в таблице. + +Обязательный аргумент: само значение. + +Опциональные аргументы: + +1. Для `TOPFREQ` — желаемое число элементов в результате. `MODE` является алиасом к `TOPFREQ` с 1 в этом аргументе. У `TOPFREQ` по умолчанию тоже 1. +2. Число элементов в используемом буфере, что позволяет разменивать потребление памяти на точность. По умолчанию 100. + +### Примеры + +```yql +SELECT + MODE(my_column), + TOPFREQ(my_column, 5, 1000) +FROM my_table; +``` + + +## STDDEV и VARIANCE {#stddev-variance} + +### Сигнатура + +```yql +STDDEV(Double?)->Double? +STDDEV_POPULATION(Double?)->Double? +POPULATION_STDDEV(Double?)->Double? +STDDEV_SAMPLE(Double?)->Double? +STDDEVSAMP(Double?)->Double? + +VARIANCE(Double?)->Double? +VARIANCE_POPULATION(Double?)->Double? +POPULATION_VARIANCE(Double?)->Double? +VARPOP(Double?)->Double? +VARIANCE_SAMPLE(Double?)->Double? +``` + +Стандартное отклонение и дисперсия по колонке. Используется [однопроходной параллельный алгоритм](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm), результат которого может отличаться от полученного более распространенными методами, требующими двух проходов по данным. + +По умолчанию вычисляются выборочная дисперсия и стандартное отклонение. Доступны несколько способов записи: + +* с суффиксом/префиксом `POPULATION`, например: `VARIANCE_POPULATION`, `POPULATION_VARIANCE` — вычисляет дисперсию/стандартное отклонение для генеральной совокупности; +* с суффиксом `SAMPLE` или без суффикса, например `VARIANCE_SAMPLE`, `SAMPLE_VARIANCE`, `VARIANCE` — вычисляет выборочную дисперсию и стандартное отклонение. + +Также определено несколько сокращенных алиасов, например `VARPOP` или `STDDEVSAMP`. + +Если все переданные значения — `NULL`, возвращает `NULL`. + +### Примеры + +```yql +SELECT + STDDEV(numeric_column), + VARIANCE(numeric_column) +FROM my_table; +``` + + +## CORRELATION и COVARIANCE {#correlation-covariance} + +### Сигнатура + +```yql +CORRELATION(Double?, Double?)->Double? +COVARIANCE(Double?, Double?)->Double? +COVARIANCE_SAMPLE(Double?, Double?)->Double? +COVARIANCE_POPULATION(Double?, Double?)->Double? +``` + +Корреляция и ковариация двух колонок. + +Также доступны сокращенные версии `CORR` или `COVAR`, а для ковариации - версии с суффиксом `SAMPLE` / `POPULATION` по аналогии с описанной выше [VARIANCE](#stddev-variance). + +В отличие от большинства других агрегатных функций не пропускают `NULL`, а считают его за 0. + +При использовании [фабрики агрегационной функции](basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](#aggregate-by) передается `Tuple` из двух значений. + +### Примеры + +```yql +SELECT + CORRELATION(numeric_column, another_numeric_column), + COVARIANCE(numeric_column, another_numeric_column) +FROM my_table; +``` + +```yql +$corr_factory = AggregationFactory("CORRELATION"); + +SELECT + AGGREGATE_BY(AsTuple(numeric_column, another_numeric_column), $corr_factory) +FROM my_table; +``` + +## PERCENTILE и MEDIAN {#percentile-median} + +### Сигнатура + +```yql +PERCENTILE(T, Double)->T +PERCENTILE(T, Tuple)->Tuple +PERCENTILE(T, Struct)->Struct +PERCENTILE(T, List)->List + +MEDIAN(T, [ Double ])->T +MEDIAN(T, [ Tuple ])->Tuple +MEDIAN(T, [ Struct ])->Struct +MEDIAN(T, [ List ])->List +``` + +Подсчет процентилей по амортизированной версии алгоритма [TDigest](https://github.com/tdunning/t-digest). `MEDIAN(x)` без второго аргумента — алиас для `PERCENTILE(x, 0.5)`. +`MEDIAN` с двумя аргументами полностью эквивалентен `PERCENTILE`. + +В качестве первого аргумента `PERCENTILE`/`MEDIAN` принимает выражение типа `T`. В качестве типа `T` на данный момент поддерживаются типы `Interval` и `Double` (а также типы которые допускают неявное приведение к ним - например целочисленные типы). + +В качестве второго аргумента можно использовать либо один `Double` (значение перцентиля), либо сразу несколько значений перцентиля в виде `Tuple`/`Struct`/`List`. + +Значения прецентиля должны лежать в диапазоне от 0.0 до 1.0 включительно. + +### Примеры + +```yql +SELECT + MEDIAN(numeric_column), + PERCENTILE(numeric_column, 0.99), + PERCENTILE(CAST(string_column as Double), (0.01, 0.5, 0.99)), -- подсчет сразу трех перцентилей + PERCENTILE(numeric_column, AsStruct(0.01 as p01, 0.5 as median, 0.99 as p99)), -- используя структуру, значениям перцентиля можно дать удобные имена + PERCENTILE(numeric_column, ListFromRange(0.00, 1.05, 0.05)), -- подсчет множества перцентилей (от 0.0 до 1.0 включительно с шагом 0.05) +FROM my_table; +``` + + + +## HISTOGRAM {#histogram} + +### Сигнатура + +```yql +HISTOGRAM(Double?)->HistogramStruct? +HISTOGRAM(Double?, weight:Double)->HistogramStruct? +HISTOGRAM(Double?, intervals:Uint32)->HistogramStruct? +HISTOGRAM(Double?, weight:Double, intervals:Uint32)->HistogramStruct? +``` + +В описании сигнатур под HistogramStruct подразумевается результат работы агрегатной функции, который является структурой определенного вида. + +Построение примерной гистограммы по числовому выражению с автоматическим выбором корзин. + +[Вспомогательные функции](../udf/list/histogram.md) + +### Базовые настройки + +Ограничение на число корзин можно задать с помощью опционального аргумента, значение по умолчанию — 100. Следует иметь в виду, что дополнительная точность стоит дополнительных вычислительных ресурсов и может негативно сказываться на времени выполнения запроса, а в экстремальных случаях — и на его успешности. + +### Поддержка весов + +Имеется возможность указать «вес» для каждого значения, участвующего в построении гистограммы. Для этого вторым аргументом в агрегатную функцию нужно передать выражение для вычисления веса. По умолчанию всегда используется вес `1.0`. Если используются нестандартные веса, ограничение на число корзин можно задать третьим аргументом. + +В случае, если передано два аргумента, смысл второго аргумента определяется по его типу (целочисленный литерал — ограничение на число корзин, в противном случае — вес). + +{% if tech %} + +### Алгоритмы + +* [Оригинальный whitepaper](http://jmlr.org/papers/volume11/ben-haim10a/ben-haim10a.pdf); + +Доступны разные модификации алгоритма: + +```yql +AdaptiveDistanceHistogram +AdaptiveWeightHistogram +AdaptiveWardHistogram +BlockWeightHistogram +BlockWardHistogram +``` + +По умолчанию `HISTOGRAM` является синонимом к `AdaptiveWardHistogram`. Обе функции эквивалентны и взаимозаменимы во всех контекстах. + +Алгоритмы Distance, Weight и Ward отличаются формулами объединения двух точек в одну: + +```c++ +TWeightedValue CalcDistanceQuality(const TWeightedValue& left, const TWeightedValue& right) { + return TWeightedValue(right.first - left.first, left.first); +} + +TWeightedValue CalcWeightQuality(const TWeightedValue& left, const TWeightedValue& right) { + return TWeightedValue(right.second + left.second, left.first); +} + +TWeightedValue CalcWardQuality(const TWeightedValue& left, const TWeightedValue& right) { + const double N1 = left.second; + const double N2 = right.second; + const double mu1 = left.first; + const double mu2 = right.first; + return TWeightedValue(N1 * N2 / (N1 + N2) * (mu1 - mu2) * (mu1 - mu2), left.first); +} +``` + +Чем отличается Adaptive и Block: + +{% block info %} + +Contrary to adaptive histogram, block histogram doesn't rebuild bins after the addition of each point. Instead, it accumulates points and in case the amount of points overflows specified limits, it shrinks all the points at once to produce histogram. Indeed, there exist two limits and two shrinkage operations: + +1. FastGreedyShrink is fast but coarse. It is used to shrink from upper limit to intermediate limit (override FastGreedyShrink to set specific behaviour). +2. SlowShrink is slow, but produces finer histogram. It shrinks from the intermediate limit to the actual number of bins in a manner similar to that in adaptive histogram (set CalcQuality in constuctor) + +While FastGreedyShrink is used most of the time, SlowShrink is mostly used for histogram finalization + +{% endblock %} + +{% endif %} + +### Если нужна точная гистограмма + +1. Можно воспользоваться описанными ниже агрегатными функциями с фиксированными сетками корзин: [LinearHistogram](#linearhistogram) или [LogarithmicHistogram](#linearhistogram). +2. Можно самостоятельно вычислить номер корзины для каждой строки и сделать по нему [GROUP BY](../syntax/group_by.md). + +При использовании [фабрики агрегационной функции](basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](#aggregate-by) передается `Tuple` из значения и веса. + +### Примеры + +```yql +SELECT + HISTOGRAM(numeric_column) +FROM my_table; +``` + +```yql +SELECT + Histogram::Print( + HISTOGRAM(numeric_column, 10), + 50 + ) +FROM my_table; +``` + +```yql +$hist_factory = AggregationFactory("HISTOGRAM"); + +SELECT + AGGREGATE_BY(AsTuple(numeric_column, 1.0), $hist_factory) +FROM my_table; +``` + +## LinearHistogram, LogarithmicHistogram и LogHistogram {#linearhistogram} + +Построение гистограммы по явно указанной фиксированной шкале корзин. + +### Сигнатура + +```yql +LinearHistogram(Double?)->HistogramStruct? +LinearHistogram(Double? [, binSize:Double [, min:Double [, max:Double]]])->HistogramStruct? + +LogarithmicHistogram(Double?)->HistogramStruct? +LogarithmicHistogram(Double? [, logBase:Double [, min:Double [, max:Double]]])->HistogramStruct? +LogHistogram(Double?)->HistogramStruct? +LogHistogram(Double? [, logBase:Double [, min:Double [, max:Double]]])->HistogramStruct? +``` + +Аргументы: + +1. Выражение, по значению которого строится гистограмма. Все последующие — опциональны. +2. Расстояние между корзинами для `LinearHistogram` или основание логарифма для `LogarithmicHistogram` / `LogHistogram` (это алиасы). В обоих случаях значение по умолчанию — 10. +3. Минимальное значение. По умолчанию минус бесконечность. +4. Максимальное значение. По умолчанию плюс бесконечность. + +Формат результата полностью аналогичен [адаптивным гистограммам](#histogram), что позволяет использовать тот же [набор вспомогательных функций](../udf/list/histogram.md). + +Если разброс входных значений неконтролируемо велик, рекомендуется указывать минимальное и максимальное значение для предотвращения потенциальных падений из-за высокого потребления памяти. + +### Примеры + +```yql +SELECT + LogarithmicHistogram(numeric_column, 2) +FROM my_table; +``` + +## CDF (cumulative distribution function) {#histogramcdf} + +К каждому виду функции Histogram можно приписать суффикс CDF для построения кумулятивной функции распределения. Конструкции + +```yql +SELECT + Histogram::ToCumulativeDistributionFunction(Histogram::Normalize(<вид_функции>Histogram(numeric_column))) +FROM my_table; +``` + +и + +```yql +SELECT + <вид_функции>HistogramCDF(numeric_column) +FROM my_table; +``` + +полностью эквивалентны. + +## BOOL_AND, BOOL_OR и BOOL_XOR {#bool-and-or-xor} + +### Сигнатура + +```yql +BOOL_AND(Bool?)->Bool? +BOOL_OR(Bool?)->Bool? +BOOL_XOR(Bool?)->Bool? +``` + +Применение соответствующей логической операции (`AND`/`OR`/`XOR`) ко всем значениям булевой колонки или выражения. + +В отличие от большинства агрегатных функций, эти функции **не пропускают** `NULL` значение при агрегации и действуют по правилу: + +- `true AND null == null` +- `false OR null == null` + +Для `BOOL_AND`: + +- Для любого количества значений `true` и хотя бы одного `NULL` значения, результатом будет `NULL`. +- В случае хотя бы одного `false` значения, результатом будет `false`, независимо от наличия `NULL`. + +Для `BOOL_OR`: + +- Для любого количества значений `false` и хотя бы одного `NULL` значения, результатом будет `NULL`. +- В случае хотя бы одного `true` значения, результатом будет `true`, независимо от наличия `NULL`. + +Для `BOOL_XOR`: + +- В случае хотя бы одного `NULL` значения, результатом будет `NULL`. + +Примеры описанного поведения приведены ниже. + +Для агрегации с пропуском `NULL`-ов можно использовать функции `MIN`/`MAX` или `BIT_AND`/`BIT_OR`/`BIT_XOR`. + +### Примеры + +```yql +$data = [ + <|nonNull: true, nonFalse: true, nonTrue: NULL, anyVal: true|>, + <|nonNull: false, nonFalse: NULL, nonTrue: NULL, anyVal: NULL|>, + <|nonNull: false, nonFalse: NULL, nonTrue: false, anyVal: false|>, +]; + +SELECT + BOOL_AND(nonNull) as nonNullAnd, -- false + BOOL_AND(nonFalse) as nonFalseAnd, -- NULL + BOOL_AND(nonTrue) as nonTrueAnd, -- false + BOOL_AND(anyVal) as anyAnd, -- false + BOOL_OR(nonNull) as nonNullOr, -- true + BOOL_OR(nonFalse) as nonFalseOr, -- true + BOOL_OR(nonTrue) as nonTrueOr, -- NULL + BOOL_OR(anyVal) as anyOr, -- true + BOOL_XOR(nonNull) as nonNullXor, -- true + BOOL_XOR(nonFalse) as nonFalseXor, -- NULL + BOOL_XOR(nonTrue) as nonTrueXor, -- NULL + BOOL_XOR(anyVal) as anyXor, -- NULL +FROM AS_TABLE($data); +``` + +## BIT_AND, BIT_OR и BIT_XOR {#bit-and-or-xor} + +Применение соответствующей битовой операции ко всем значениям числовой колонки или выражения. + +### Примеры + +```yql +SELECT + BIT_XOR(unsigned_numeric_value) +FROM my_table; +``` + + +{% if feature_window_functions %} + + ## SessionStart {#session-start} + +Без аргументов. Допускается только при наличии [SessionWindow](../syntax/group_by.md#session-window) в +[GROUP BY](../syntax/group_by.md) / [PARTITION BY](../syntax/window.md#partition). +Возвращает значение ключевой колонки `SessionWindow`. В случае `SessionWindow` с двумя аргументами – минимальное значение первого аргумента внутри группы/раздела. +В случае раширенного варианта `SessionWindoow` – значение второго элемента кортежа, возвращаемого ``, при котором первый элемент кортежа равен `True`. + + +{% endif %} + + +## AGGREGATE_BY и MULTI_AGGREGATE_BY {#aggregate-by} + +{% if backend_name == "YDB" and oss == true %} + +{% include [not_allow_for_olap_note](../../../_includes/not_allow_for_olap_note.md) %} + +{% endif %} + +Применение [фабрики агрегационной функции](basic.md#aggregationfactory) ко всем значениям колонки или выражения. Функция `MULTI_AGGREGATE_BY` требует, чтобы в значении колонки или выражения была структура, кортеж или список, и применяет фабрику поэлементно, размещая результат в контейнере той же формы. Если в разных значениях колонки или выражения содержатся списки разной длины, результирующий список будет иметь наименьшую из длин этих списков. + +1. Колонка, `DISTINCT` колонка или выражение; +2. Фабрика. + +### Примеры + +```yql +$count_factory = AggregationFactory("COUNT"); + +SELECT + AGGREGATE_BY(DISTINCT column, $count_factory) as uniq_count +FROM my_table; + +SELECT + MULTI_AGGREGATE_BY(nums, AggregationFactory("count")) as count, + MULTI_AGGREGATE_BY(nums, AggregationFactory("min")) as min, + MULTI_AGGREGATE_BY(nums, AggregationFactory("max")) as max, + MULTI_AGGREGATE_BY(nums, AggregationFactory("avg")) as avg, + MULTI_AGGREGATE_BY(nums, AggregationFactory("percentile", 0.9)) as p90 +FROM my_table; +``` + diff --git a/ydb/docs/ru/core/yql/reference/builtins/basic.md b/ydb/docs/ru/core/yql/reference/builtins/basic.md new file mode 100644 index 000000000000..943413c2d1ae --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/builtins/basic.md @@ -0,0 +1,1691 @@ + +# Базовые встроенные функции + +Ниже описаны функции общего назначения, а для специализированных функций есть отдельные статьи: [агрегатные](aggregation.md){% if feature_window_functions %}, [оконные](window.md){% endif %}, а также для работы со [списками](list.md), [словарями](dict.md), [структурами](struct.md), [типами данных](types.md){% if feature_codegen %} и [генерацией кода](codegen.md){% endif %}. + + +## COALESCE {#coalesce} + +Перебирает аргументы слева направо и возвращает первый найденный непустой аргумент. Чтобы результат получился гарантированно непустым (не [optional типа](../types/optional.md)), самый правый аргумент должен быть такого типа (зачастую используют литерал). При одном аргументе возвращает его без изменений. + +### Сигнатура + +```yql +COALESCE(T?, ..., T)->T +COALESCE(T?, ..., T?)->T? +``` + +Позволяет передавать потенциально пустые значения в функции, которые не умеют обрабатывать их самостоятельно. + +Доступен краткий формат записи в виде оператора `??`. Можно использовать алиас `NVL`. + +### Примеры + +```yql +SELECT COALESCE( + maybe_empty_column, + "it's empty!" +) FROM my_table; +``` + +```yql +SELECT + maybe_empty_column ?? "it's empty!" +FROM my_table; +``` + +```yql +SELECT NVL( + maybe_empty_column, + "it's empty!" +) FROM my_table; +``` + +Все три примера выше эквивалентны. + + +## LENGTH {#length} + +Возвращает длину строки в байтах. Также эта функция доступна под именем `LEN`. + +### Сигнатура + +```yql +LENGTH(T)->Uint32 +LENGTH(T?)->Uint32? +``` + +### Примеры + +```yql +SELECT LENGTH("foo"); +``` + +```yql +SELECT LEN("bar"); +``` + +{% note info %} + +Для вычисления длины строки в unicode символах можно воспользоваться функцией [Unicode::GetLength](../udf/list/unicode.md).

Для получения числа элементов в списке нужно использовать функцию [ListLength](list.md#listlength). + +{% endnote %} + + +## SUBSTRING {#substring} + +Возвращает подстроку. + +### Сигнатура + +```yql +Substring(String[, Uint32? [, Uint32?]])->String +Substring(String?[, Uint32? [, Uint32?]])->String? +``` + +Обязательные аргументы: + +* Исходная строка; +* Позиция — отступ от начала строки в байтах (целое число) или `NULL`, означающий «от начала». + +Опциональные аргументы: + +* Длина подстроки — количество байт, начиная с указанной позиции (целое число, или `NULL` по умолчанию, означающий «до конца исходной строки»). + +Индексация с нуля. Если указанные позиция и длина выходят за пределы строки, возвращает пустую строку. +Если входная строка является опциональной, то таким же является и результат. + +### Примеры + +```yql +SELECT SUBSTRING("abcdefg", 3, 1); -- d +``` + +```yql +SELECT SUBSTRING("abcdefg", 3); -- defg +``` + +```yql +SELECT SUBSTRING("abcdefg", NULL, 3); -- abc +``` + + +## FIND {#find} + +Поиск позиции подстроки в строке. + +### Сигнатура + +```yql +Find(String, String[, Uint32?])->Uint32? +Find(String?, String[, Uint32?])->Uint32? +Find(Utf8, Utf8[, Uint32?])->Uint32? +Find(Utf8?, Utf8[, Uint32?])->Uint32? +``` + +Обязательные аргументы: + +* Исходная строка; +* Искомая подстрока. + +Опциональные аргументы: + +* Позиция — в байтах, с которой начинать поиск (целое число, или `NULL` по умолчанию, означающий «от начала исходной строки»). + +Возвращает первую найденную позицию подстроки или `NULL`, означающий что искомая подстрока с указанной позиции не найдена. + +### Примеры + +```yql +SELECT FIND("abcdefg_abcdefg", "abc"); -- 0 +``` + +```yql +SELECT FIND("abcdefg_abcdefg", "abc", 1); -- 8 +``` + +```yql +SELECT FIND("abcdefg_abcdefg", "abc", 9); -- null +``` + +## RFIND {#rfind} + +Обратный поиск позиции подстроки в строке, от конца к началу. + +### Сигнатура + +```yql +RFind(String, String[, Uint32?])->Uint32? +RFind(String?, String[, Uint32?])->Uint32? +RFind(Utf8, Utf8[, Uint32?])->Uint32? +RFind(Utf8?, Utf8[, Uint32?])->Uint32? +``` + +Обязательные аргументы: + +* Исходная строка; +* Искомая подстрока. + +Опциональные аргументы: + +* Позиция — в байтах, с которой начинать поиск (целое число, или `NULL` по умолчанию, означающий «от конца исходной строки»). + +Возвращает первую найденную позицию подстроки или `NULL`, означающий, что искомая подстрока с указанной позиции не найдена. + +### Примеры + +```yql +SELECT RFIND("abcdefg_abcdefg", "bcd"); -- 9 +``` + +```yql +SELECT RFIND("abcdefg_abcdefg", "bcd", 8); -- 1 +``` + +```yql +SELECT RFIND("abcdefg_abcdefg", "bcd", 0); -- null +``` + + +## StartsWith, EndsWith {#starts_ends_with} + +Проверка наличия префикса или суффикса в строке. + +### Сигнатуры + +```yql +StartsWith(T str, U prefix)->Bool[?] + +EndsWith(T str, U suffix)->Bool[?] +``` + +Обязательные аргументы: + +* Исходная строка; +* Искомая подстрока. + +Аргументы должны иметь тип `String`/`Utf8` (или опциональный `String`/`Utf8`) либо строковый PostgreSQL тип (`PgText`/`PgBytea`/`PgVarchar`). +Результатом функции является опциональный Bool, за исключением случая, когда оба аргумента неопциональные – в этом случае возвращается Bool. + +### Примеры + +```yql +SELECT StartsWith("abc_efg", "abc") AND EndsWith("abc_efg", "efg"); -- true +``` + +```yql +SELECT StartsWith("abc_efg", "efg") OR EndsWith("abc_efg", "abc"); -- false +``` + +```yql +SELECT StartsWith("abcd", NULL); -- null +``` + +```yql +SELECT EndsWith(NULL, Utf8("")); -- null +``` + +```yql +SELECT StartsWith("abc_efg"u, "abc"p) AND EndsWith("abc_efg", "efg"pv); -- true +``` + + +## IF {#if} + +Проверяет условие `IF(condition_expression, then_expression, else_expression)`. + +Является упрощенной альтернативой для [CASE WHEN ... THEN ... ELSE ... END](../syntax/expressions.md#case). + +### Сигнатура + +```yql +IF(Bool, T, T)->T +IF(Bool, T)->T? +``` + +Аргумент `else_expression` можно не указывать. В этом случае, если условие ложно (`condition_expression` вернул `false`), будет возвращено пустое значение с типом, соответствующим `then_expression` и допускающим значение `NULL`. Таким образом, у результата получится [optional тип данных](../types/optional.md). + +### Примеры + +```yql +SELECT + IF(foo > 0, bar, baz) AS bar_or_baz, + IF(foo > 0, foo) AS only_positive_foo +FROM my_table; +``` + + +## NANVL {#nanvl} + +Заменяет значения `NaN` (not a number) в выражениях типа `Float`, `Double` или [Optional](../types/optional.md). + +### Сигнатура + +```yql +NANVL(Float, Float)->Float +NANVL(Double, Double)->Double +``` + +Аргументы: + +1. Выражение, в котором нужно произвести замену. +2. Значение, на которое нужно заменить `NaN`. + +Если один из агрументов `Double`, то в выдаче `Double`, иначе `Float`. Если один из агрументов `Optional`, то и в выдаче `Optional`. + +### Примеры + +```yql +SELECT + NANVL(double_column, 0.0) +FROM my_table; +``` + + +## Random... {#random} + +Генерирует псевдослучайное число: + +* `Random()` — число с плавающей точкой (Double) от 0 до 1; +* `RandomNumber()` — целое число из всего диапазона Uint64; +* `RandomUuid()` — [Uuid version 4](https://tools.ietf.org/html/rfc4122#section-4.4). + +### Сигнатуры + +```yql +Random(T1[, T2, ...])->Double +RandomNumber(T1[, T2, ...])->Uint64 +RandomUuid(T1[, T2, ...])->Uuid +``` + +При генерации случайных чисел аргументы не используются и нужны исключительно для управления моментом вызова. В каждый момент вызова возвращается новое случайное число. Поэтому: + +{% if ydb_non_deterministic_functions %} + +* Повторный вызов Random в рамках **одного запроса** при идентичном наборе аргументов не гарантирует получения одинаковых наборов случайных чисел. Значения будут равны, если вызовы Random попадут в одну фазу исполнения. + +{% else %} + +* Повторный вызов Random в рамках **одного запроса** при идентичном наборе аргументов возвращает тот же самый набор случайных чисел. Важно понимать, что речь именно про сами аргументы (текст между круглыми скобками), а не их значения. + +{% endif %} +* Вызовы Random с одним и тем же набором аргументов в **разных запросах** вернут разные наборы случайных чисел. + +{% note warning %} + +Если Random используется в [именованных выражениях](../syntax/expressions.md#named-nodes), то его однократное вычисление не гарантируется. В зависимости от оптимизаторов и среды исполнения он может посчитаться как один раз, так и многократно. Для гарантированного однократного подсчета необходимо в этом случае материализовать именованное выражение в таблицу. + +{% endnote %} + +Сценарии использования: + +* `SELECT RANDOM(1);` — получить одно случайное значение на весь запрос и несколько раз его использовать (чтобы получить несколько, можно передать разные константы любого типа); +* `SELECT RANDOM(1) FROM table;` — одно и то же случайное число на каждую строку таблицы; +* `SELECT RANDOM(1), RANDOM(2) FROM table;` — по два случайных числа на каждую строку таблицы, все числа в каждой из колонок одинаковые; +* `SELECT RANDOM(some_column) FROM table;` — разные случайные числа на каждую строку таблицы; +* `SELECT RANDOM(some_column), RANDOM(some_column) FROM table;` — разные случайные числа на каждую строку таблицы, но в рамках одной строки — два одинаковых числа; +* `SELECT RANDOM(some_column), RANDOM(some_column + 1) FROM table;` или `SELECT RANDOM(some_column), RANDOM(other_column) FROM table;` — две колонки, и все с разными числами. + +### Примеры + +```yql +SELECT + Random(key) -- [0, 1) +FROM my_table; +``` + +```yql +SELECT + RandomNumber(key) -- [0, Max) +FROM my_table; +``` + +```yql +SELECT + RandomUuid(key) -- Uuid version 4 +FROM my_table; +``` + +```yql +SELECT + RANDOM(column) AS rand1, + RANDOM(column) AS rand2, -- same as rand1 + RANDOM(column, 1) AS randAnd1, -- different from rand1/2 + RANDOM(column, 2) AS randAnd2 -- different from randAnd1 +FROM my_table; +``` + + +## Udf {#udf} + +Строит `Callable` по заданному названию функции и опциональным `external user types`, `RunConfig` и `TypeConfig`. + +* `Udf(Foo::Bar)` — Функция `Foo::Bar` без дополнительных параметров. +* `Udf(Foo::Bar)(1, 2, 'abc')` — Вызов udf `Foo::Bar`. +* `Udf(Foo::Bar, Int32, @@{"device":"AHCI"}@@ as TypeConfig")(1, 2, 'abc')` — Вызов udf `Foo::Bar` с дополнительным типом `Int32` и указанным `TypeConfig`. +* `Udf(Foo::Bar, "1e9+7" as RunConfig")(1, 'extended' As Precision)` — Вызов udf `Foo::Bar` с указанным `RunConfig` и именоваными параметрами. + +### Сигнатуры + +```yql +Udf(Callable[, T1, T2, ..., T_N][, V1 as TypeConfig][,V2 as RunConfig]])->Callable +``` + +Где `T1`, `T2`, и т. д. -- дополнительные (`external`) пользовательские типы. + +### Примеры + +```yql +$IsoParser = Udf(DateTime2::ParseIso8601); +SELECT $IsoParser("2022-01-01"); +``` + +```yql +SELECT Udf(Unicode::IsUtf)("2022-01-01") +``` + +```yql +$config = @@{ + "name":"MessageFoo", + "meta": "..." +}@@; +SELECT Udf(Protobuf::TryParse, $config As TypeConfig)("") +``` + + +## CurrentUtc... {#current-utc} + +`CurrentUtcDate()`, `CurrentUtcDatetime()` и `CurrentUtcTimestamp()` - получение текущей даты и/или времени в UTC. Тип данных результата указан в конце названия функции. + +### Сигнатуры + +```yql +CurrentUtcDate(...)->Date +CurrentUtcDatetime(...)->Datetime +CurrentUtcTimestamp(...)->Timestamp +``` + +Аргументы опциональны и работают по тому же принципу, что и у [RANDOM](#random). + +### Примеры + +```yql +SELECT CurrentUtcDate(); +``` + +```yql +SELECT CurrentUtcTimestamp(TableRow()) FROM my_table; +``` + + +## CurrentTz... {#current-tz} + +`CurrentTzDate()`, `CurrentTzDatetime()` и `CurrentTzTimestamp()` - получение текущей даты и/или времени в указанной в первом аргументе [IANA временной зоне](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Тип данных результата указан в конце названия функции. + +### Сигнатуры + +```yql +CurrentTzDate(String, ...)->TzDate +CurrentTzDatetime(String, ...)->TzDatetime +CurrentTzTimestamp(String, ...)->TzTimestamp +``` + +Последующие аргументы опциональны и работают по тому же принципу, что и у [RANDOM](#random). + +### Примеры + +```yql +SELECT CurrentTzDate("Europe/Moscow"); +``` + +```yql +SELECT CurrentTzTimestamp("Europe/Moscow", TableRow()) FROM my_table; +``` + +## AddTimezone + +Добавление информации о временной зоне к дате/времени, заданных в UTC. При выводе в результате `SELECT` или после `CAST` в `String` будут применены правила временной зоны по вычислению смещения времени. + +### Сигнатура + +```yql +AddTimezone(Date, String)->TzDate +AddTimezone(Date?, String)->TzDate? +AddTimezone(Datetime, String)->TzDatetime +AddTimezone(Datetime?, String)->TzDatetime? +AddTimezone(Timestamp, String)->TzTimestamp +AddTimezone(Timestamp?, String)->TzTimestamp? +``` + +Аргументы: + +1. Дата - тип `Date`/`Datetime`/`Timestamp`; +2. [IANA имя временной зоны](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). + +Тип результата - `TzDate`/`TzDatetime`/`TzTimestamp`, в зависимости от типа данных входа. + +### Примеры + +```yql +SELECT AddTimezone(Datetime("2018-02-01T12:00:00Z"), "Europe/Moscow"); +``` + +## RemoveTimezone + +Удаление информации о временной зоне и перевод в дату/время, заданные в UTC. + +### Сигнатура + +```yql +RemoveTimezone(TzDate)->Date +RemoveTimezone(TzDate?)->Date? +RemoveTimezone(TzDatetime)->Datetime +RemoveTimezone(TzDatetime?)->Datetime? +RemoveTimezone(TzTimestamp)->Timestamp +RemoveTimezone(TzTimestamp?)->Timestamp? +``` + +Аргументы: + +1. Дата - тип `TzDate`/`TzDatetime`/`TzTimestamp`. + +Тип результата - `Date`/`Datetime`/`Timestamp`, в зависимости от типа данных входа. + +### Примеры + +```yql +SELECT RemoveTimezone(TzDatetime("2018-02-01T12:00:00,Europe/Moscow")); +``` + + +## Version {#version} + +`Version()` возвращает строку, описывающую текущую версию узла, обрабатывающего запрос. В некоторых случаях, например, во время постепенного обновлений кластера, она может возвращать разные строки в зависимости от того, какой узел обрабатывает запрос. Функция не принимает никаких аргументов. + +### Примеры + +```yql +SELECT Version(); +``` + + +## MAX_OF, MIN_OF, GREATEST и LEAST {#max-min} + +Возвращает минимальный или максимальный среди N аргументов. Эти функции позволяют не использовать стандартную для SQL конструкцию `CASE WHEN a < b THEN a ELSE b END`, которая была бы особенно громоздкой для N больше двух. + +### Сигнатуры + +```yql +MIN_OF(T[,T,...})->T +MAX_OF(T[,T,...})->T +``` + +Типы аргументов должны быть приводимы друг к другу и могут допускать значение `NULL`. + +`GREATEST` является синонимом к `MAX_OF`, а `LEAST` — к `MIN_OF`. + +### Примеры + +```yql +SELECT MIN_OF(1, 2, 3); +``` + + +## AsTuple, AsStruct, AsList, AsDict, AsSet, AsListStrict, AsDictStrict и AsSetStrict {#as-container} + +Создает контейнеры соответствующих типов. Также доступна [операторная запись](#containerliteral) литералов контейнеров. + +Особенности: + +* Элементы контейнеров передаются через аргументы, таким образом число элементов результирующего контейнера равно числу переданных аргументов, кроме случая, когда повторяются ключи словаря. +* В `AsTuple` и `AsStruct` могут быть вызваны без аргументов, а также аргументы могут иметь разные типы. +* Имена полей в `AsStruct` задаются через `AsStruct(field_value AS field_name)`. +* Для создания списка требуется хотя бы один аргумент, если нужно вывести типы элементов. Для создания пустого списка с заданным типом элементов используется функция [ListCreate](list.md#listcreate). Можно создать пустой список как вызов `AsList()` без аргументов, в этом случае это выражение будет иметь тип `EmptyList`. +* Для создания словаря требуется хотя бы один аргумент, если нужно вывести типы элементов. Для создания пустого словаря с заданным типом элементов используется функция [DictCreate](dict.md#dictcreate). Можно создать пустой словарь как вызов `AsDict()` без аргументов, в этом случае это выражение будет иметь тип `EmptyDict`. +* Для создания множества требуется хотя бы один аргумент, если нужно вывести типы элементов. Для создания пустого множества с заданным типом элементов используется функция [SetCreate](dict.md#setcreate). Можно создать пустое множество как вызов `AsSet()` без аргументов, в этом случае это выражение будет иметь тип `EmptyDict`. +* `AsList` выводит общий тип элементов списка. При несовместимых типах генерируется ошибка типизации. +* `AsDict` выводит раздельно общие типы ключей и значений. При несовместимых типах генерируется ошибка типизации. +* `AsSet` выводит общие типы ключей. При несовместимых типах генерируется ошибка типизации. +* `AsListStrict`, `AsDictStrict`, `AsSetStrict` требуют одинакового типа для аргументов. +* В `AsDict` и `AsDictStrict` в качестве аргументов ожидаются `Tuple` из двух элементов: ключ и значение, соответственно. Если ключи повторяются, в словаре останется только значение для первого ключа. +* В `AsSet` и `AsSetStrict` в качестве аргументов ожидаются ключи. + +### Примеры + +```yql +SELECT + AsTuple(1, 2, "3") AS `tuple`, + AsStruct( + 1 AS a, + 2 AS b, + "3" AS c + ) AS `struct`, + AsList(1, 2, 3) AS `list`, + AsDict( + AsTuple("a", 1), + AsTuple("b", 2), + AsTuple("c", 3) + ) AS `dict`, + AsSet(1, 2, 3) AS `set` +``` + + +## Литералы контейнеров {#containerliteral} + +Для некоторых контейнеров возможна операторная форма записи их литеральных значений: + +* Кортеж — `(value1, value2...)`; +* Структура — `<|name1: value1, name2: value2...|>`; +* Список — `[value1, value2,...]`; +* Словарь — `{key1: value1, key2: value2...}`; +* Множество — `{key1, key2...}`. + +Во всех случаях допускается незначащая хвостовая запятая. Для кортежа с одним элементом эта запятая является обязательной - `(value1,)`. +Для имен полей в литерале структуры допускается использовать выражение, которое можно посчитать в evaluation time, например, строковые литералы, а также идентификаторы (в том числе в backticks). + +Для списка внутри используется функция [AsList](#as-container), словаря - [AsDict](#as-container), множества - [AsSet](#as-container), кортежа - [AsTuple](#as-container), структуры - [AsStruct](#as-container). + +### Примеры + +```yql +$name = "computed " || "member name"; +SELECT + (1, 2, "3") AS `tuple`, + <| + `complex member name`: 2.3, + b: 2, + $name: "3", + "inline " || "computed member name": false + |> AS `struct`, + [1, 2, 3] AS `list`, + { + "a": 1, + "b": 2, + "c": 3, + } AS `dict`, + {1, 2, 3} AS `set` +``` + + +## Variant {#variant} + +`Variant()` создает значение варианта над кортежем или структурой. + +### Сигнатура + +```yql +Variant(T, String, Type>)->Variant<...> +``` + +Аргументы: + +* Значение +* Строка с именем поля или индексом кортежа +* Тип варианта + +### Пример + +```yql +$var_type = Variant; + +SELECT + Variant(6, "foo", $var_type) as Variant1Value, + Variant(false, "bar", $var_type) as Variant2Value; +``` + +## AsVariant {#asvariant} + +`AsVariant()` создает значение [варианта над структурой](../types/containers.md) с одним полем. Это значение может быть неявно преобразовано к любому варианту над структурой, в которой совпадает для этого имени поля тип данных и могут быть дополнительные поля с другими именами. + +### Сигнатура + +```yql +AsVariant(T, String)->Variant +``` + +Аргументы: + +* Значение +* Строка с именем поля + +### Пример + +```yql +SELECT + AsVariant(6, "foo") as VariantValue +``` + +## Visit, VisitOrDefault {#visit} + +Обрабатывает возможные значения варианта, представленного структурой или кортежем, с использованием предоставленных функций-обработчиков для каждого из его полей/элементов. + +### Сигнатура + +```yql +Visit(Variant, K1->R AS key1, K2->R AS key2, ...)->R +Visit(Variant, K1->R, K2->R, ...)->R + +VisitOrDefault(Variant{Flags:AutoMap}, R, [K1->R, [K2->R, ...]])->R +VisitOrDefault(Variant{Flags:AutoMap}, R, [K1->R AS key1, [K2->R AS key2, ...]])->R +``` + +### Аргументы + +* Для варианта над структурой функция принимает сам вариант в качестве позиционного аргумента и по одному именованному аргументу-обработчику для каждого поля этой структуры. +* Для варианта над кортежем функция принимает сам вариант и по одному обработчику на каждый элемент кортежа в качестве позиционных аргументов. +* Модификация `VisitOrDefault` принимает дополнительный позиционный аргумент (на втором месте), представляющий значение по умолчанию, и позволяет не указывать некоторые обработчики. + +### Пример + +```yql +$vartype = Variant; +$handle_num = ($x) -> { return 2 * $x; }; +$handle_flag = ($x) -> { return If($x, 200, 10); }; +$handle_str = ($x) -> { return Unwrap(CAST(LENGTH($x) AS Int32)); }; + +$visitor = ($var) -> { return Visit($var, $handle_num AS num, $handle_flag AS flag, $handle_str AS str); }; +SELECT + $visitor(Variant(5, "num", $vartype)), -- 10 + $visitor(Just(Variant(True, "flag", $vartype))), -- Just(200) + $visitor(Just(Variant("somestr", "str", $vartype))), -- Just(7) + $visitor(Nothing(OptionalType($vartype))), -- Nothing(Optional) + $visitor(NULL) -- NULL +; +``` + +## VariantItem {#variantitem} + +Возвращает значение гомогенного варианта (т.е. содержащего поля/элементы одного типа). + +### Сигнатура + +```yql +VariantItem(Variant{Flags:AutoMap})->K +VariantItem(Variant{Flags:AutoMap})->K +``` + +### Пример + +```yql +$vartype1 = Variant; +SELECT + VariantItem(Variant(7, "num2", $vartype1)), -- 7 + VariantItem(Just(Variant(5, "num1", $vartype1))), -- Just(5) + VariantItem(Nothing(OptionalType($vartype1))), -- Nothing(Optional) + VariantItem(NULL) -- NULL +; +``` + +## Way {#way} + +Возвращает активное поле (активный индекс) варианта поверх структуры (кортежа). + +### Сигнатура + +```yql +Way(Variant{Flags:AutoMap})->Utf8 +Way(Variant{Flags:AutoMap})->Uint32 +``` + +### Пример + +```yql +$vr = Variant(1, "0", Variant); +$vrs = Variant(1, "a", Variant); + + +SELECT Way($vr); -- 0 +SELECT Way($vrs); -- "a" + +``` + +## DynamicVariant {#dynamic_variant} + +Создает экзмепляр гомогенного варианта (т.е. содержащего поля/элементы одного типа), причем индекс или поле варианта можно задавать динамически. При несуществующем индексе или имени поля будет возвращен `NULL`. +Обратная функция - [VariantItem](#variantitem). + +### Сигнатура + +```yql +DynamicVariant(item:T,index:Uint32?,Variant)->Optional> +DynamicVariant(item:T,index:Utf8?,Variant)->Optional> +``` + +### Пример + +```yql +$dt = Int32; +$tvt = Variant<$dt,$dt>; +SELECT ListMap([(10,0u),(20,2u),(30,NULL)],($x)->(DynamicVariant($x.0,$x.1,$tvt))); -- [0: 10,NULL,NULL] + +$dt = Int32; +$svt = Variant; +SELECT ListMap([(10,'x'u),(20,'z'u),(30,NULL)],($x)->(DynamicVariant($x.0,$x.1,$svt))); -- [x: 10,NULL,NULL] + +``` + +## Enum {#enum} + +`Enum()` cоздает значение перечисления. + +### Сигнатура + +```yql +Enum(String, Type>)->Enum<...> +``` + +Аргументы: + +* Строка с именем поля +* Тип перечисления + +### Пример + +```yql +$enum_type = Enum; +SELECT + Enum("Foo", $enum_type) as Enum1Value, + Enum("Bar", $enum_type) as Enum2Value; +``` + +## AsEnum {#asenum} + +`AsEnum()` создает значение [перечисления](../types/containers.md) с одним элементом. Это значение может быть неявно преобразовано к любому перечислению, содержащему такое имя. + +### Сигнатура + +```yql +AsEnum(String)->Enum<'tag'> +``` + +Аргументы: + +* Строка с именем элемента перечисления + +### Пример + +```yql +SELECT + AsEnum("Foo"); +``` + + +## AsTagged, Untag {#as-tagged} + +Оборачивает значение в [Tagged тип данных](../types/special.md) с указанной меткой с сохранением физического типа данных. `Untag` — обратная операция. + +### Сигнатура + +```yql +AsTagged(T, tagName:String)->Tagged +AsTagged(T?, tagName:String)->Tagged? + +Untag(Tagged)->T +Untag(Tagged?)->T? +``` + +Обязательные аргументы: + +1. Значение произвольного типа; +2. Имя метки. + +Возвращает копию значения из первого аргумента с указанной меткой в типе данных. + +Примеры сценариев использования: + +* Возвращение на клиент для отображения в веб-интерфейсе медиа-файлов из base64-encoded строк{% if feature_webui %}. Поддержка меток в веб-UI YQL [описана здесь](../interfaces/web_tagged.md){% endif %}. + +{% if feature_mapreduce %} + +* Защита на границах вызова UDF от передачи некорректных значений; + +{% endif %} + +* Дополнительные уточнения на уровне типов возвращаемых колонок. + + +{% if feature_bulk_tables %} + +## TablePath {#tablepath} + +Доступ к текущему имени таблицы, что бывает востребовано при использовании [CONCAT](../syntax/select/concat.md#concat), [RANGE](../syntax/select/concat.md#range) и других подобных механизмов. + +### Сигнатура + +```yql +TablePath()->String +``` + +Аргументов нет. Возвращает строку с полным путём, либо пустую строку и warning при использовании в неподдерживаемом контексте (например, при работе с подзапросом или диапазоном из 1000+ таблиц). + +{% note info %} + +Функции [TablePath](#tablepath), [TableName](#tablename) и [TableRecordIndex](#tablerecordindex) не работают для временных и анонимных таблиц (возвращают пустую строку или 0 для [TableRecordIndex](#tablerecordindex)). +Данные функции вычисляются в момент [выполнения](../syntax/select/index.md#selectexec) проекции в `SELECT`, и к этому моменту текущая таблица уже может быть временной. +Чтобы избежать такой ситуации, следует поместить вычисление этих функций в подзапрос, как это сделано во втором примере ниже. + +{% endnote %} + +### Примеры + +```yql +SELECT TablePath() FROM CONCAT(table_a, table_b); +``` + +```yql +SELECT key, tpath_ AS path FROM (SELECT a.*, TablePath() AS tpath_ FROM RANGE(`my_folder`) AS a) +WHERE key IN $subquery; +``` + +## TableName {#tablename} + +Получить имя таблицы из пути к таблице. Путь можно получить через функцию [TablePath](#tablepath), или в виде колонки `Path` при использовании табличной функции {% if feature_mapreduce %}[FOLDER](../syntax/select/folder.md){% else %} `FOLDER`{% endif %}. + +### Сигнатура + +```yql +TableName()->String +TableName(String)->String +TableName(String, String)->String +``` + +Необязательные аргументы: + +* путь к таблице, по умолчанию используется `TablePath()` (также см. его ограничения); +* указание системы ("yt"), по правилам которой выделяется имя таблицы. Указание системы нужно только в том случае, если с помощью {% if feature_mapreduce %}[USE](../syntax/use.md){% else %}`USE`{% endif %} не указан текущий кластер. + +### Примеры + +```yql +USE hahn; +SELECT TableName() FROM CONCAT(table_a, table_b); +``` + +```yql +SELECT TableName(Path, "yt") FROM cluster.FOLDER(folder_name); +``` + +## TableRecordIndex {#tablerecordindex} + +Доступ к текущему порядковому номеру строки в исходной физической таблице, **начиная с 1** (зависит от реализации хранения). + +### Сигнатура + +```yql +TableRecordIndex()->Uint64 +``` + +Аргументов нет. При использовании в сочетании с [CONCAT](../syntax/select/concat.md#concat), [RANGE](../syntax/select/concat.md#range) и другими подобными механизмами нумерация начинается заново для каждой таблицы на входе. В случае использования в некорректном контексте возвращает 0. + +### Пример + +```yql +SELECT TableRecordIndex() FROM my_table; +``` + + +{% endif %} + +## TableRow{% if feature_join %}, JoinTableRow{% endif %} {#tablerow} + +Получение всей строки таблицы целиком в виде структуры. Аргументов нет{% if feature_join %}. `JoinTableRow` в случае `JOIN`-ов всегда возвращает структуру с префиксами таблиц{% endif %}. + +### Сигнатура + +```yql +TableRow()->Struct +``` + +### Пример + +```yql +SELECT TableRow() FROM my_table; +``` + + +{% if feature_mapreduce %} + +## FileContent и FilePath {#file-content-path} + +{% if oss != true %} + +Как [консольный](../interfaces/cli.md), так и [веб](../interfaces/web.md)-интерфейсы позволяют «прикладывать» к запросу произвольные именованные файлы. С помощью этих функций можно по имени приложенного файла получить его содержимое или путь в «песочнице» и в дальнейшем использовать в запросе произвольным образом. + +{% endif %} + +### Сигнатуры + +```yql +FilePath(String)->String +FileContent(String)->String +``` + +Аргумент `FileContent` и `FilePath` — строка с алиасом. + +### Примеры + +```yql +SELECT "Content of " + || FilePath("my_file.txt") + || ":\n" + || FileContent("my_file.txt"); +``` +## FolderPath {#folderpath} + +Получение пути до корня директории с несколькими «приложенными» файлами с указанным общим префиксом. + +### Сигнатура + +```yql +FolderPath(String)->String +``` + +Аргумент — строка с префиксом среди алиасов. + +Также см. [PRAGMA File](../syntax/pragma.md#file) и [PRAGMA Folder](../syntax/pragma.md#folder). + +### Примеры + +```yql +PRAGMA File("foo/1.txt", "http://url/to/somewhere"); +PRAGMA File("foo/2.txt", "http://url/to/somewhere/else"); +PRAGMA File("bar/3.txt", "http://url/to/some/other/place"); + +SELECT FolderPath("foo"); -- в директории по возвращённому пути будут + -- находиться файлы 1.txt и 2.txt, скачанные по указанным выше ссылкам +``` + +## ParseFile + +Получить из приложенного текстового файла список значений. Может использоваться в сочетании с [IN](../syntax/expressions.md#in) и прикладыванием файла по URL{% if oss != true %} (инструкции по прикладыванию файлов для {% if feature_webui %}[веб-интерфейса](../interfaces/web.md#attach) и {% endif %} [клиента](../interfaces/cli.md#attach)){% endif %}. + +Поддерживается только один формат файла — по одному значению на строку.{% if feature_udf_noncpp and oss != true %} Для чего-то более сложного прямо сейчас придется написать небольшую UDF на [Python](../udf/python.md) или [JavaScript](../udf/javascript.md).{% endif %} + +### Сигнатура + +```yql +ParseFile(String, String)->List +``` + +Два обязательных аргумента: + +1. Тип ячейки списка: поддерживаются только строки и числовые типы; +2. Имя приложенного файла. + +{% note info %} + +Возвращаемое значение - ленивый список. Для многократного использования его нужно обернуть в функцию [ListCollect](list.md#listcollect) + +{% endnote %} + +### Примеры + +```yql +SELECT ListLength(ParseFile("String", "my_file.txt")); +``` + +```yql +SELECT * FROM my_table +WHERE int_column IN ParseFile("Int64", "my_file.txt"); +``` + + +## WeakField {#weakfield} + +Вытаскивает колонку таблицы из строгой схемы, если оно там есть, либо из полей `_other` и `_rest`. В случае отсутствия значения возвращается `NULL`. + +Синтаксис: `WeakField([
.], [, ])`. + +Значение по умолчанию используется только в случае отсутствия колонки в схеме данных. Чтобы подставить значение по умолчанию в любом случае можно воспользоваться [COALESCE](#coalesce). + +### Примеры + +```yql +SELECT + WeakField(my_column, String, "no value"), + WeakField(my_table.other_column, Int64) +FROM my_table; +``` + +{% endif %} + +## Ensure... {#ensure} + +Проверка пользовательских условий: + +* `Ensure()` — проверка верности предиката во время выполнения запроса. +* `EnsureType()` — проверка точного соответствия типа выражения указанному. +* `EnsureConvertibleTo()` — мягкая проверка соответствия типа выражения, работающая по тем же правилам, что и неявное приведение типов. + +Если проверка не прошла успешно, то весь запрос завершается с ошибкой. + +### Сигнатуры + +```yql +Ensure(T, Bool, String)->T +EnsureType(T, Type, String)->T +EnsureConvertibleTo(T, Type, String)->T +``` + +Аргументы: + +1. Выражение, которое станет результатом вызова функции в случае успеха проверки. Оно же подвергается проверке на тип данных в соответствующих функциях. +2. В Ensure — булевый предикат, который проверяется на `true`. В остальных функциях — тип данных, который может быть получен через [предназначенные для этого функции](types.md), либо строковый литерал с [текстовым описанием типа](../types/type_string.md). +3. Опциональная строка с комментарием к ошибке, которая попадет в общее сообщение об ошибке при завершении запроса. Для проверок типов не может использовать сами данные, так как они выполняются на этапе валидации запроса, а для Ensure — может быть произвольным выражением. + +{% if backend_name != "YDB" %} + +Для проверки условий по финальному результату вычисления Ensure удобно использовать в сочетании с [DISCARD SELECT](../syntax/discard.md). + +{% endif %} + +### Примеры + +```yql +SELECT Ensure( + value, + value < 100, + "value out or range" +) AS value FROM my_table; +``` + +```yql +SELECT EnsureType( + value, + TypeOf(other_value), + "expected value and other_value to be of same type" +) AS value FROM my_table; +``` + +```yql +SELECT EnsureConvertibleTo( + value, + Double?, + "expected value to be numeric" +) AS value FROM my_table; +``` + + +## AssumeStrict {#assumestrict} + +### Сигнатура + +```yql +AssumeStrict(T)->T +``` + +Функция `AssumeStrict` возвращает свой аргумент. Использование этой функции – способ сказать оптимизатору YQL, что выражение в аргументе является *строгим*, т.е. свободным от ошибок времени выполнения. +Большинство встроенных функций и операторов YQL являются строгими, но есть исключения – например [Unwrap](#optional-ops) и [Ensure](#ensure). +Кроме того, нестрогим выражением считается вызов UDF. + +Если есть уверенность, что при вычислении выражения ошибок времени выполнения на самом деле не возникает, то имеет смысл использовать `AssumeStrict`. + +### Пример + +```yql +SELECT * FROM T1 AS a JOIN T2 AS b USING(key) +WHERE AssumeStrict(Unwrap(CAST(a.key AS Int32))) == 1; +``` + +В данном примере мы считаем что все значения текстовой колонки `a.key` в таблице `T1` являются валидными числами, поэтому Unwrap не приводит к ошибке. +При налиичии `AssumeStrict` оптимизатор сможет выполнить сначала фильтрацию, а потом JOIN. +Без `AssumeStrict` такая оптимизация не выполняется – оптимизатор обязан учитывать ситуацию, при которой в колонке `a.key` есть нечисловые значения, которые отфильтровываются `JOIN`ом. + + +## Likely {#likely} + +### Сигнатура + +```yql +Likely(Bool)->Bool +Likely(Bool?)->Bool? +``` + +Функция `Likely` возвращает свой аргумент. Функция является подсказкой оптимизатору и говорит о том, что в большинстве случаев ее аргумент будет иметь значение `True`. +Например, наличие такой функции в `WHERE` означает что фильтр является слабоселективным. + +### Пример + +```yql +SELECT * FROM T1 AS a JOIN T2 AS b USING(key) +WHERE Likely(a.amount > 0) -- почти всегда верно +``` + +При наличии `Likely` оптимизатор не будет стараться выполнить фильтрацию перед `JOIN`. + + +{% if feature_codegen %} + +## EvaluateExpr, EvaluateAtom {#evaluate_expr_atom} + +Возможность выполнить выражение до начала основного расчета и подставить его результат в запрос как литерал (константу). Во многих контекстах, где в стандартном SQL ожидалась бы только константа (например, в именах таблиц, количестве строк в [LIMIT](../syntax/select/limit_offset.md) и т.п.) этот функционал активируется неявным образом автоматически. + +EvaluateExpr может использоваться в тех местах, где грамматикой уже ожидается выражение. Например, с его помощью можно: + +* округлить текущее время до дней, недель или месяцев и подставить в запрос, что затем позволит корректно работать [кешированию запросов](../syntax/pragma.md#yt.querycachemode), хотя обычно использование [функций для получения текущего времени](#current-utc) его полностью отключает; +* сделать тяжелое вычисление с небольшим результатом один раз на запрос вместо одного раза на каждую джобу. + +{% if backend_name == "YT" %} + +EvaluateAtom позволяет динамически создать [атом](../types/special.md), но т.к. ими в основном оперирует более низкий уровень [s-expressions](/docs/s_expressions/functions), то использовать эту функцию напрямую как правило не рекомендуется. + +{% endif %} + +Единственный аргумент у обоих функций — само выражение для вычисления и подстановки. + +Ограничения: + +* выражение не должно приводить к запуску MapReduce операций; +* данный функционал полностью заблокирован в YQL over YDB. + +### Примеры + +```yql +$now = CurrentUtcDate(); +SELECT EvaluateExpr( + DateTime::MakeDate(DateTime::StartOfWeek($now) + ) +); +``` + + +{% endif %} + +## Литералы простых типов {#data-type-literals} + +Для простых типов могут быть созданы литералы на основании строковых литералов. + +### Синтаксис + +`<Простой тип>( <строка>[, <дополнительные атрибуты>] )` + +В отличие от `CAST("myString" AS MyType)`: + +* Проверка на приводимость литерала к требуемому типу происходит на этапе валидации; +* Результат не является optional. + +Для типов данных `Date`, `Datetime`, `Timestamp` и `Interval` поддерживаются литералы только в формате, соответствующем [ISO 8601](https://ru.wikipedia.org/wiki/ISO_8601). У `Interval` есть следующие отличия от стандарта: + +* поддерживается отрицательный знак для сдвигов в прошлое; +* микросекунды могут быть записаны как дробная часть секунд; +* единицы измерения больше недель не доступны; +* не поддерживаются варианты с началом/концом интервала, а также повторами. + +Для типов данных `TzDate`, `TzDatetime`, `TzTimestamp` литералы также задаются в формате, соответствующем [ISO 8601](https://ru.wikipedia.org/wiki/ISO_8601), но вместо опционального суффикса Z через запятую указывается [IANA имя временной зоны](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones), например, GMT или Europe/Moscow. + +{% include [decimal args](../_includes/decimal_args.md) %} + +### Примеры + +```yql +SELECT + Bool("true"), + Uint8("0"), + Int32("-1"), + Uint32("2"), + Int64("-3"), + Uint64("4"), + Float("-5"), + Double("6"), + Decimal("1.23", 5, 2), -- до 5 десятичных знаков, из которых 2 после запятой + String("foo"), + Utf8("привет"), + Yson("[3;%false]"), + Json(@@{"a":1,"b":null}@@), + Date("2017-11-27"), + Datetime("2017-11-27T13:24:00Z"), + Timestamp("2017-11-27T13:24:00.123456Z"), + Interval("P1DT2H3M4.567890S"), + TzDate("2017-11-27,Europe/Moscow"), + TzDatetime("2017-11-27T13:24:00,America/Los_Angeles"), + TzTimestamp("2017-11-27T13:24:00.123456,GMT"), + Uuid("f9d5cc3f-f1dc-4d9c-b97e-766e57ca4ccb"); +``` + +{% if feature_webui %} + +## Доступ к метаданным текущей операции {#metadata} + +При запуске YQL операций через веб-интерфейс или HTTP API, предоставляется доступ к следующей информации: + +* `CurrentOperationId()` — приватный идентификатор операции; +* `CurrentOperationSharedId()` — публичный идентификатор операции; +* `CurrentAuthenticatedUser()` — логин текущего пользователя. + +### Сигнатуры + +```yql +CurrentOperationId()->String +CurrentOperationSharedId()->String +CurrentAuthenticatedUser()->String +``` + +Аргументов нет. + +При отсутствии данной информации, например, при запуске в embedded режиме, возвращают пустую строку. + +### Примеры + +```yql +SELECT + CurrentOperationId(), + CurrentOperationSharedId(), + CurrentAuthenticatedUser(); +``` + + +{% endif %} + +## ToBytes и FromBytes {#to-from-bytes} + +Конвертация [простых типов данных](../types/primitive.md) в строку со своим бинарным представлением и обратно. Числа представляются в [little endian](https://en.wikipedia.org/wiki/Endianness#Little-endian). + +### Сигнатуры + +```yql +ToBytes(T)->String +ToBytes(T?)->String? + +FromBytes(String, Type)->T? +FromBytes(String?, Type)->T? +``` + +### Примеры + +```yql +SELECT + ToBytes(123), -- "\u0001\u0000\u0000\u0000" + FromBytes( + "\xd2\x02\x96\x49\x00\x00\x00\x00", + Uint64 + ); -- 1234567890ul +``` + + +## ByteAt {#byteat} + +Получение значение байта в строке по индексу от её начала. В случае некорректного индекса возвращается `NULL`. + +### Сигнатура + +```yql +ByteAt(String, Uint32)->Uint8 +ByteAt(String?, Uint32)->Uint8? + +ByteAt(Utf8, Uint32)->Uint8 +ByteAt(Utf8?, Uint32)->Uint8? +``` + +Аргументы: + +1. Строка: `String` или `Utf8`; +2. Индекс: `Uint32`. + +### Примеры + +```yql +SELECT + ByteAt("foo", 0), -- 102 + ByteAt("foo", 1), -- 111 + ByteAt("foo", 9); -- NULL +``` + + +## ...Bit {#bitops} + +`TestBit()`, `ClearBit()`, `SetBit()` и `FlipBit()` - проверить, сбросить, установить или инвертировать бит в беззнаковом числе по указанному порядковому номеру бита. + +### Сигнатуры + +```yql +TestBit(T, Uint8)->Bool +TestBit(T?, Uint8)->Bool? + +ClearBit(T, Uint8)->T +ClearBit(T?, Uint8)->T? + +SetBit(T, Uint8)->T +SetBit(T?, Uint8)->T? + +FlipBit(T, Uint8)->T +FlipBit(T?, Uint8)->T? +``` + +Аргументы: + +1. Беззнаковое число, над которым выполнять требуемую операцию. TestBit также реализован и для строк. +2. Номер бита. + +TestBit возвращает `true/false`. Остальные функции возвращают копию своего первого аргумента с проведенным соответствующим преобразованием. + +### Примеры + +```yql +SELECT + TestBit(1u, 0), -- true + SetBit(8u, 0); -- 9 +``` + + +## Abs {#abs} + +Абсолютное значение числа. + +### Сигнатура + +```yql +Abs(T)->T +Abs(T?)->T? +``` + +### Примеры + +```yql +SELECT Abs(-123); -- 123 +``` + + +## Just {#optional-ops} + +`Just()` - Изменить тип данных значения на [optional](../types/optional.md) от текущего типа данных (то есть `T` превращается в `T?`). + +### Сигнатура + +```yql +Just(T)->T? +``` + +### Примеры + +```yql +SELECT + Just("my_string"); -- String? +``` + +## Unwrap {#unwrap} + +`Unwrap()` - Преобразование значения [optional](../types/optional.md) типа данных в соответствующий не-optional тип с ошибкой времени выполнений, если в данных оказался `NULL`. Таким образом, `T?` превращается в `T`. + +Если значение не является [optional](../types/optional.md), то функция возвращает свой первый аргумент без изменений. + +### Сигнатура + +```yql +Unwrap(T?)->T +Unwrap(T?, Utf8)->T +Unwrap(T?, String)->T +``` + +Аргументы: + +1. Значение для преобразования; +2. Опциональная строка с комментарием для текста ошибки. + +Обратная операция — [Just](#optional-ops). + +### Примеры + +```yql +$value = Just("value"); + +SELECT Unwrap($value, "Unexpected NULL for $value"); +``` + +## Nothing {#nothing} + +`Nothing()` - Создать пустое значение указанного [Optional](../types/optional.md) типа данных. + +### Сигнатура + +```yql +Nothing(Type)->T? +``` + +### Примеры + +```yql +SELECT + Nothing(String?); -- пустое значение (NULL) с типом String? +``` + +[Подробнее о ParseType и других функциях для работы с типами данных](types.md). + + +## Callable {#callable} + +Создать вызываемое значение с заданной сигнатурой из лямбда-функции. Обычно используется для того, чтобы размещать вызываемые значения в контейнерах. + +### Сигнатура + +```yql +Callable(TypeT>>, lambda)->Callable<(...)->T> +``` + +Аргументы: + +1. Тип; +2. Лямбда-функция. + +### Примеры + +```yql +$lambda = ($x) -> { + RETURN CAST($x as String) +}; + +$callables = AsTuple( + Callable(Callable<(Int32)->String>, $lambda), + Callable(Callable<(Bool)->String>, $lambda), +); + +SELECT $callables.0(10), $callables.1(true); +``` + + +## Pickle, Unpickle {#pickle} + +`Pickle()` и `StablePickle()` сериализуют произвольный объект в последовательность байт, если это возможно. Типовыми несериализуемыми объектами являются Callable и Resource. Формат сериализации не версионируется, допускается использовать в пределах одного запроса. Для типа Dict функция StablePickle предварительно сортирует ключи, а для Pickle порядок элементов словаря в сериализованном представлении не определен. + +`Unpickle()` — обратная операция (десериализация), где первым аргументом передается тип данных результата, а вторым — строка с результатом `Pickle()` или `StablePickle()`. + +### Сигнатуры + +```yql +Pickle(T)->String +StablePickle(T)->String +Unpickle(Type, String)->T +``` + +### Примеры + +```yql +SELECT * +FROM my_table +WHERE Digest::MurMurHash32( + Pickle(TableRow()) + ) % 10 == 0; -- в реальности лучше использовать TABLESAMPLE + +$buf = Pickle(123); +SELECT Unpickle(Int32, $buf); +``` + + +## StaticMap + +Преобразует структуру или кортеж, применяя лямбду к каждому элементу. + +### Сигнатура + +```yql +StaticMap(Struct<...>, lambda)->Struct<...> +StaticMap(Tuple<...>, lambda)->Tuple<...> +``` + +Аргументы: + +* Структура или кортеж; +* Лямбда для обработки элементов. + +Результат: структура или кортеж с аналогичным первому аргументу количеством и именованием элементов, а типы данных элементов определяются результатами лямбды. + +### Примеры + +```yql +SELECT * +FROM ( + SELECT + StaticMap(TableRow(), ($item) -> { + return CAST($item AS String); + }) + FROM my_table +) FLATTEN COLUMNS; -- преобразование всех колонок в строки +``` + + + +## StaticZip + +Поэлементно "склеивает" структуры или кортежи. Все аргументы (один и более) должны быть либо структурами с одинаковым набором полей, либо кортежами одинаковой длины. +Результататом будет соответственно структура или кортеж. +Каждый элемент результата – кортеж с соответствующими элементами из аргументов. + +### Сигнатура + +```yql +StaticZip(Struct, Struct)->Struct +StaticZip(Tuple, Tuple)->Tuple +``` + +### Примеры + +```yql +$one = <|k1:1, k2:2.0|>; +$two = <|k1:3.0, k2:4|>; + +-- поэлементное сложение двух структур +SELECT StaticMap(StaticZip($one, $two), ($tuple)->($tuple.0 + $tuple.1)) AS sum; +``` + + +## StaticFold, StaticFold1 {#staticfold} + +```yql +StaticFold(obj:Struct/Tuple, initVal, updateLambda) +StaticFold1(obj:Struct/Tuple, initLambda, updateLambda) +``` + +Статическая левоассоциативная свертка структуры или кортежа. +Для кортежей свертка производится в порядке от меньшего индекса к большему, для структур порядок не гарантируется. + +- `obj` - объект, элементы которого нужно свернуть +- `initVal` - *(для StaticFold)* исходное состояние свертки +- `initLambda` - *(для StaticFold1)* функция для получения исходного состояния по первому элементу +- `updateLambda` - функция обновления состояния (принимает в аргументах следующий элемент объекта и предыдущее состояние) + +`StaticFold(<|key_1:$el_1, key_2:$el_2, ..., key_n:$el_n|>, $init, $f)` преобразуется в свертку: + +```yql +$f($el_n, ...$f($el_2, $f($init, el_1))...) +``` + +`StaticFold1(<|key_1:$el_1, key_2:$el_2, ..., key_n:$el_n|>, $f0, $f)`: + +```yql +$f($el_n, ...$f($el_2, $f($f0($init), el_1))...) +``` + +`StaticFold1(<||>, $f0, $f)` вернет `NULL`. + +Аналогично работает и с кортежами. + + +## AggregationFactory {#aggregationfactory} + +Создать фабрику для [агрегационных функций](aggregation.md) для того чтобы разделить процесс описания того, как агрегировать данные, и то, к каким данным это применять. + +Аргументы: + +1. Строка в кавычках, являющаяся именем агрегационной функции, например ["MIN"](aggregation.md#min). +2. Опциональные параметры агрегационной функции, которые не зависят от данных. Например, значение percentile в [PERCENTILE](aggregation.md#percentile). + +Полученную фабрику можно использовать как второй параметр функции [AGGREGATE_BY](aggregation.md#aggregateby). +Если агрегационная функция работает на двух колонках вместо одной, как например, [MIN_BY](aggregation.md#minby), то в [AGGREGATE_BY](aggregation.md#aggregateby) первым аргументом передается `Tuple` из двух значений. Подробнее это указано при описании такой агрегационной функции. + +### Примеры + +```yql +$factory = AggregationFactory("MIN"); +SELECT + AGGREGATE_BY(value, $factory) AS min_value -- применить MIN агрегацию к колонке value +FROM my_table; +``` + +## AggregateTransformInput {#aggregatetransform} + +`AggregateTransformInput()` преобразует фабрику для [агрегационных функций](aggregation.md), например, полученную через функцию [AggregationFactory](#aggregationfactory) в другую фабрику, в которой перед началом выполнения агрегации производится указанное преобразование входных элементов. + +Аргументы: + +1. Фабрика для агрегационных функций; +2. Лямбда функция с одним аргументом, преобразующая входной элемент. + +### Примеры + +```yql +$f = AggregationFactory("sum"); +$g = AggregateTransformInput($f, ($x) -> (cast($x as Int32))); +$h = AggregateTransformInput($f, ($x) -> ($x * 2)); +SELECT ListAggregate([1,2,3], $f); -- 6 +SELECT ListAggregate(["1","2","3"], $g); -- 6 +SELECT ListAggregate([1,2,3], $h); -- 12 +``` + +## AggregateTransformOutput {#aggregatetransformoutput} + +`AggregateTransformOutput()` преобразует фабрику для [агрегационных функций](aggregation.md), например, полученную через функцию [AggregationFactory](#aggregationfactory) в другую фабрику, в которой после окончания выполнения агрегации производится указанное преобразование результата. + +Аргументы: + +1. Фабрика для агрегационных функций; +2. Лямбда функция с одним аргументом, преобразующая результат. + +### Примеры + +```yql +$f = AggregationFactory("sum"); +$g = AggregateTransformOutput($f, ($x) -> ($x * 2)); +SELECT ListAggregate([1,2,3], $f); -- 6 +SELECT ListAggregate([1,2,3], $g); -- 12 +``` + +## AggregateFlatten {#aggregateflatten} + +Адаптирует фабрику для [агрегационных функций](aggregation.md), например, полученную через функцию [AggregationFactory](#aggregationfactory) так, чтобы выполнять агрегацию над входными элементами - списками. Эта операция похожа на [FLATTEN LIST BY](../syntax/flatten.md) - производится агрегация каждого элемента списка. + +Аргументы: + +1. Фабрика для агрегационных функций. + +### Примеры + +```yql +$i = AggregationFactory("AGGREGATE_LIST_DISTINCT"); +$j = AggregateFlatten($i); +SELECT AggregateBy(x, $j) from ( + SELECT [1,2] as x + union all + SELECT [2,3] as x +); -- [1, 2, 3] + +``` + +{% if tech %} + +## YQL::, s-expressions {#s-expressions} + +Полный список внутренних функций YQL находится в [документации к s-expressions](/docs/s_expressions/functions), альтернативному низкоуровневому синтаксису YQL. Любую из перечисленных там функций можно вызвать и из SQL синтаксиса, добавив к её имени префикс `YQL::`, но это не рекомендуется делать, т.к. данный механизм предназначен в первую очередь для временного обхода возможных проблем, а также для нужд внутреннего тестирования. + +Если функция доступна в SQL синтаксисе без префикса `YQL::`, то её поведение имеет право отличаться от одноименной функции из документации по s-expressions, если таковая существует. + + +{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/codegen.md b/ydb/docs/ru/core/yql/reference/builtins/codegen.md similarity index 85% rename from ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/codegen.md rename to ydb/docs/ru/core/yql/reference/builtins/codegen.md index da44954fd288..1d6cd2373e2f 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/codegen.md +++ b/ydb/docs/ru/core/yql/reference/builtins/codegen.md @@ -1,6 +1,7 @@ + # Функции для работы с генерацией кода -Во время выполнения вычислений можно сгенерировать код, состоящий из узлов [S-expressions](/docs/s_expressions). Для этого используется механизм представления кода, упакованного в [ресурс](../../types/special.md). После конструирования кода можно подставить его в основную програму с помощью функции [EvaluateCode](#evaluatecode). Для отладки сконвертировать код в строку можно с помощью функции [FormatCode](#formatcode). +Во время выполнения вычислений можно сгенерировать код, состоящий из узлов [S-expressions](/docs/s_expressions). Для этого используется механизм представления кода, упакованного в [ресурс](../types/special.md). После конструирования кода можно подставить его в основную програму с помощью функции [EvaluateCode](#evaluatecode). Для отладки сконвертировать код в строку можно с помощью функции [FormatCode](#formatcode). Возможные типы узлов в S-expressions, которые можно использовать для генерации кода: @@ -112,8 +113,8 @@ SELECT FormatCode(FuncCode( Построить узел кода с типом `объявление лямбда функции` можно из: -* [Лямбда функции](../../syntax/expressions.md#lambda), если заранее известно количество аргументов. В этом случае в качестве аргументов этой лямбда функции будут переданы узлы типа `аргумент`. -* Количества аргументов и [лямбда функции](../../syntax/expressions.md#lambda) с одним аргументом. В этом случае в качестве аргумента этой лямбды функции будет передан список узлов типа `аргумент`. +* [Лямбда функции](../syntax/expressions.md#lambda), если заранее известно количество аргументов. В этом случае в качестве аргументов этой лямбда функции будут переданы узлы типа `аргумент`. +* Количества аргументов и [лямбда функции](../syntax/expressions.md#lambda) с одним аргументом. В этом случае в качестве аргумента этой лямбды функции будет передан список узлов типа `аргумент`. ### Примеры @@ -163,7 +164,7 @@ SELECT $add3(1); -- 4 ## QuoteCode -Подстановка в основную программу узла кода, который является представлением выражения или [лямбда функции](../../syntax/expressions.md#lambda), переданной в аргумент. Если во время подстановки были найдены свободные аргументы лямбда функций, то они вычисляются и подставляются в код как в функции [ReprCode](#reprcode). +Подстановка в основную программу узла кода, который является представлением выражения или [лямбда функции](../syntax/expressions.md#lambda), переданной в аргумент. Если во время подстановки были найдены свободные аргументы лямбда функций, то они вычисляются и подставляются в код как в функции [ReprCode](#reprcode). ### Примеры @@ -178,3 +179,4 @@ $makeClosure = ($y) -> { $closure = $makeClosure(2); SELECT $closure(1); -- 3 ``` + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/dict.md b/ydb/docs/ru/core/yql/reference/builtins/dict.md similarity index 90% rename from ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/dict.md rename to ydb/docs/ru/core/yql/reference/builtins/dict.md index e52428e64371..7c9ccf87edee 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/dict.md +++ b/ydb/docs/ru/core/yql/reference/builtins/dict.md @@ -1,3 +1,4 @@ + # Функции для работы со словарями ## DictCreate {#dictcreate} @@ -8,15 +9,15 @@ DictCreate(K,V)->Dict ``` -Сконструировать пустой словарь. Передается два аргумента — для ключа и значения, в каждом из которых указывается строка с описанием типа данных, либо сам тип, полученный с помощью [предназначенных для этого функций](../types.md). Словарей с неизвестным типом ключа или значения в YQL не бывает. +Сконструировать пустой словарь. Передается два аргумента — для ключа и значения, в каждом из которых указывается строка с описанием типа данных, либо сам тип, полученный с помощью [предназначенных для этого функций](types.md). Словарей с неизвестным типом ключа или значения в YQL не бывает. В качестве типа ключа могут быть заданы: -* [примитивный тип данных](../../types/primitive.md) (кроме `Yson` и `Json`), +* [примитивный тип данных](../types/primitive.md) (кроме `Yson` и `Json`), * примитивный тип данных (кроме `Yson` и `Json`) с признаком опциональности, * кортеж длины не менее два из типов, перечисленных выше. -[Документация по формату описания типа](../../types/type_string.md). +[Документация по формату описания типа](../types/type_string.md). ### Примеры @@ -40,9 +41,9 @@ SELECT DictCreate(ParseType("Tuple"), ParseType("TupleSet ``` -Сконструировать пустое множество. Передается аргумент - тип ключа, возможно, полученный с помощью [предназначенных для этого функций](../types.md). Множеств с неизвестным типом ключа в YQL не бывает. Ограничения на тип ключа такие же как и на тип ключа для словаря. Следует иметь ввиду, что множество это словарь с типом значения `Void` и множество также можно создать и с помощью функции `DictCreate`. Отсюда также следует, что все функции, которые принимают на вход `Dict` могут также принимать `Set`. +Сконструировать пустое множество. Передается аргумент - тип ключа, возможно, полученный с помощью [предназначенных для этого функций](types.md). Множеств с неизвестным типом ключа в YQL не бывает. Ограничения на тип ключа такие же как и на тип ключа для словаря. Следует иметь ввиду, что множество это словарь с типом значения `Void` и множество также можно создать и с помощью функции `DictCreate`. Отсюда также следует, что все функции, которые принимают на вход `Dict` могут также принимать `Set`. -[Документация по формату описания типа](../../types/type_string.md). +[Документация по формату описания типа](../types/type_string.md). ### Примеры @@ -258,7 +259,7 @@ DictAggregate(Dict>, List->T)->Dict DictAggregate(Dict>?, List->T)->Dict? ``` -Применить [фабрику агрегационных функций](../basic.md#aggregationfactory) для переданного словаря, в котором каждое значение является списком. Фабрика применяется отдельно внутри каждого ключа. +Применить [фабрику агрегационных функций](basic.md#aggregationfactory) для переданного словаря, в котором каждое значение является списком. Фабрика применяется отдельно внутри каждого ключа. Если список является пустым, то результат агрегации будет такой же, как для пустой таблицы: 0 для функции `COUNT` и `NULL` для других функций. Если в переданном словаре список по некоторому ключу является пустым, то такой ключ удаляется из результата. Если переданный словарь является опциональным и содержит значение `NULL`, то в результате также будет `NULL`. @@ -266,7 +267,7 @@ DictAggregate(Dict>?, List->T)->Dict? Аргументы: 1. Словарь; -2. [Фабрика агрегационных функций](../basic.md#aggregationfactory). +2. [Фабрика агрегационных функций](basic.md#aggregationfactory). ### Примеры @@ -345,7 +346,7 @@ SELECT SetIntersection( {% note info %} -В примере использовалась [лямбда функция](../../syntax/expressions.md#lambda). +В примере использовалась [лямбда функция](../syntax/expressions.md#lambda). {% endnote %} @@ -469,3 +470,4 @@ SELECT SetSymmetricDifference( ($k, $a, $b) -> { RETURN AsTuple($a, $b) }); -- { 2 : (null, "qwe"), 3 : ("bar", null) } ``` + diff --git a/ydb/docs/ru/core/yql/reference/builtins/index.md b/ydb/docs/ru/core/yql/reference/builtins/index.md new file mode 100644 index 000000000000..6d29963501b4 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/builtins/index.md @@ -0,0 +1,26 @@ + +# Встроенные функции YQL + +- [Базовые](basic.md) +- [Агрегатные](aggregation.md) + +{% if feature_window_functions %} + +- [Оконные](window.md) + +{% endif %} + +- [Для работы со списками](list.md) +- [Для работы со словарями](dict.md) +- [Для работы со структурами](struct.md) +- [Для работы с типами](types.md) + +{% if feature_codegen %} + +- [Для работы с генерацией кода](codegen.md) + +{% endif %} + +- [Для работы с JSON](json.md) +- [Библиотеки C++](../udf/list/index.md) + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/json.md b/ydb/docs/ru/core/yql/reference/builtins/json.md similarity index 99% rename from ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/json.md rename to ydb/docs/ru/core/yql/reference/builtins/json.md index 557b7852ef4f..449ac84c93f0 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/json.md +++ b/ydb/docs/ru/core/yql/reference/builtins/json.md @@ -1,3 +1,4 @@ + # Функции для работы с JSON @@ -501,7 +502,7 @@ JsonPath поддерживает предикаты - выражения, во #### `like_regex` -Предикат `like_regex` позволяет проверить строку на соответствие регулярному выражению. Синтаксис регулярных выражений такой же как в [Hyperscan UDF](../../udf/list/hyperscan.md) и [REGEXP](../../syntax/expressions.md#regexp). +Предикат `like_regex` позволяет проверить строку на соответствие регулярному выражению. Синтаксис регулярных выражений такой же как в [Hyperscan UDF](../udf/list/hyperscan.md) и [REGEXP](../syntax/expressions.md#regexp). ##### Синтаксис @@ -1196,7 +1197,8 @@ SELECT ## Смотрите также -* [{#T}](../../../../recipes/yql/accessing-json.md) -* [{#T}](../../../../recipes/yql/modifying-json.md) +* [{#T}](../recipes/accessing-json.md) +* [{#T}](../recipes/modifying-json.md) {% endif %} + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/list.md b/ydb/docs/ru/core/yql/reference/builtins/list.md similarity index 97% rename from ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/list.md rename to ydb/docs/ru/core/yql/reference/builtins/list.md index 9dc056921276..d9f57d8afc7e 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/list.md +++ b/ydb/docs/ru/core/yql/reference/builtins/list.md @@ -2,9 +2,9 @@ ## ListCreate {#list-create} -Сконструировать пустой список. В единственном аргументе указывается строка с описанием типа данных ячейки списка, либо сам тип, полученный с помощью [предназначенных для этого функций](../types.md). Списков с неизвестным типом ячейки в YQL не бывает. +Сконструировать пустой список. В единственном аргументе указывается строка с описанием типа данных ячейки списка, либо сам тип, полученный с помощью [предназначенных для этого функций](types.md). Списков с неизвестным типом ячейки в YQL не бывает. -[Документация по формату описания типа](../../types/type_string.md). +[Документация по формату описания типа](../types/type_string.md). ### Примеры @@ -133,7 +133,7 @@ SELECT ListSort($list, ($x) -> { {% note info %} -В примере использовалась [лямбда функция](../../syntax/expressions.md#lambda). +В примере использовалась [лямбда функция](../syntax/expressions.md#lambda). {% endnote %} @@ -228,7 +228,7 @@ ListUnionAll(List>?, List>?..)->List>? По входящим спискам построить список пар, содержащих соответствующие по индексу элементы списков (`List>`). Длина возвращаемого списка определяется самым коротким списком для ListZip и самым длинным — для ListZipAll. -Когда более короткий список исчерпан, в качестве пары к элементам более длинного списка подставляется пустое значение (`NULL`) соответствующего [optional типа](../../types/optional.md). +Когда более короткий список исчерпан, в качестве пары к элементам более длинного списка подставляется пустое значение (`NULL`) соответствующего [optional типа](../types/optional.md). ### Примеры @@ -373,7 +373,7 @@ ListTake(List?, Uint64)->List? Если вероятность/размер выборки является NULL, то вернется исходный список. -Дополнительный аргумент используется для управления случайностью, подробнее см. [документацию к `Random`](./basic/random.md). +Дополнительный аргумент используется для управления случайностью, подробнее см. [документацию к `Random`](basic.md#random). ### Примеры @@ -396,7 +396,7 @@ ListSampleN(List?, Uint64?[, U])->List? ## ListShuffle {#listshuffle} -Возвращает копию списка с элементами, перестановленными в случайном порядке. Дополнительный аргумент используется для управления случайностью, подробнее см. [документацию к `Random`](./basic/random.md). +Возвращает копию списка с элементами, перестановленными в случайном порядке. Дополнительный аргумент используется для управления случайностью, подробнее см. [документацию к `Random`](basic.md#random). ### Примеры @@ -461,12 +461,12 @@ ListIndexOf(List?, T)->Uint64? 1. Исходный список; 2. Функции для обработки элементов, например: - * [Лямбда функция](../../syntax/expressions.md#lambda); + * [Лямбда функция](../syntax/expressions.md#lambda); * `Module::Function` - С++ UDF; {% if feature_udf_noncpp and oss != true %} - * [Python UDF](../../udf/python.md), [JavaScript UDF](../../udf/javascript.md) или любое другое вызываемое значение; + * [Python UDF](../udf/python.md), [JavaScript UDF](../udf/javascript.md) или любое другое вызываемое значение; {% endif %} @@ -926,14 +926,14 @@ ListTakeWhile(List?, (T)->Bool)->List? ## ListAggregate {#listaggregate} -Применить [фабрику агрегационных функций](../basic.md#aggregationfactory) для переданного списка. +Применить [фабрику агрегационных функций](basic.md#aggregationfactory) для переданного списка. Если переданный список является пустым, то результат агрегации будет такой же, как для пустой таблицы: 0 для функции `COUNT` и `NULL` для других функций. Если переданный список является опциональным и равен `NULL`, то в результате также будет `NULL`. Аргументы: 1. Список; -2. [Фабрика агрегационных функций](../basic.md#aggregationfactory). +2. [Фабрика агрегационных функций](basic.md#aggregationfactory). ### Примеры @@ -988,7 +988,7 @@ ToDict(List>?)->Dict? Преобразует список в словарь, в котором ключи являются уникальными элементами этого списка, а значения отсутствуют и имеют тип `Void`. Для списка `List` тип результата будет `Dict`. Также поддерживается опциональный список, что приводит к опциональному словарю в результате. -Обратная функция - получить список ключей словаря [DictKeys](../dict.md#dictkeys). +Обратная функция - получить список ключей словаря [DictKeys](dict.md#dictkeys). ### Примеры @@ -1074,3 +1074,4 @@ ListTop(List{Flags:AutoMap}, N, (T)->U)->List ``` Сигнатуры остальных функций совпадают с `ListTop`. + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/struct.md b/ydb/docs/ru/core/yql/reference/builtins/struct.md similarity index 99% rename from ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/struct.md rename to ydb/docs/ru/core/yql/reference/builtins/struct.md index 3333afe3b2ca..6fdfd3475bb1 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/struct.md +++ b/ydb/docs/ru/core/yql/reference/builtins/struct.md @@ -1,3 +1,4 @@ + # Функции для работы со структурами ## TryMember {#trymember} @@ -54,7 +55,7 @@ ExpandStruct(struct:Struct<...>, value_1:T1 AS key_1:K, value_2:T2 AS key_2:K, . Аргументы: * В первый аргумент передается исходная структура для расширения. -* Все остальные аргументы должны быть именованными, каждый аргумент добавляет новое поле и имя аргумента используется в роли имени поля (по аналогии с [AsStruct](../basic.md#asstruct)). +* Все остальные аргументы должны быть именованными, каждый аргумент добавляет новое поле и имя аргумента используется в роли имени поля (по аналогии с [AsStruct](basic.md#asstruct)). ### Примеры @@ -466,3 +467,4 @@ SELECT StructSymmetricDifference($left, $right) -- <|a: 1, b: 2, d: 2, e: 3|> ; ``` + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/toc_i.yaml b/ydb/docs/ru/core/yql/reference/builtins/toc_i.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/builtins/toc_i.yaml rename to ydb/docs/ru/core/yql/reference/builtins/toc_i.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/types.md b/ydb/docs/ru/core/yql/reference/builtins/types.md similarity index 94% rename from ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/types.md rename to ydb/docs/ru/core/yql/reference/builtins/types.md index cafd39101397..13e58e46ed14 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/types.md +++ b/ydb/docs/ru/core/yql/reference/builtins/types.md @@ -1,6 +1,7 @@ + # Функции для работы с типами данных -Помимо обычных функций, которые работают с конкретными значениями (типа FIND, COALESCE), YQL поддерживает функции для работами с [типами](../../types/index.md). +Помимо обычных функций, которые работают с конкретными значениями (типа FIND, COALESCE), YQL поддерживает функции для работами с [типами](../types/index.md). Функции позволяют узнать тип произвольного выражения, проанализировать контейнерный тип и создавть новый контейнерный тип на основе имеющегося. ## Примеры @@ -19,7 +20,7 @@ FormatType(Type)->String FormatType(TypeHandle)->String ``` -Сериализация типа {% if feature_codegen %} или хендла типа{% endif %} в человекочитаемую строку. Это полезно для отладки, а также будет использоваться в последующих примерах данного раздела. [Документация по формату](../../types/type_string.md). +Сериализация типа {% if feature_codegen %} или хендла типа{% endif %} в человекочитаемую строку. Это полезно для отладки, а также будет использоваться в последующих примерах данного раздела. [Документация по формату](../types/type_string.md). ## FormatTypeDiff и FormatTypeDiffPretty {#formattypediff} @@ -43,7 +44,7 @@ FormatTypeDiffPretty(TypeHandle, TypeHandle)->String ParseType(String)->Type ``` -Построение типа по строке с его описанием. [Документация по её формату](../../types/type_string.md). +Построение типа по строке с его описанием. [Документация по её формату](../types/type_string.md). ### Примеры @@ -101,7 +102,7 @@ SELECT FormatType(TypeOf( DataType(String, [String, ...])->Type ``` -Возвращает тип для [примитивных типов данных](../../types/primitive.md) по его имени. +Возвращает тип для [примитивных типов данных](../types/primitive.md) по его имени. Для некоторых типов (например Decimal) необходимо передавать параметры типа в качестве дополнительных аргументов. ### Примеры @@ -230,7 +231,7 @@ SELECT FormatType(VariantType( ResourceType(String)->тип ресурса ``` -Возвращает тип [ресурса](../../types/special.md) по переданной строковой метке. +Возвращает тип [ресурса](../types/special.md) по переданной строковой метке. ### Примеры @@ -273,7 +274,7 @@ UnitType()->тип VoidType()->тип ``` -Возвращают одноименные [специальные типы данных](../../types/special.md). Аргументов нет, так как они не параметризуются. +Возвращают одноименные [специальные типы данных](../types/special.md). Аргументов нет, так как они не параметризуются. ### Примеры @@ -440,7 +441,7 @@ FormatType(VariantUnderlyingType( ## Функции для работы с типами данных во время выполнения вычислений -Для работы с типами данных во время выполнения вычислений используется механизм хендлов типов - [ресурс](../../types/special.md), содержащий непрозрачное описание типа. После конструирования хендла типа можно вернуться к обычному типу с помощью функции [EvaluateType](#evaluatetype). Для отладки сконвертировать хендл типа в строку можно с помощью функции [FormatType](#formattype). +Для работы с типами данных во время выполнения вычислений используется механизм хендлов типов - [ресурс](../types/special.md), содержащий непрозрачное описание типа. После конструирования хендла типа можно вернуться к обычному типу с помощью функции [EvaluateType](#evaluatetype). Для отладки сконвертировать хендл типа в строку можно с помощью функции [FormatType](#formattype). ### TypeHandle @@ -466,7 +467,7 @@ SELECT FormatType(TypeHandle(TypeOf("foo"))); -- String EvaluateType(TypeHandle)->тип ``` -Получение типа из хендла типа, переданного в аргумент. Функция вычисляется до начала основного расчета, как и [EvaluateExpr](../basic.md#evaluate_expr_atom). +Получение типа из хендла типа, переданного в аргумент. Функция вычисляется до начала основного расчета, как и [EvaluateExpr](basic.md#evaluate_expr_atom). #### Примеры @@ -482,7 +483,7 @@ SELECT FormatType(EvaluateType(TypeHandle(TypeOf("foo")))); -- String ParseTypeHandle(String)->хэндл типа ``` -Построение хендла типа по строке с его описанием. [Документация по её формату](../../types/type_string.md). +Построение хендла типа по строке с его описанием. [Документация по её формату](../types/type_string.md). #### Примеры @@ -515,7 +516,7 @@ SELECT TypeKind(ParseTypeHandle("List")); -- List DataTypeComponents(DataTypeHandle)->List ``` -Получение названия и параметров [примитивного типа данных](../../types/primitive.md) из хендла примитивного типа, переданного в аргумент. Обратная функция - [DataTypeHandle](#datatypehandle). +Получение названия и параметров [примитивного типа данных](../types/primitive.md) из хендла примитивного типа, переданного в аргумент. Обратная функция - [DataTypeHandle](#datatypehandle). #### Примеры @@ -532,7 +533,7 @@ SELECT DataTypeComponents(ParseTypeHandle("Decimal(4,1)")); -- ["Decimal", "4", DataTypeHandle(List)->хэндл примитивного типа данных ``` -Построение хендла [примитивного типа данных](../../types/primitive.md) из его названия и параметров, переданных списком в аргумент. Обратная функция - [DataTypeComponents](#datatypecomponents). +Построение хендла [примитивного типа данных](../types/primitive.md) из его названия и параметров, переданных списком в аргумент. Обратная функция - [DataTypeComponents](#datatypecomponents). #### Примеры @@ -1003,3 +1004,4 @@ SELECT LambdaOptionalArgumentsCount(($x, $y, $z?)->(if($x,$y,$z))) ``` {% endif %} + diff --git a/ydb/docs/ru/core/yql/reference/builtins/window.md b/ydb/docs/ru/core/yql/reference/builtins/window.md new file mode 100644 index 000000000000..357400d381e9 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/builtins/window.md @@ -0,0 +1,240 @@ + +# Список оконных функций в YQL + +Синтаксис вызова оконных функций подробно описан в [отдельной статье](../syntax/window.md). + + +## Агрегатные функции {#aggregate-functions} + +Все [агрегатные функции](aggregation.md) также могут использоваться в роли оконных. +В этом случае на каждой строке оказывается результат агрегации, полученный на множестве строк из [рамки окна](../syntax/window.md#frame). + +### Примеры + +```yql +SELECT + SUM(int_column) OVER w1 AS running_total, + SUM(int_column) OVER w2 AS total, +FROM my_table +WINDOW + w1 AS (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), + w2 AS (); +``` + + +## ROW_NUMBER {#row_number} + +Номер строки в рамках [раздела](../syntax/window.md#partition). Без аргументов. + +### Сигнатура + +```yql +ROW_NUMBER()->Uint64 +``` + +### Примеры + +```yql +SELECT + ROW_NUMBER() OVER w AS row_num +FROM my_table +WINDOW w AS (ORDER BY key); +``` + + +## LAG / LEAD {#lag-lead} + +Доступ к значению из строки [раздела](../syntax/window.md#partition), отстающей (`LAG`) или опережающей (`LEAD`) текущую на фиксированное число. В первом аргументе указывается выражение, к которому необходим доступ, а во втором — отступ в строках. Отступ можно не указывать, по умолчанию используется соседняя строка — предыдущая или следующая, соответственно, то есть подразумевается 1. В строках, для которых нет соседей с заданным расстоянием (например `LAG(expr, 3)` в первой и второй строках раздела), возвращается `NULL`. + +### Сигнатура + +```yql +LEAD(T[,Int32])->T? +LAG(T[,Int32])->T? +``` + +### Примеры + +```yql +SELECT + int_value - LAG(int_value) OVER w AS int_value_diff +FROM my_table +WINDOW w AS (ORDER BY key); +``` + +```yql +SELECT item, odd, LAG(item, 1) OVER w as lag1 FROM ( + SELECT item, item % 2 as odd FROM ( + SELECT AsList(1, 2, 3, 4, 5, 6, 7) as item + ) + FLATTEN BY item +) +WINDOW w As ( + PARTITION BY odd + ORDER BY item +); + +/* Output: +item odd lag1 +-------------------- +2 0 NULL +4 0 2 +6 0 4 +1 1 NULL +3 1 1 +5 1 3 +7 1 5 +*/ +``` + + +## FIRST_VALUE / LAST_VALUE + +Доступ к значениям из первой и последней (в порядке `ORDER BY` на окне) строк [рамки окна](../syntax/window.md#frame). Единственный аргумент - выражение, к которому необходим доступ. + +Опционально перед `OVER` может указываться дополнительный модификатор `IGNORE NULLS`, который меняет поведение функций на первое или последнее **не пустое** (то есть не `NULL`) значение среди строк рамки окна. Антоним этого модификатора — `RESPECT NULLS` является поведением по умолчанию и может не указываться. + +### Сигнатура + +```yql +FIRST_VALUE(T)->T? +LAST_VALUE(T)->T? +``` + +### Примеры + +```yql +SELECT + FIRST_VALUE(my_column) OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + +```yql +SELECT + LAST_VALUE(my_column) IGNORE NULLS OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + +## NTH_VALUE + +Доступ к значения из заданной строки (в порядке `ORDER BY` на окне) [рамки окна](../syntax/window.md#frame). Аргументы - выражение, к которому необходим доступ и номер строки, начиная с 1. + +Опционально перед `OVER` может указываться дополнительный модификатор `IGNORE NULLS`, который приводит к пропуску строк с NULL в значении первого аргумента. Антоним этого модификатора — `RESPECT NULLS` является поведением по умолчанию и может не указываться. + +### Сигнатура + +```yql +NTH_VALUE(T,N)->T? +``` + +### Примеры + +```yql +SELECT + NTH_VALUE(my_column, 2) OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + +```yql +SELECT + NTH_VALUE(my_column, 3) IGNORE NULLS OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + + +## RANK / DENSE_RANK / PERCENT_RANK {#rank} + +Пронумеровать группы соседних строк [раздела](../syntax/window.md#partition) с одинаковым значением выражения в аргументе. `DENSE_RANK` нумерует группы подряд, а `RANK` — пропускает `(N - 1)` значений, где `N` — число строк в предыдущей группе. `PERCENT_RANK` выдает относительный ранг текущей строки: `(RANK - 1)/(число строк в разделе - 1)`. + +При отсутствии аргумента использует порядок, указанный в секции `ORDER BY` определения окна. +Если аргумент отсутствует и `ORDER BY` не указан, то все строки считаются равными друг другу. + +{% note info %} + +Возможность передавать аргумент в `RANK`/`DENSE_RANK`/`PERCENT_RANK` является нестандартным расширением YQL. + +{% endnote %} + +### Сигнатура + +```yql +RANK([T])->Uint64 +DENSE_RANK([T])->Uint64 +PERCENT_RANK([T])->Double +``` + +### Примеры + +```yql +SELECT + RANK(my_column) OVER w +FROM my_table +WINDOW w AS (ORDER BY key); +``` + +```yql +SELECT + DENSE_RANK() OVER w +FROM my_table +WINDOW w AS (ORDER BY my_column); +``` + +```yql +SELECT + PERCENT_RANK() OVER w +FROM my_table +WINDOW w AS (ORDER BY my_column); +``` + + +## NTILE + +Распределяет строки упорядоченного [раздела](../syntax/window.md#partition) в заданное количество групп. Группы нумеруются, начиная с единицы. Для каждой строки функция NTILE возвращает номер группы,которой принадлежит строка. + +### Сигнатура + +```yql +NTILE(Uint64)->Uint64 +``` + +### Примеры + +```yql +SELECT + NTILE(10) OVER w AS group_num +FROM my_table +WINDOW w AS (ORDER BY key); +``` + + +## CUME_DIST + +Возвращает относительную позицию (> 0 и <= 1) строки в рамках [раздела](../syntax/window.md#partition). Без аргументов. + +### Сигнатура + +```yql +CUME_DIST()->Double +``` + +### Примеры + +```yql +SELECT + CUME_DIST() OVER w AS dist +FROM my_table +WINDOW w AS (ORDER BY key); +``` + + + +## SessionState() {#session-state} + +Нестандартная оконная функция `SessionState()` (без аргументов) позволяет получить состояние расчета сессий из [SessionWindow](../syntax/group_by.md#session-window) для текущей строки. + +Допускается только при наличии `SessionWindow()` в секции `PARTITION BY` определения окна. + diff --git a/ydb/docs/ru/core/yql/reference/essentials.base_rev b/ydb/docs/ru/core/yql/reference/essentials.base_rev new file mode 100644 index 000000000000..fceed7f7df6b --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/essentials.base_rev @@ -0,0 +1 @@ +9cf1bce240d3b7ba00185ee4715c7533ddf91cb9;yql/essentials/docs/ru diff --git a/ydb/docs/ru/core/yql/reference/index.md b/ydb/docs/ru/core/yql/reference/index.md index d5c159f81736..39f309966360 100644 --- a/ydb/docs/ru/core/yql/reference/index.md +++ b/ydb/docs/ru/core/yql/reference/index.md @@ -1,4 +1,26 @@ -{% include [intro.md](_includes/index/intro.md) %} +# YQL - Обзор + +*YQL* ({{ ydb-short-name }} Query Language) — универсальный декларативный язык запросов к YDB, диалект SQL. YQL создавался для работы с большими распределенными базами данных, и поэтому обладает рядом отличий от стандарта SQL. + +{% if oss == true and backend_name == "YDB" %} + +Инструменты работы с {{ ydb-short-name }} поддерживают интерфейсы отправки YQL-запросов и получения результатов их исполнения: + + + +- [{{ ydb-short-name }} CLI](../../reference/ydb-cli/index.md) +- [{{ ydb-short-name }} SDK](../../reference/ydb-sdk/index.md) + +В данном разделе документации находится справочник по YQL, который включает разделы: + +- [Типы данных](types/index.md) с описанием типов данных, применяемых в YQL +- [Синтаксис](syntax/index.md) с полным перечнем команд YQL +- [Встроенные функции](builtins/index.md) с описанием доступных встроенных функций + +Также вы можете пройти серию уроков, знакомящих вас с основными командами YQL, в разделе [Туториал YQL](../../dev/yql-tutorial/index.md). + +{% endif %} + + -{% include [intro.md](_includes/index/start.md) %} diff --git a/ydb/docs/ru/core/recipes/yql/accessing-json.md b/ydb/docs/ru/core/yql/reference/recipes/accessing-json.md similarity index 82% rename from ydb/docs/ru/core/recipes/yql/accessing-json.md rename to ydb/docs/ru/core/yql/reference/recipes/accessing-json.md index 63b01e54afd7..5f18e965f872 100644 --- a/ydb/docs/ru/core/recipes/yql/accessing-json.md +++ b/ydb/docs/ru/core/yql/reference/recipes/accessing-json.md @@ -2,8 +2,8 @@ YQL предоставляет два основных способа извлечения значений из JSON: -- Использование [**JSON-функций из SQL стандарта**](../../yql/reference/builtins/json.md). Этот подход рекомендуется для простых случаев и для команд, которые знакомы с ними по другим СУБД. -- Использование [**Yson UDF**](../../yql/reference/udf/list/yson.md), встроенных функций для работы со [списками](../../yql/reference/builtins/list.md) и [словарями](../../yql/reference/builtins/dict.md), а также [лямбд](../../yql/reference/syntax/expressions.md#lambda). Этот подход более гибкий и тесно интегрирован с системой типов данных {{ ydb-short-name }}, поэтому рекомендуется для сложных случаев. +- Использование [**JSON-функций из SQL стандарта**](../builtins/json.md). Этот подход рекомендуется для простых случаев и для команд, которые знакомы с ними по другим СУБД. +- Использование [**Yson UDF**](../udf/list/yson.md), встроенных функций для работы со [списками](../builtins/list.md) и [словарями](../builtins/dict.md), а также [лямбд](../syntax/expressions.md#lambda). Этот подход более гибкий и тесно интегрирован с системой типов данных {{ ydb-short-name }}, поэтому рекомендуется для сложных случаев. Ниже приведены рецепты, которые используют один и тот же входной JSON, чтобы показать, как использовать каждый из этих вариантов для проверки существования ключа, получения конкретного значения и извлечения поддерева. diff --git a/ydb/docs/ru/core/recipes/yql/index.md b/ydb/docs/ru/core/yql/reference/recipes/index.md similarity index 84% rename from ydb/docs/ru/core/recipes/yql/index.md rename to ydb/docs/ru/core/yql/reference/recipes/index.md index 2c79becdea63..fc587b97c304 100644 --- a/ydb/docs/ru/core/recipes/yql/index.md +++ b/ydb/docs/ru/core/yql/reference/recipes/index.md @@ -10,5 +10,5 @@ Смотрите также: -- [{#T}](../../yql/reference/index.md) -- [{#T}](../../dev/index.md) +- [{#T}](../index.md) +- [{#T}](../../../dev/index.md) diff --git a/ydb/docs/ru/core/recipes/yql/modifying-json.md b/ydb/docs/ru/core/yql/reference/recipes/modifying-json.md similarity index 88% rename from ydb/docs/ru/core/recipes/yql/modifying-json.md rename to ydb/docs/ru/core/yql/reference/recipes/modifying-json.md index 9b6fab310d32..871662c59bd8 100644 --- a/ydb/docs/ru/core/recipes/yql/modifying-json.md +++ b/ydb/docs/ru/core/yql/reference/recipes/modifying-json.md @@ -17,7 +17,7 @@ SELECT Yson::SerializeJson(Yson::From($result_dict)); ## Смотрите также -- [{#T}](../../yql/reference/udf/list/yson.md) -- [{#T}](../../yql/reference/builtins/list.md) -- [{#T}](../../yql/reference/builtins/dict.md) +- [{#T}](../udf/list/yson.md) +- [{#T}](../builtins/list.md) +- [{#T}](../builtins/dict.md) - [{#T}](accessing-json.md) diff --git a/ydb/docs/ru/core/recipes/yql/toc_p.yaml b/ydb/docs/ru/core/yql/reference/recipes/toc_i.yaml similarity index 100% rename from ydb/docs/ru/core/recipes/yql/toc_p.yaml rename to ydb/docs/ru/core/yql/reference/recipes/toc_i.yaml diff --git a/ydb/docs/ru/core/recipes/yql/ttl.md b/ydb/docs/ru/core/yql/reference/recipes/ttl.md similarity index 93% rename from ydb/docs/ru/core/recipes/yql/ttl.md rename to ydb/docs/ru/core/yql/reference/recipes/ttl.md index 35146ae2d0ce..354d95e3de65 100644 --- a/ydb/docs/ru/core/recipes/yql/ttl.md +++ b/ydb/docs/ru/core/yql/reference/recipes/ttl.md @@ -12,7 +12,7 @@ ALTER TABLE `mytable` SET (TTL = Interval("PT1H") ON created_at); {% note tip %} -`Interval` создается из строкового литерала в формате [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) с [некоторыми ограничениями](../../yql/reference/builtins/basic#data-type-literals). +`Interval` создается из строкового литерала в формате [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) с [некоторыми ограничениями](../builtins/basic#data-type-literals). {% endnote %} @@ -24,9 +24,9 @@ ALTER TABLE `mytable` SET (TTL = Interval("PT1H") ON modified_at AS SECONDS); ## Включение вытеснения данных во внешнее S3-совместимое хранилище {#enable-tiering-on-existing-tables} -{% include [OLTP_not_allow_note](../../_includes/not_allow_for_oltp_note.md) %} +{% include [OLTP_not_allow_note](../../../_includes/not_allow_for_oltp_note.md) %} -Для включения вытеснения требуется объект [external data source](../../concepts/datamodel/external_data_source.md), описывающий подключение к внешнему хранилищу. +Для включения вытеснения требуется объект [external data source](../../../concepts/datamodel/external_data_source.md), описывающий подключение к внешнему хранилищу. В приведённом ниже примере создаётся external data source `/Root/s3_cold_data`: он описывает подключение к бакету `test_cold_data`, расположенному в Yandex Object Storage, с авторизацией через статический ключ доступа, данные которого хранятся в секретах `access_key` и `secret_key`. ```yql diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_assets/join-YQL-06.png b/ydb/docs/ru/core/yql/reference/syntax/_assets/join-YQL-06.png similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_assets/join-YQL-06.png rename to ydb/docs/ru/core/yql/reference/syntax/_assets/join-YQL-06.png diff --git a/ydb/docs/ru/core/yql/reference/syntax/action.md b/ydb/docs/ru/core/yql/reference/syntax/action.md new file mode 100644 index 000000000000..6245a54a97ed --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/action.md @@ -0,0 +1,156 @@ +# ACTION + +## DEFINE ACTION {#define-action} + +Задает именованное действие, которое представляют собой параметризуемый блок из нескольких выражений верхнего уровня. + +### Синтаксис + +1. `DEFINE ACTION` — объявление действия. +1. [Имя действия](expressions.md#named-nodes), по которому объявляемое действие доступно далее для вызова. +1. В круглых скобках — список имен параметров. +1. Ключевое слово `AS`. +1. Список выражений верхнего уровня. +1. `END DEFINE` — маркер последнего выражения внутри действия. + +Один или более последних параметров могут быть помечены знаком вопроса `?` как необязательные. Если они не будут указаны при вызове, то им будет присвоено значение `NULL`. + +## DO {#do} + +Выполняет `ACTION` с указанными параметрами. + +### Синтаксис + +1. `DO` — выполнение действия. +1. Именованное выражение, по которому объявлено действие. +1. В круглых скобках — список значений для использования в роли параметров. + +`EMPTY_ACTION` — действие, которое ничего не выполняет. + +{% if feature_mapreduce %} + +{% note info %} + +В больших запросах объявление действий можно выносить в отдельные файлы и подключать их в основной запрос с помощью [EXPORT](export_import.md#export) + [IMPORT](export_import.md#import), чтобы вместо одного длинного текста получилось несколько логических частей, в которых проще ориентироваться. Важный нюанс: директива `USE my_cluster;` в импортирующем запросе не влияет на поведение объявленных в других файлах действий. + +{% endnote %} + +{% endif %} + +### Пример + +```yql +DEFINE ACTION $hello_world($name, $suffix?) AS + $name = $name ?? ($suffix ?? "world"); + SELECT "Hello, " || $name || "!"; +END DEFINE; + +DO EMPTY_ACTION(); +DO $hello_world(NULL); +DO $hello_world("John"); +DO $hello_world(NULL, "Earth"); +``` + + + +## BEGIN .. END DO {#begin} + +Выполнение действия без его объявления (анонимное действие). + +### Синтаксис + +1. `BEGIN`; +1. Список выражений верхнего уровня; +1. `END DO`. + +Анонимное действие не может содержать параметров. + +### Пример + +```yql +DO BEGIN + SELECT 1; + SELECT 2 -- здесь и в предыдущем примере ';' перед END можно не ставить +END DO +``` + +{% if feature_mapreduce %} + +## EVALUATE IF {#evaluate-if} + +`EVALUATE IF` — выполнение действия (action) в зависимости от выполнения условия. Далее указывается: + +1. Условие; +2. [DO](#do) с именем и параметрами действия или анонимным действием; +3. Опционально `ELSE` и следом второе `DO` для ситуации, когда условие не выполнено. + +## EVALUATE FOR {#evaluate-for} + +`EVALUATE FOR` — выполнение действия (action) для каждого элемента в списке. Далее указывается: + +1. [Именованное выражение](expressions.md#named-nodes), в которое будет подставляться каждый очередной элемент списка; +2. Ключевое слово `IN`; +3. Объявленное выше именованное выражение со списком, по которому будет выполняться действие. +4. [DO](#do) с именем и параметрами действия или анонимным действием, в параметрах можно использовать как текущий элемент из первого пункта, так и любые объявленные выше именованные выражения, в том числе сам список. +5. Опционально `ELSE` и следом второе `DO` для ситуации, когда список пуст. + +### Примеры + +```yql +DEFINE ACTION $hello() AS + SELECT "Hello!"; +END DEFINE; + +DEFINE ACTION $bye() AS + SELECT "Bye!"; +END DEFINE; + +EVALUATE IF RANDOM(0) > 0.5 + DO $hello() +ELSE + DO $bye(); + +EVALUATE IF RANDOM(0) > 0.1 DO BEGIN + SELECT "Hello!"; +END DO; + +EVALUATE FOR $i IN AsList(1, 2, 3) DO BEGIN + SELECT $i; +END DO; +``` + +```yql +-- скопировать таблицу $input в $count новых таблиц +$count = 3; +$input = "my_input"; +$inputs = ListReplicate($input, $count); +$outputs = ListMap( + ListFromRange(0, $count), + ($i) -> { + RETURN "tmp/out_" || CAST($i as String) + } +); +$pairs = ListZip($inputs, $outputs); + +DEFINE ACTION $copy_table($pair) as + $input = $pair.0; + $output = $pair.1; + INSERT INTO $output WITH TRUNCATE + SELECT * FROM $input; +END DEFINE; + +EVALUATE FOR $pair IN $pairs + DO $copy_table($pair) +ELSE + DO EMPTY_ACTION(); -- такой ELSE можно было не указывать, + -- ничего не делать подразумевается по умолчанию +``` + +{% note info %} + +Стоит учитывать, что `EVALUATE` выполняется до начала работы основного запроса. Также в рамках вычисления предиката в `EVALUATE IF` или списка в `EVALUATE FOR` невозможно использование {% if feature_temp_table %}[анонимных таблиц](select/temporary_table.md){% else %} анонимных таблиц{% endif %}. + +{% endnote %} + + +{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-async-replication.md b/ydb/docs/ru/core/yql/reference/syntax/alter-async-replication.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-async-replication.md rename to ydb/docs/ru/core/yql/reference/syntax/alter-async-replication.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-group.md b/ydb/docs/ru/core/yql/reference/syntax/alter-group.md similarity index 89% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-group.md rename to ydb/docs/ru/core/yql/reference/syntax/alter-group.md index 84b067d74d6e..b74298e0630f 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-group.md +++ b/ydb/docs/ru/core/yql/reference/syntax/alter-group.md @@ -14,4 +14,4 @@ ALTER GROUP role_name DROP USER user_name [, ... ] ## Встроенные группы -{% include [!](_includes/initial_groups_and_users.md) %} +{% include [!](../_includes/initial_groups_and_users.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-resource-pool-classifier.md b/ydb/docs/ru/core/yql/reference/syntax/alter-resource-pool-classifier.md similarity index 61% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-resource-pool-classifier.md rename to ydb/docs/ru/core/yql/reference/syntax/alter-resource-pool-classifier.md index 38f231e80f66..b5b42e2dc5b5 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-resource-pool-classifier.md +++ b/ydb/docs/ru/core/yql/reference/syntax/alter-resource-pool-classifier.md @@ -46,7 +46,9 @@ GRANT 'ALL' ON `/my_db` TO `user1@domain`; ## Параметры -{% include [x](_includes/resource_pool_classifier_parameters.md) %} +* `RANK` (Int64) — опциональное поле, задающее порядок выбора классификатора пула ресурсов. Если значение не указано, берётся максимальный существующий `RANK` и к нему прибавляется 1000. Допустимые значения: уникальное число в диапазоне $[0, 2^{63}-1]$. +* `RESOURCE_POOL` (String) — обязательное поле, задающее имя пула ресурсов, в который будут отправлены запросы, удовлетворяющие критериям классификатора. +* `MEMBER_NAME` (String) — опциональное поле, определяющее, какой пользователь или группа пользователей будут отправлены в указанный пул ресурсов. Если поле не указано, классификатор игнорирует `MEMBER_NAME`, и классификация осуществляется по другим признакам. ## См. также diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/resource_pool_parameters.md b/ydb/docs/ru/core/yql/reference/syntax/alter-resource-pool.md similarity index 62% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/resource_pool_parameters.md rename to ydb/docs/ru/core/yql/reference/syntax/alter-resource-pool.md index 4739c90250c0..65af497b2074 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/resource_pool_parameters.md +++ b/ydb/docs/ru/core/yql/reference/syntax/alter-resource-pool.md @@ -1,7 +1,61 @@ +# ALTER RESOURCE POOL + +`ALTER RESOURCE POOL` изменяет определение [пула ресурсов](../../../concepts/glossary.md#resource-pool.md). + +## Синтаксис + +### Изменение параметров + +Синтаксис для изменения любого параметра пула ресурсов выглядит следующим образом: + +```yql +ALTER RESOURCE POOL SET ( = ); +``` + +`` — имя параметра, `` — его новое значение. + +Например, такая команда включит ограничение на число параллельных запросов, равное 100: + +```yql +ALTER RESOURCE POOL olap SET (CONCURRENT_QUERY_LIMIT = "100"); +``` + +### Сброс параметров + +Команда для сброса параметра пула ресурсов выглядит следующим образом: + +```yql +ALTER RESOURCE POOL RESET (); +``` + +`````` — имя параметра. + +Например, такая команда сбросит настройки `TOTAL_CPU_LIMIT_PERCENT_PER_NODE` для пула ресурсов: + +```yql +ALTER RESOURCE POOL olap RESET (TOTAL_CPU_LIMIT_PERCENT_PER_NODE); +``` + +## Разрешения + +Требуется [разрешение](grant.md#permissions-list) `ALTER SCHEMA` на пул ресурсов в директории `.metadata/workload_manager/pools`, пример выдачи такого разрешения: + +```yql +GRANT 'ALTER SCHEMA' ON `.metadata/workload_manager/pools/olap_pool` TO `user1@domain`; +``` + +## Параметры + * `CONCURRENT_QUERY_LIMIT` (Int32) — опциональное поле, задающее количество параллельно выполняющихся запросов в пуле ресурсов. Если значение `-1`, то ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 2^{31}-1]$. * `QUEUE_SIZE` (Int32) — опциональное поле, определяющее размер очереди ожидания. Всего в системе может находиться не более чем $CONCURRENT\_QUERY\_LIMIT + QUEUE\_SIZE$ запросов одновременно. Если значение `-1`, ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 2^{31}-1]$. * `DATABASE_LOAD_CPU_THRESHOLD` (Int32) — опциональное поле, задающее порог загрузки CPU всей базы данных, после которого запросы не отправляются на выполнение и остаются в очереди. Если значение `-1`, ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 100]$. * `QUERY_MEMORY_LIMIT_PERCENT_PER_NODE` (Double) — опциональное поле, определяющее процент доступной памяти на узле, который может использовать запрос в данном пуле ресурсов. Если значение `-1`, действует ограничение на общую доступную память между всеми запросами. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 100]$. * `TOTAL_CPU_LIMIT_PERCENT_PER_NODE` (Double) — опциональное поле, задающее процент доступного CPU, который могут использовать все запросы на узле в данном пуле ресурсов. Если значение `-1`, ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 100]$. * `QUERY_CPU_LIMIT_PERCENT_PER_NODE` (Double) — опциональное поле, определяющее процент доступного CPU на узле для одного запроса в пуле ресурсов. Если значение `-1`, ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 100]$. -* `RESOURCE_WEIGHT` (Int32) — опциональное поле, задающее веса для распределения ресурсов между пулами. Если значение `-1`, веса не используются. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 2^{31}-1]$. \ No newline at end of file +* `RESOURCE_WEIGHT` (Int32) — опциональное поле, задающее веса для распределения ресурсов между пулами. Если значение `-1`, веса не используются. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 2^{31}-1]$. + +## См. также + +* [{#T}](../../../dev/resource-consumption-management.md) +* [{#T}](create-resource-pool.md) +* [{#T}](drop-resource-pool.md) \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-topic.md b/ydb/docs/ru/core/yql/reference/syntax/alter-topic.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-topic.md rename to ydb/docs/ru/core/yql/reference/syntax/alter-topic.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-user.md b/ydb/docs/ru/core/yql/reference/syntax/alter-user.md similarity index 92% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-user.md rename to ydb/docs/ru/core/yql/reference/syntax/alter-user.md index 10e846b4fcf0..5dbfe0477e99 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-user.md +++ b/ydb/docs/ru/core/yql/reference/syntax/alter-user.md @@ -18,4 +18,4 @@ ALTER USER user_name [ WITH ] option [ ... ] ## Встроенные пользователи -{% include [!](_includes/initial_groups_and_users.md) %} +{% include [!](../_includes/initial_groups_and_users.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-view.md b/ydb/docs/ru/core/yql/reference/syntax/alter-view.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-view.md rename to ydb/docs/ru/core/yql/reference/syntax/alter-view.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/changefeed.md b/ydb/docs/ru/core/yql/reference/syntax/alter_table/changefeed.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/changefeed.md rename to ydb/docs/ru/core/yql/reference/syntax/alter_table/changefeed.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/columns.md b/ydb/docs/ru/core/yql/reference/syntax/alter_table/columns.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/columns.md rename to ydb/docs/ru/core/yql/reference/syntax/alter_table/columns.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/family.md b/ydb/docs/ru/core/yql/reference/syntax/alter_table/family.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/family.md rename to ydb/docs/ru/core/yql/reference/syntax/alter_table/family.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/index.md b/ydb/docs/ru/core/yql/reference/syntax/alter_table/index.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/index.md rename to ydb/docs/ru/core/yql/reference/syntax/alter_table/index.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/rename.md b/ydb/docs/ru/core/yql/reference/syntax/alter_table/rename.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/rename.md rename to ydb/docs/ru/core/yql/reference/syntax/alter_table/rename.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/secondary_index.md b/ydb/docs/ru/core/yql/reference/syntax/alter_table/secondary_index.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/secondary_index.md rename to ydb/docs/ru/core/yql/reference/syntax/alter_table/secondary_index.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/set.md b/ydb/docs/ru/core/yql/reference/syntax/alter_table/set.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/set.md rename to ydb/docs/ru/core/yql/reference/syntax/alter_table/set.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/toc_i.yaml b/ydb/docs/ru/core/yql/reference/syntax/alter_table/toc_i.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/toc_i.yaml rename to ydb/docs/ru/core/yql/reference/syntax/alter_table/toc_i.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/toc_p.yaml b/ydb/docs/ru/core/yql/reference/syntax/alter_table/toc_p.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/alter_table/toc_p.yaml rename to ydb/docs/ru/core/yql/reference/syntax/alter_table/toc_p.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/analyze.md b/ydb/docs/ru/core/yql/reference/syntax/analyze.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/analyze.md rename to ydb/docs/ru/core/yql/reference/syntax/analyze.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/commit.md b/ydb/docs/ru/core/yql/reference/syntax/commit.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/commit.md rename to ydb/docs/ru/core/yql/reference/syntax/commit.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-async-replication.md b/ydb/docs/ru/core/yql/reference/syntax/create-async-replication.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-async-replication.md rename to ydb/docs/ru/core/yql/reference/syntax/create-async-replication.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-external-data-source.md b/ydb/docs/ru/core/yql/reference/syntax/create-external-data-source.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-external-data-source.md rename to ydb/docs/ru/core/yql/reference/syntax/create-external-data-source.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-external-table.md b/ydb/docs/ru/core/yql/reference/syntax/create-external-table.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-external-table.md rename to ydb/docs/ru/core/yql/reference/syntax/create-external-table.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-group.md b/ydb/docs/ru/core/yql/reference/syntax/create-group.md similarity index 84% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-group.md rename to ydb/docs/ru/core/yql/reference/syntax/create-group.md index b2b55f7abc95..1c12c79c0e56 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-group.md +++ b/ydb/docs/ru/core/yql/reference/syntax/create-group.md @@ -12,4 +12,4 @@ CREATE GROUP group_name ## Встроенные группы -{% include [!](_includes/initial_groups_and_users.md) %} +{% include [!](../_includes/initial_groups_and_users.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-object-type-secret-access.md b/ydb/docs/ru/core/yql/reference/syntax/create-object-type-secret-access.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-object-type-secret-access.md rename to ydb/docs/ru/core/yql/reference/syntax/create-object-type-secret-access.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-object-type-secret.md b/ydb/docs/ru/core/yql/reference/syntax/create-object-type-secret.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-object-type-secret.md rename to ydb/docs/ru/core/yql/reference/syntax/create-object-type-secret.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-resource-pool-classifier.md b/ydb/docs/ru/core/yql/reference/syntax/create-resource-pool-classifier.md similarity index 74% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-resource-pool-classifier.md rename to ydb/docs/ru/core/yql/reference/syntax/create-resource-pool-classifier.md index bd433e71176d..69db9dadb2bd 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-resource-pool-classifier.md +++ b/ydb/docs/ru/core/yql/reference/syntax/create-resource-pool-classifier.md @@ -14,7 +14,9 @@ WITH ( [= ] [, ... ] ) ### Параметры -{% include [x](_includes/resource_pool_classifier_parameters.md) %} +* `RANK` (Int64) — опциональное поле, задающее порядок выбора классификатора пула ресурсов. Если значение не указано, берётся максимальный существующий `RANK` и к нему прибавляется 1000. Допустимые значения: уникальное число в диапазоне $[0, 2^{63}-1]$. +* `RESOURCE_POOL` (String) — обязательное поле, задающее имя пула ресурсов, в который будут отправлены запросы, удовлетворяющие критериям классификатора. +* `MEMBER_NAME` (String) — опциональное поле, определяющее, какой пользователь или группа пользователей будут отправлены в указанный пул ресурсов. Если поле не указано, классификатор игнорирует `MEMBER_NAME`, и классификация осуществляется по другим признакам. ## Замечания {#remarks} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-resource-pool.md b/ydb/docs/ru/core/yql/reference/syntax/create-resource-pool.md similarity index 51% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-resource-pool.md rename to ydb/docs/ru/core/yql/reference/syntax/create-resource-pool.md index 45e95ea76abf..ad155f250bec 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-resource-pool.md +++ b/ydb/docs/ru/core/yql/reference/syntax/create-resource-pool.md @@ -14,7 +14,13 @@ WITH ( [= ] [, ... ] ) ### Параметры {#parameters} -{% include [x](_includes/resource_pool_parameters.md) %} +* `CONCURRENT_QUERY_LIMIT` (Int32) — опциональное поле, задающее количество параллельно выполняющихся запросов в пуле ресурсов. Если значение `-1`, то ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 2^{31}-1]$. +* `QUEUE_SIZE` (Int32) — опциональное поле, определяющее размер очереди ожидания. Всего в системе может находиться не более чем $CONCURRENT\_QUERY\_LIMIT + QUEUE\_SIZE$ запросов одновременно. Если значение `-1`, ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 2^{31}-1]$. +* `DATABASE_LOAD_CPU_THRESHOLD` (Int32) — опциональное поле, задающее порог загрузки CPU всей базы данных, после которого запросы не отправляются на выполнение и остаются в очереди. Если значение `-1`, ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 100]$. +* `QUERY_MEMORY_LIMIT_PERCENT_PER_NODE` (Double) — опциональное поле, определяющее процент доступной памяти на узле, который может использовать запрос в данном пуле ресурсов. Если значение `-1`, действует ограничение на общую доступную память между всеми запросами. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 100]$. +* `TOTAL_CPU_LIMIT_PERCENT_PER_NODE` (Double) — опциональное поле, задающее процент доступного CPU, который могут использовать все запросы на узле в данном пуле ресурсов. Если значение `-1`, ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 100]$. +* `QUERY_CPU_LIMIT_PERCENT_PER_NODE` (Double) — опциональное поле, определяющее процент доступного CPU на узле для одного запроса в пуле ресурсов. Если значение `-1`, ограничений нет. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 100]$. +* `RESOURCE_WEIGHT` (Int32) — опциональное поле, задающее веса для распределения ресурсов между пулами. Если значение `-1`, веса не используются. Значение по умолчанию: `-1`. Допустимые значения: $-1, [0, 2^{31}-1]$. ## Замечания {#remark} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-topic.md b/ydb/docs/ru/core/yql/reference/syntax/create-topic.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-topic.md rename to ydb/docs/ru/core/yql/reference/syntax/create-topic.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-user.md b/ydb/docs/ru/core/yql/reference/syntax/create-user.md similarity index 94% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-user.md rename to ydb/docs/ru/core/yql/reference/syntax/create-user.md index 7faa39fced1d..fcaa87fb7e6f 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-user.md +++ b/ydb/docs/ru/core/yql/reference/syntax/create-user.md @@ -19,4 +19,4 @@ CREATE USER user_name [option] ## Встроенные пользователи -{% include [!](_includes/initial_groups_and_users.md) %} +{% include [!](../_includes/initial_groups_and_users.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create-view.md b/ydb/docs/ru/core/yql/reference/syntax/create-view.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create-view.md rename to ydb/docs/ru/core/yql/reference/syntax/create-view.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/family.md b/ydb/docs/ru/core/yql/reference/syntax/create_table/family.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/family.md rename to ydb/docs/ru/core/yql/reference/syntax/create_table/family.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/index.md b/ydb/docs/ru/core/yql/reference/syntax/create_table/index.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/index.md rename to ydb/docs/ru/core/yql/reference/syntax/create_table/index.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md b/ydb/docs/ru/core/yql/reference/syntax/create_table/secondary_index.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/secondary_index.md rename to ydb/docs/ru/core/yql/reference/syntax/create_table/secondary_index.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/temporary.md b/ydb/docs/ru/core/yql/reference/syntax/create_table/temporary.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/temporary.md rename to ydb/docs/ru/core/yql/reference/syntax/create_table/temporary.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/toc_i.yaml b/ydb/docs/ru/core/yql/reference/syntax/create_table/toc_i.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/toc_i.yaml rename to ydb/docs/ru/core/yql/reference/syntax/create_table/toc_i.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/toc_p.yaml b/ydb/docs/ru/core/yql/reference/syntax/create_table/toc_p.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/toc_p.yaml rename to ydb/docs/ru/core/yql/reference/syntax/create_table/toc_p.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/with.md b/ydb/docs/ru/core/yql/reference/syntax/create_table/with.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table/with.md rename to ydb/docs/ru/core/yql/reference/syntax/create_table/with.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/declare/general.md b/ydb/docs/ru/core/yql/reference/syntax/declare.md similarity index 61% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/declare/general.md rename to ydb/docs/ru/core/yql/reference/syntax/declare.md index 4a17a181522e..704e831a1f07 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/declare/general.md +++ b/ydb/docs/ru/core/yql/reference/syntax/declare.md @@ -1,6 +1,7 @@ + # DECLARE -Объявляет типизированное [именованное выражение](../../expressions.md#named-nodes), значение для которого будет передано параметром отдельно от текста запроса. Параметризация дает возможность отделить разработку аналитического решения задачи от её запуска с различными вариантами входных значений. +Объявляет типизированное [именованное выражение](expressions.md#named-nodes), значение для которого будет передано параметром отдельно от текста запроса. Параметризация дает возможность отделить разработку аналитического решения задачи от её запуска с различными вариантами входных значений. Для транзакционной нагрузки использование параметров позволяет избежать перекомпиляции запросов при повторении однотипных вызовов, снижая потребление ресурсов сервера, и исключая время компиляции из общего времени исполнения запроса. @@ -15,14 +16,14 @@ DECLARE $named-node AS data_type; 1. Ключевое слово `DECLARE`. 1. `$named-node` — имя, по которому можно будет обращаться к переданному значению, должно начинаться с символа `$`. 1. Ключевое слово `AS`. -1. `data_type` — тип данных [в виде строки в принятом формате](../../../types/type_string.md). +1. `data_type` — тип данных [в виде строки в принятом формате](../types/type_string.md). Допустимы только сериализуемые типы данных: -* [Примитивные типы](../../../types/primitive.md). -* [Опциональные типы](../../../types/optional.md). -* [Контейнеры](../../../types/containers.md) за исключением `Stream`. -* `Void` и `Null`— поддерживаемые [специальные типы](../../../types/special.md). +* [Примитивные типы](../types/primitive.md). +* [Опциональные типы](../types/optional.md). +* [Контейнеры](../types/containers.md) за исключением `Stream`. +* `Void` и `Null`— поддерживаемые [специальные типы](../types/special.md). ## Пример @@ -34,4 +35,5 @@ DECLARE $z AS List; SELECT $x, $y, $z; ``` -Примеры передачи параметров для DECLARE можно найти [здесь](../../../types/_includes/json.md). +Примеры передачи параметров для DECLARE можно найти [здесь](../types/json.md). + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/delete.md b/ydb/docs/ru/core/yql/reference/syntax/delete.md similarity index 82% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/delete.md rename to ydb/docs/ru/core/yql/reference/syntax/delete.md index 39075f4c1fb3..87c271d0fcfb 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/delete.md +++ b/ydb/docs/ru/core/yql/reference/syntax/delete.md @@ -1,18 +1,19 @@ + # DELETE FROM {% if oss == true and backend_name == "YDB" %} {% note warning %} -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} +{% include [OLAP_not_allow_text](../../../_includes/not_allow_for_olap_text.md) %} -Вместо `DELETE FROM` для удаления данных из колоночных таблиц можно воспользоваться механизмом удаления строк по времени — [TTL](../../../../concepts/ttl.md). TTL можно задать при [создании](../create_table/index.md) таблицы через `CREATE TABLE` или [измененить позже](../alter_table/index.md) через `ALTER TABLE`. +Вместо `DELETE FROM` для удаления данных из колоночных таблиц можно воспользоваться механизмом удаления строк по времени — [TTL](../../../concepts/ttl.md). TTL можно задать при [создании](create_table/index.md) таблицы через `CREATE TABLE` или [измененить позже](alter_table/index.md) через `ALTER TABLE`. {% endnote %} {% endif %} -Удаляет строки из строковой таблицы, подходящие под условия, заданные в `WHERE`.{% if feature_mapreduce %} Таблица ищется по имени в базе данных, заданной оператором [USE](../use.md).{% endif %} +Удаляет строки из строковой таблицы, подходящие под условия, заданные в `WHERE`.{% if feature_mapreduce %} Таблица ищется по имени в базе данных, заданной оператором [USE](use.md).{% endif %} ## Пример @@ -38,3 +39,5 @@ $to_delete = ( DELETE FROM my_table ON SELECT * FROM $to_delete; ``` + + diff --git a/ydb/docs/ru/core/yql/reference/syntax/discard.md b/ydb/docs/ru/core/yql/reference/syntax/discard.md new file mode 100644 index 000000000000..4ccf9cc05679 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/discard.md @@ -0,0 +1,32 @@ + +# DISCARD + +Вычисляет {% if select_command == "SELECT STREAM" %}[`SELECT STREAM`](select_stream.md){% else %}[`SELECT`](select/index.md){% endif %}{% if feature_mapreduce %}{% if reduce_command %}, [`{{ reduce_command }}`](reduce.md){% endif %} или [`{{ process_command }}`](process.md){% endif %}, но не возвращает результат ни в клиент, ни в таблицу. {% if feature_mapreduce %}Не может быть задано одновременно с [INTO RESULT](into_result.md).{% endif %} + +Полезно использовать в сочетании с [`Ensure`](../builtins/basic.md#ensure) для проверки выполнения пользовательских условий на финальный результат вычислений. + +{% if select_command != true or select_command == "SELECT" %} + +### Примеры + +```yql +DISCARD SELECT 1; +``` + +```yql +INSERT INTO result_table WITH TRUNCATE +SELECT * FROM +my_table +WHERE value % 2 == 0; + +COMMIT; + +DISCARD SELECT Ensure( + 0, -- will discard result anyway + COUNT(*) > 1000, + "Too small result table, got only " || CAST(COUNT(*) AS String) || " rows" +) FROM result_table; + +``` + +{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-async-replication.md b/ydb/docs/ru/core/yql/reference/syntax/drop-async-replication.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-async-replication.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-async-replication.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-external-data-source.md b/ydb/docs/ru/core/yql/reference/syntax/drop-external-data-source.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-external-data-source.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-external-data-source.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-external-table.md b/ydb/docs/ru/core/yql/reference/syntax/drop-external-table.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-external-table.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-external-table.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-group.md b/ydb/docs/ru/core/yql/reference/syntax/drop-group.md similarity index 88% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-group.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-group.md index ceb745e92901..dd338bd67e4c 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-group.md +++ b/ydb/docs/ru/core/yql/reference/syntax/drop-group.md @@ -13,4 +13,4 @@ DROP GROUP [ IF EXISTS ] group_name [, ...] ## Встроенные группы -{% include [!](_includes/initial_groups_and_users.md) %} +{% include [!](../_includes/initial_groups_and_users.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-object-type-secret-access.md b/ydb/docs/ru/core/yql/reference/syntax/drop-object-type-secret-access.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-object-type-secret-access.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-object-type-secret-access.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-object-type-secret.md b/ydb/docs/ru/core/yql/reference/syntax/drop-object-type-secret.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-object-type-secret.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-object-type-secret.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-resource-pool-classifier.md b/ydb/docs/ru/core/yql/reference/syntax/drop-resource-pool-classifier.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-resource-pool-classifier.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-resource-pool-classifier.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-resource-pool.md b/ydb/docs/ru/core/yql/reference/syntax/drop-resource-pool.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-resource-pool.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-resource-pool.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-topic.md b/ydb/docs/ru/core/yql/reference/syntax/drop-topic.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-topic.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-topic.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-user.md b/ydb/docs/ru/core/yql/reference/syntax/drop-user.md similarity index 92% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-user.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-user.md index ce15db9828a0..606bec8eae81 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-user.md +++ b/ydb/docs/ru/core/yql/reference/syntax/drop-user.md @@ -13,4 +13,4 @@ DROP USER [ IF EXISTS ] user_name [, ...] ## Встроенные пользователи -{% include [!](_includes/initial_groups_and_users.md) %} +{% include [!](../_includes/initial_groups_and_users.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-view.md b/ydb/docs/ru/core/yql/reference/syntax/drop-view.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/drop-view.md rename to ydb/docs/ru/core/yql/reference/syntax/drop-view.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/drop_table.md b/ydb/docs/ru/core/yql/reference/syntax/drop_table.md similarity index 84% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/drop_table.md rename to ydb/docs/ru/core/yql/reference/syntax/drop_table.md index 1d40419dffc0..8831b4e76d1f 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/drop_table.md +++ b/ydb/docs/ru/core/yql/reference/syntax/drop_table.md @@ -1,6 +1,7 @@ + # DROP TABLE -Удаляет указанную строковую или колоночную таблицу.{% if feature_mapreduce %} Таблица по имени ищется в базе данных, заданной оператором [USE](../use.md).{% endif %} +Удаляет указанную строковую или колоночную таблицу.{% if feature_mapreduce %} Таблица по имени ищется в базе данных, заданной оператором [USE](use.md).{% endif %} Если таблицы с таким именем не существует, возвращается ошибка. @@ -9,3 +10,5 @@ ```yql DROP TABLE my_table; ``` + + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/export_import.md b/ydb/docs/ru/core/yql/reference/syntax/export_import.md similarity index 71% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/export_import.md rename to ydb/docs/ru/core/yql/reference/syntax/export_import.md index 36350c84140d..9f60ed1b9196 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/export_import.md +++ b/ydb/docs/ru/core/yql/reference/syntax/export_import.md @@ -2,7 +2,7 @@ Механизм для выноса части запроса в отдельный приложенный файл: -* [PRAGMA Library](../pragma.md#library) помечает приложенный файл как доступный для импорта. +* [PRAGMA Library](pragma.md#library) помечает приложенный файл как доступный для импорта. ## `Export` * В `EXPORT $my_symbol1, $my_symbol2, ...;` перечисляется список именованных выражений в библиотеке, доступных для импорта. @@ -12,13 +12,13 @@ {% note info %} -В библиотеку могут быть вынесены [лямбды](../expressions.md#lambda), [действия](../action.md){% if feature_subquery %}, [именованные подзапросы](../subquery.md){% endif %}, константы и выражения, но __не подзапросы и не агрегатные функции__. +В библиотеку могут быть вынесены [лямбды](expressions.md#lambda), [действия](action.md){% if feature_subquery %}, [именованные подзапросы](subquery.md){% endif %}, константы и выражения, но __не подзапросы и не агрегатные функции__. {% endnote %} {% note warning %} -Файл, на который ссылается [PRAGMA Library](../pragma.md#library) должен быть приложен к запросу. __Использовать для этой цели [PRAGMA File](../pragma.md#file) нельзя__. +Файл, на который ссылается [PRAGMA Library](pragma.md#library) должен быть приложен к запросу. __Использовать для этой цели [PRAGMA File](pragma.md#file) нельзя__. {% endnote %} @@ -57,3 +57,5 @@ FROM ( SELECT 3 AS x ) ``` + + diff --git a/ydb/docs/ru/core/yql/reference/syntax/expressions.md b/ydb/docs/ru/core/yql/reference/syntax/expressions.md new file mode 100644 index 000000000000..bba831c3f8b3 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/expressions.md @@ -0,0 +1,600 @@ +# Выражения + + + +## Конкатенация строк {#concatenation} + +Выполняется через бинарный оператор `||`. + +Как и у других бинарных операторов, если в данных с одной из сторон оказался `NULL`, то и результат будет `NULL`. + +Не следует путать этот оператор с логическим «или», в SQL оно обозначается ключевым словом `OR`. Также не стоит пытаться делать конкатенацию через `+`. + +### Примеры + +```yql +SELECT "fo" || "o"; +``` + + +## Проверка строки на соответствие шаблону {#check-match} + +`REGEXP` и `RLIKE` являются алиасами и представляют собой короткий способ записи для вызова [Re2::Grep](../udf/list/re2.md#match). `MATCH` — аналогично для [Re2::Match](../udf/list/re2.md#match). + +`LIKE` работает по следующим принципам: + +* В шаблонах используется два спецсимвола: + + * `%` — ноль и более любых символов; + * `_` — ровно один любой символ. + + Все остальные символы выступают как литералы, то есть обозначают сами себя. + +* В отличие от `REGEXP`, с шаблоном `LIKE` строка должна совпасть полностью. Например, для поиска подстроки в середине нужно добавить `%` в начале и в конце шаблона. +* `ILIKE` является не чувствительной к регистру версией `LIKE`. +* Если `LIKE` применяется к ключевой колонке сортированной таблицы и шаблон начинается не со спецсимвола, то фильтрация по префиксу опускается прямо до кластера, что в некоторых случаях позволяет не сканировать всю таблицу целиком. Для `ILIKE` данная оптимизация отключена. +* Чтобы заэкранировать спецсимволы, необходимо после шаблона указать символ для экранирования с помощью ключевого слова `ESCAPE '?'`. Вместо `?` можно использовать любой символ, кроме `%`, `_` и `\`. Например, если в качестве экранирующего символа используется знак вопроса, то выражения `?%`, `?_` и `??` в шаблоне совпадут со своим вторым символом: процент, подчеркивание и знак вопроса, соответственно. По умолчанию экранирующий символ не определен. + +Наиболее популярный способ использования ключевых слов `LIKE` и `REGEXP` — фильтрация таблицы в выражениях с `WHERE`. Однако ограничения на использование шаблонов именно в этом контексте нет, и их можно использовать в большинстве контекстов при работе со строками, наравне, например, с конкатенацией с помощью `||`. + +### Примеры + +```yql +SELECT * FROM my_table +WHERE string_column REGEXP '\\d+'; +-- второй слеш нужен, так как все +-- стандартные строковые литералы в SQL +-- могут принимать С-escaped строки +``` + +```yql +SELECT + string_column LIKE '___!_!_!_!!!!!!' ESCAPE '!' + -- ищет строку из ровно 9 символов: + -- 3 произвольных, + -- затем 3 подчеркивания + -- и 3 восклицательных знака +FROM my_table; +``` + +```yql +SELECT * FROM my_table +WHERE key LIKE 'foo%bar'; +-- при наличии сортировки таблицы по key просканирует только ключи, +-- начинающиеся на foo, и затем среди них +-- оставит только заканчивающиеся на bar +``` + + +## Операторы + +### Арифметические операторы {#math-operators} + +Операторы `+`, `-`, `*`, `/`, `%` определены для [примитивных типов данных](../types/primitive.md), являющихся разновидностями чисел. + +Для типа данных Decimal используется банковское округление (до ближайшего четного). + +#### Примеры + +```yql +SELECT 2 + 2; +``` + +```yql +SELECT 0.0 / 0.0; +``` + +### Операторы сравнения {#comparison-operators} + +Операторы `=`, `==`, `!=`, `<>`, `>`, `<` определены для: + +* Примитивных типов данных за исключением Yson и Json. +* Кортежей и структур с одинаковым набором полей. Для структур не определен порядок, но можно проверять на (не-)равенство, а кортежи сравниваются поэлементно слева направо. + +#### Примеры + +```yql +SELECT 2 > 1; +``` + +### Логические операторы {#logic-operators} + +С помощью операторов `AND`, `OR`, `XOR` осуществляются логические операции над булевыми значениями (`Bool`). + +#### Примеры + +```yql +SELECT 3 > 0 AND false; +``` + +### Битовые операторы {#bit-operators} + +Битовые операции над числами: + +* `&`, `|`, `^` — AND, OR и XOR соответственно. Не следует путать битовые операции с аналогичными ключевыми словами. Ключевые слова `AND`, `OR` и `XOR` используются *только для булевых значений*, но не для чисел; +* ` ~ ` — отрицание; +* `<<`, `>>` — сдвиги влево-вправо; +* `|<<`, `>>|` — кольцевые сдвиги влево-вправо. + +#### Примеры + +```yql +SELECT + key << 10 AS key, + ~value AS value +FROM my_table; +``` + +### Приоритет и ассоциативность операторов {#operator-priority} + +Приоритет оператора определяет порядок вычисления выражения содержащего разные операторы. +Например, выражение `1 + 2 * 3` вычисляется как `1 + (2 * 3)`, +поскольку приоритет оператора умножения больше приоритета оператора сложения. + +Ассоциативность определяет порядок вычисления в выражениях содержащих операторы одного типа. +Например, выражение `1 + 2 + 3` вычисляется как `(1 + 2) + 3`, поскольку оператор сложения является лево-ассоциативным. +С другой стороны, выражение `a ?? b ?? c` вычисляется как `a ?? (b ?? c)` из-за право-ассоциативности оператора `??` + +В таблице ниже указаны приоритет и ассоциативность операторов языка YQL. +Операторы в таблице перечислены в порядке убывания приоритета. + +| Приоритет | Оператор | Описание | Ассоциативность | +| --- | --- | --- | --- | +| 1 | `a[], a.foo, a()` | Обращение к элементу контейнера, вызов функции | Левая | +| 2 | `+a, -a, ~a, NOT a` | Унарные операторы: плюс, минус, битовое и логическое отрицание | Правая | +| 3 | `a\|\|b` | [Конкатенация строк](#concatenation) | Левая | +| 4 | `a*b, a/b, a%b` | Умножение,деление, остаток от деления | Левая | +| 5 | `a+b, a-b` | Сложение / вычитание | Левая | +| 6 | `a ?? b` | Операторная форма записи [NVL/COALESCE](../builtins/basic.md#coalesce) | Правая | +| 7 | `a<>b, a\|<>\|b,` `a\|b, a^b, a&b` | Сдвиговые и логические битовые операторы | Левая | +| 8 | `a=b, a>b` | Сравнение | Левая | +| 9 | `a IN b` | Вхождение элемента в множество | Левая | +| 9 | `a==b, a=b, a!=b, a<>b,` `a is (not) distinct from b` | Сравнение на (не)равенство | Левая | +| 10 | `a XOR b` | Логическое XOR | Левая | +| 11 | `a AND b` | Логическое AND | Левая | +| 12 | `a OR b` | Логическое OR | Левая | + + +## IS \[NOT\] NULL {#is-null} + +Проверка на пустое значение (`NULL`). Так как `NULL` является особым значением, которое [ничему не равно](../types/optional.md#null_expr), то обычные [операторы сравнения](#comparison-operators) для этой задачи не подходят. + +### Примеры + +```yql +SELECT key FROM my_table +WHERE value IS NOT NULL; +``` + +## IS \[NOT\] DISTINCT FROM {#is-distinct-from} + +Сравнение двух значений. В отличие от обычных [операторов сравнения](#comparison-operators), нуллы считаются равными друг другу. + +Сравнение осуществляется по следующим правилам: + +1. операторы `IS DISTINCT FROM`/`IS NOT DISTINCT FROM` определены для тех и только для тех аргументов, для которых определены операторы `!=` и `=`; +2. результат `IS NOT DISTINCT FROM` равен логическому отрицанию результата `IS DISTINCT FROM` для данных аргументов; +3. если результат оператора `==` не равен нуллу для некоторых аргументов, то он совпадает с результатом оператора `IS NOT DISTINCT FROM` для тех же аргументов; +4. если оба аргумента являются незаполненными `Optional`ми или `NULL`ами, то значение `IS NOT DISTINCT FROM` равно `True` +5. результат `IS NOT DISTINCT FROM` от незаполненного `Optional` или `NULL` и заполненного `Optional` или не-`Optional` значения равен `False`. + +Для значений композитных типов эти правила применяются рекурсивно. + +## BETWEEN {#between} + +Проверка на вхождение значения в диапазон. Cинтаксис: `expr [NOT] BETWEEN [ASYMMETRIC | SYMMETRIC] expr AND expr`. + +* `BETWEEN` и `BETWEEN ASYMMETRIC` эквивалентны, `x BETWEEN a AND b` эквивалентно `a <= x AND x <= b`. +* `BETWEEN SYMMETRIC` автоматически переставляет аргументы местами так чтобы диапазон получился непустым, +`x BETWEEN SYMMETRIC a AND b` эквивалентно `(x BETWEEN a AND b) OR (x BETWEEN b AND a)`. +* `NOT` инвертирует результат проверки. + +### Примеры + +```yql +SELECT * FROM my_table +WHERE key BETWEEN 10 AND 20; +``` + +```yql +SELECT * FROM my_table +WHERE key NOT BETWEEN SYMMETRIC 20 AND 10; +``` + + +## IN {#in} + +Проверка вхождения одного значения в набор значений. Логически эквивалентно цепочке сравнений на равенство через `OR`, но реализовано более эффективно. + +{% note warning %} + +В отличие от аналогичного ключевого слова в Python, в YQL `IN` **НЕ** является поиском подстроки в строке. Для поиска подстроки можно использовать функцию [String::Contains](../udf/list/string.md) или описанные выше [LIKE / REGEXP](#check-match). + +{% endnote %} + +Сразу после `IN` можно указать [хинт](lexer.md#sql-hints) `COMPACT`. +Если `COMPACT` не указан, то `IN` с подзапросом по возможности выполняется как соответствующий `JOIN` (`LEFT SEMI` для `IN` и `LEFT ONLY` для `NOT IN`). +Наличие `COMPACT` форсирует in-memory стратегию выполнения: из содержимого правой части `IN` в памяти сразу строится хеш-таблица, по которой затем фильтруется левая часть. + +Хинтом `COMPACT` следует пользоваться с осторожностью. Поскольку хеш-таблица строится в памяти, то запрос может завершиться с ошибкой, если правая часть `IN` содержит много больших и/или различных элементов. + +{% if feature_mapreduce %} + +Так как в YQL есть лимит на размер запроса в байтах (порядка 1Мб), для больших списков значений нужно прикладывать их к запросу через URL и использовать функцию [ParseFile](../builtins/basic.md#parsefile). + +{% endif %} + +### Примеры + +```yql +SELECT column IN (1, 2, 3) +FROM my_table; +``` + +```yql +SELECT * FROM my_table +WHERE string_column IN ("a", "b", "c"); +``` + +```yql +$foo = AsList(1, 2, 3); +SELECT 1 IN $foo; +``` + +```yql +$values = (SELECT column + 1 FROM table); +SELECT * FROM my_table WHERE + -- фильтрация по in-memory хеш-таблице на основе table + column1 IN /*+ COMPACT() */ $values AND + -- с последующим LEFT ONLY JOIN с other_table + column2 NOT IN (SELECT other_column FROM other_table); +``` + + +## AS {#as} + +Может использоваться в следующих сценариях: + +* Присвоение короткого имени (алиаса) столбцам или таблицам в рамках запроса. +* Указание именованных аргументов при вызове функций. +* При явном приведении типов данных для указания целевого типа, см. [CAST](#cast). + +### Примеры + +{% if select_command != "SELECT STREAM" %} + +```yql +SELECT key AS k FROM my_table; +``` + +```yql +SELECT t.key FROM my_table AS t; +``` + +```yql +SELECT + MyFunction(key, 123 AS my_optional_arg) +FROM my_table; +``` +{% else %} + +```yql +SELECT STREAM key AS k FROM my_stream; +``` + +```yql +SELECT STREAM s.key FROM my_stream AS s; +``` + +```yql +SELECT STREAM + MyFunction(key, 123 AS my_optional_arg) +FROM my_stream; +``` + +{% endif %} + +## CAST {#cast} + +Пробует привести значение к указанному типу. Попытка может оказаться неуспешной и вернуть `NULL`. Для чисел может потерять точность или старшие биты. + +{% if feature_column_container_type %} + +Для списков и словарей может либо удалить, либо заменить на `NULL` элементы, преобразование которых неудачно. +Для структур и кортежей удаляет элементы, которых нет в целевом типе. +Подробнее правила преобразований описаны [здесь](../types/cast.md). + +{% endif %} + +{% include [decimal_args](../_includes/decimal_args.md) %} + +### Примеры + +{% include [cast_examples](../_includes/cast_examples.md) %} + + +## BITCAST {#bitcast} + +Выполняет побитное преобразование целочисленного значения к указанному целочисленному типу. Преобразование всегда успешно, но может потерять точность или старшие биты. + +### Примеры + +```yql +SELECT + BITCAST(100000ul AS Uint32), -- 100000 + BITCAST(100000ul AS Int16), -- -31072 + BITCAST(100000ul AS Uint16), -- 34464 + BITCAST(-1 AS Int16), -- -1 + BITCAST(-1 AS Uint16); -- 65535 +``` + + +## CASE {#case} + +Условные выражения и ветвление. Аналог `if`, `switch` и тернарных операторов в императивных языках программирования. +Если результатом выражения `WHEN` оказывается `true`, значением выражения `CASE` становится результат, +следующий за условием, а остальная часть выражения `CASE` не вычисляется. Если же условие не выполняется, +за ним таким же образом проверяются все последующие предложения `WHEN`. Если не выполняется +ни одно из условий `WHEN`, значением `CASE` становится результат, записанный в предложении `ELSE`. +Ветка `ELSE` является обязательной в выражении `CASE`. Выражения в `WHEN` проверяются последовательно, сверху вниз. + +Так как синтаксис достаточно громоздкий, зачастую удобнее пользоваться встроенной функцией [IF](../builtins/basic.md#if). + +### Примеры + +```yql +SELECT + CASE + WHEN value > 0 + THEN "positive" + ELSE "negative" + END +FROM my_table; +``` + +```yql +SELECT + CASE value + WHEN 0 THEN "zero" + WHEN 1 THEN "one" + ELSE "not zero or one" + END +FROM my_table; +``` + + +## Именованные выражения {#named-nodes} + +Сложные запросы могут выглядеть громоздко и содержать много уровней вложенности и/или повторяющихся частей. В YQL имеется возможность использовать именованные выражения – способ назначить имя произвольному выражению или подзапросу. На это именованное выражение можно ссылаться в других выражениях или подзапросах. При этом фактически происходит подстановка исходного выражения/подзапроса по месту использования. + +Именованное выражение определяется следующим образом: + +```antlr + = | ; +``` + +Здесь `` состоит из символа $ и произвольного непустого идентификатора (например `$foo`). + +Если выражение в правой части представляет собой кортеж, то его можно автоматически распаковать, указав в левой части несколько именованных выражений через запятую: + +```antlr +, , ... = ; +``` + +В этом случае число выражений должно совпадать с размером кортежа. + +У каждого именованного выражения есть область видимости. Она начинается сразу после определения именованного выражения и заканчивается в конце ближайшего охватывающего scope имен (например в конце запроса либо в конце тела [лямбда-функции](#lambda), [ACTION](action.md#define-action){% if feature_subquery %}, [SUBQUERY](subquery.md#define-subquery){% endif %}{% if feature_mapreduce %} или цикла [EVALUATE FOR](action.md#evaluate-for){% endif %}). +Повторное определение именованного выражения с тем же именем приводит к сокрытию предыдущего выражения из текущей области видимости. + +Если именованное выражение ни разу не использовалось, то генерируется предупреждение. Для того, чтобы избавиться от такого предупреждения, достаточно использовать символ подчеркивания в качестве первого символа идентификатора (например `$_foo`). +Именованное выражение `$_` называется анонимным именованным выражением и обрабатывается специальным образом: оно работает, как если бы `$_` автоматически заменялось на `$_`. +Анонимными именованными выражениями удобно пользоваться в тех случаях, когда мы не интересуемся его значением. Например, для извлечения второго элемента из кортежа из трех элементов можно написать: + +```yql +$_, $second, $_ = AsTuple(1, 2, 3); +select $second; +``` + +Попытка сослаться на анонимное именованное выражение приводит к ошибке: + +```yql +$_ = 1; +select $_; --- ошибка: Unable to reference anonymous name $_ +export $_; --- ошибка: Can not export anonymous name $_ +``` + +{% if feature_mapreduce %} + +Кроме того, нельзя импортировать именованное выражение под анонимным алиасом: + +```yql +import utils symbols $sqrt as $_; --- ошибка: Can not import anonymous name $_ +``` + +{% endif %} + +Анонимные имена аргументов поддерживаются также для [лямбда-функций](#lambda), [ACTION](action.md#define-action){% if feature_subquery %}, [SUBQUERY](subquery.md#define-subquery){% endif %}{% if feature_mapreduce %} и в [EVALUATE FOR](action.md#evaluate-for){% endif %}. + +{% note info %} + +Если в результате подстановки именованных выражений в графе выполнения запроса получились полностью одинаковые подграфы, они объединяются, чтобы такой подграф выполнялся только один раз. + +{% endnote %} + +### Примеры + +```yql +$multiplier = 712; +SELECT + a * $multiplier, -- $multiplier is 712 + b * $multiplier, + (a + b) * $multiplier +FROM abc_table; +``` + +```yql +$intermediate = ( + SELECT + value * value AS square, + value + FROM my_table +); +SELECT a.square * b.value +FROM $intermediate AS a +INNER JOIN $intermediate AS b +ON a.value == b.square; +``` + +```yql +$a, $_, $c = AsTuple(1, 5u, "test"); -- распаковка кортежа +SELECT $a, $c; +``` + +```yql +$x, $y = AsTuple($y, $x); -- swap значений выражений +``` + + +## Табличные выражения {#table-contexts} + +Табличное выражения – это выражение, которое возвращает таблицу. Табличными выражениями в YQL являются: + +* подзапросы: `(SELECT key, subkey FROM T)` +* [именованные подзапросы](#named-nodes): `$foo = SELECT * FROM T;` (использование именованного подзапроса `$foo` является табличным выражением) + +{% if feature_subquery %} + +* [шаблоны подзапросов](subquery.md#define-subquery): `DEFINE SUBQUERY $foo($name) AS ... END DEFINE;` (вызов `$foo("InputTable")` является табличным выражением). + +{% endif %} + +Семантика табличного выражения зависит от контекста в котором оно используется. В YQL табличные выражения могут применяться в следующих контекстах: + +* табличный контекст - после [FROM](select/from.md). + + Здесь табличные выражения работают как ожидается – например `$input = SELECT a, b, c FROM T; SELECT * FROM $input` вернет таблицу с тремя колонками. + + Табличный контекст также возникает после [UNION ALL](select/index.md#unionall){% if feature_join %}, [JOIN](join.md#join){% endif %}{% if feature_mapreduce and process_command == "PROCESS" %}, [PROCESS](process.md#process), [REDUCE](reduce.md#reduce){% endif %}; + +* векторный контекст - после [IN](#in). В этом контексте табличное выражение обязано содержать ровно одну колонку (имя этой колонки никак не влияет на результат выражения). + + Табличное выражение в векторном контексте типизируется как список (тип элемента списка при этом совпадает с типом колонки). Пример: `SELECT * FROM T WHERE key IN (SELECT k FROM T1)`; + +* скалярный контекст возникает *во всех остальных случаях*. Как и в векторном контексте, табличное выражение должно содержать ровно одну колонку, но значением табличного выражения будет скаляр – произвольно выбранное значение этой колонки (если получилось ноль строк, то результатом будет `NULL`). Пример: `$count = SELECT COUNT(*) FROM T; SELECT * FROM T ORDER BY key LIMIT $count / 2`. + +Порядок строк в табличном контексте, порядок элементов в векторном контексте и правило выбора значения в скалярном контексте (в случае если значений несколько) не определены. На этот порядок также нельзя повлиять с помощью `ORDER BY`: `ORDER BY` без `LIMIT` в табличных выражениях будет игнорироваться с выдачей предупреждения, а использование `ORDER BY` с `LIMIT` определяет множество элементов, но не порядок внутри этого множества. + +{% if feature_mapreduce and process_command == "PROCESS" %} + +Из этого правила есть исключение. Именованное выражение с [PROCESS](process.md#process), будучи использованным в скалярном контексте, ведет себя как в табличном: + +```yql +$input = SELECT 1 AS key, 2 AS value; +$process = PROCESS $input; + +SELECT FormatType(TypeOf($process)); -- $process используется в скалярном контексте, + -- но результат SELECT при этом - List> + +SELECT $process[0].key; -- вернет 1 + +SELECT FormatType(TypeOf($input)); -- ошибка: $input в скалярном контексте должен содержать одну колонку +``` + +{% note warning "Внимание" %} + +Часто встречающейся ошибкой является использование выражения в скалярном контексте вместо табличного или векторного. Например: + +```yql +$dict = SELECT key, value FROM T1; + +DEFINE SUBQUERY $merge_dict($table, $dict) AS +SELECT * FROM $table LEFT JOIN $dict USING(key); +END DEFINE; + +SELECT * FROM $merge_dict("Input", $dict); -- $dict здесь используется в скалярном контексте. + -- ошибка - в скалярном контексте ожидается ровно одна колонка + +``` + +Правильное решение в данном случае выглядит так: + +```yql +DEFINE SUBQUERY $dict() AS +SELECT key, value FROM T1; +END DEFINE; + +DEFINE SUBQUERY $merge_dict($table, $dict) AS +SELECT * FROM $table LEFT JOIN $dict() USING(key); -- использование табличного выражения $dict() + -- (вызов шаблона подзапроса) в табличном контексте +END DEFINE; + +SELECT * FROM $merge_dict("Input", $dict); -- $dict - шаблон позапроса (не табличное выражение) + -- передаваемый в качестве аргумента табличного выражения +``` + +{% endnote %} + +{% endif %} + + +## Lambda функции {#lambda} + +Позволяют комбинировать несколько выражений в одно вызываемое значение. + +В круглых скобках перечисляются аргументы, далее после стрелки указывается тело lambda. Тело lambda состоит либо из выражения в круглых скобках, либо из фигурных скобок вокруг необязательной цепочки выражений с присвоением [именованных выражений](#named-nodes) и результата вызова после ключевого слова `RETURN` в последнем выражении. + +Область видимости для тела lambda — сначала локальные именованные выражения, затем аргументы, затем именованные выражения, определенные выше lambda на верхнем уровне запроса. + +В теле lambda можно использовать только чистые выражения — в том числе другие lambda, возможно, переданные через аргументы. Но нельзя использовать [SELECT](select/index.md), [INSERT INTO](insert_into.md) и прочие выражения верхнего уровня. + +Один или более последних параметров lambda могут быть помечены вопросиком как необязательные — если они не были указаны при вызове lambda, то им будет присвоено значение `NULL`. + +### Примеры + +```yql +$f = ($y) -> { + $prefix = "x"; + RETURN $prefix || $y; +}; + +$g = ($y) -> ("x" || $y); + +$h = ($x, $y?) -> ($x + ($y ?? 0)); + +SELECT $f("y"), $g("z"), $h(1), $h(2, 3); -- "xy", "xz", 1, 5 +``` + +```yql +-- если результат лямбды вычисляется единственным выражением, то можно использовать более компактный вариант синтаксиса: +$f = ($x, $_) -> ($x || "suffix"); -- второй аргумент не используется +SELECT $f("prefix_", "whatever"); +``` + + +## Обращение к контейнерам {#items-access} + +Для адресации к значениям внутри контейнеров: + +* `Struct<>`, `Tuple<>` и `Variant<>` — используется **точка**. Набор ключей (для кортежа и соответствующего варианта — индексов) известен в момент компиляции запроса. Валидность ключа **проверяется** до начала выполнения запроса. +* `List<>` и `Dict<>` — используются **квадратные скобки**. Набор ключей (для списка — индексов) известен только во время выполнения запроса. Валидность ключа **не проверяется** до начала выполнения запроса. Если значение не найдено — будет возвращено пустое значение (NULL) + +[Описание и список доступных контейнеров](../types/containers.md). + +При использовании этого синтаксиса для обращения к контейнерам в столбцах таблиц обязательно нужно указывать полное имя столбца, включая имя или алиас таблицы через точку (см. первый пример ниже). + +### Примеры + +```yql +SELECT + t.struct.member, + t.tuple.7, + t.dict["key"], + t.list[7] +FROM my_table AS t; +``` + +```yql +SELECT + Sample::ReturnsStruct().member; +``` + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_by.md b/ydb/docs/ru/core/yql/reference/syntax/flatten.md similarity index 60% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_by.md rename to ydb/docs/ru/core/yql/reference/syntax/flatten.md index 666a2d91205e..a59b1ac0d7e3 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_by.md +++ b/ydb/docs/ru/core/yql/reference/syntax/flatten.md @@ -2,7 +2,7 @@ ## FLATTEN BY {#flatten-by} -Преобразует строки исходной таблицы с помощью вертикального разворачивания [контейнеров](../../../types/containers.md) переменной длины (списков или словарей). +Преобразует строки исходной таблицы с помощью вертикального разворачивания [контейнеров](../types/containers.md) переменной длины (списков или словарей). Например: @@ -41,9 +41,9 @@ SELECT value, id FROM as_table($sample) FLATTEN BY (value); Такое преобразование может быть удобным в следующих случаях: -* Когда по ячейкам из столбца-контейнера необходимо вывести статистику (например, через [`GROUP BY`](../../group_by.md)). +* Когда по ячейкам из столбца-контейнера необходимо вывести статистику (например, через [`GROUP BY`](group_by.md)). {% if feature_join %} -* Когда в ячейках столбца-контейнера хранятся идентификаторы из другой таблицы, которую нужно присоединить с помощью [`JOIN`](../../join.md). +* Когда в ячейках столбца-контейнера хранятся идентификаторы из другой таблицы, которую нужно присоединить с помощью [`JOIN`](join.md). {% endif %} ### Синтаксис @@ -65,8 +65,81 @@ SELECT value, id FROM as_table($sample) FLATTEN BY (value); {% note info %} -`FLATTEN BY` интерпретирует [опциональные типы данных](../../../types/optional.md) как списки длины 0 или 1. Строки таблицы с `NULL` пропускаются, и тип столбца меняется на аналогичный неопциональный. +`FLATTEN BY` интерпретирует [опциональные типы данных](../types/optional.md) как списки длины 0 или 1. Строки таблицы с `NULL` пропускаются, и тип столбца меняется на аналогичный неопциональный. `FLATTEN BY` делает только одно преобразование за раз, поэтому на опциональных контейнерах, например, `Optional>` следует использовать `FLATTEN LIST BY` или `FLATTEN OPTIONAL BY`. -{% endnote %} \ No newline at end of file +{% endnote %} + +### Уточнение типа контейнера {#flatten-by-specific-type} + +Чтобы уточнить тип контейнера, по которому необходимо произвести преобразование, можно использовать: + +* `FLATTEN LIST BY` + + Для `Optional>` операция `FLATTEN LIST BY` будет разворачивать список, интерпретируя `NULL`-значение как пустой список. +* `FLATTEN DICT BY` + + Для `Optional>` операция `FLATTEN DICT BY` будет разворачивать словарь, интерпретируя `NULL`-значение как пустой словарь. +* `FLATTEN OPTIONAL BY` + + Чтобы фильтровать `NULL`-значения без размножения, необходимо уточнить операцию до `FLATTEN OPTIONAL BY`. + +#### Примеры + +```yql +SELECT + t.item.0 AS key, + t.item.1 AS value, + t.dict_column AS original_dict, + t.other_column AS other +FROM my_table AS t +FLATTEN DICT BY dict_column AS item; +``` + +```yql +SELECT * FROM ( + SELECT + AsList(1, 2, 3) AS a, + AsList("x", "y", "z") AS b +) FLATTEN LIST BY (a, b); +``` + +```yql +SELECT * FROM ( + SELECT + "1;2;3" AS a, + AsList("x", "y", "z") AS b +) FLATTEN LIST BY (String::SplitToList(a, ";") as a, b); +``` + +### Аналоги FLATTEN BY для других СУБД {#flatten-other-dmb} + +* PostgreSQL: `unnest`; +* Hive: `LATERAL VIEW`; +* MongoDB: `unwind`; +* Google BigQuery: `FLATTEN`; +* ClickHouse: `ARRAY JOIN / arrayJoin`; + + + + +## FLATTEN COLUMNS {#flatten-columns} + +Преобразует таблицу, в которой все столбцы должны являться структурами, в таблицу со столбцами, соответствующими каждому элементу каждой структуры из исходных столбцов. + +Имена исходных столбцов-структур не используются и не возвращаются в результате. Имена элементов структур не должны повторяться в исходных столбцах. + +### Пример + +```yql +SELECT x, y, z +FROM ( + SELECT + AsStruct( + 1 AS x, + "foo" AS y), + AsStruct( + false AS z) +) FLATTEN COLUMNS; +``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/grant.md b/ydb/docs/ru/core/yql/reference/syntax/grant.md similarity index 97% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/grant.md rename to ydb/docs/ru/core/yql/reference/syntax/grant.md index 847d8be7e757..ad1d16da93d6 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/grant.md +++ b/ydb/docs/ru/core/yql/reference/syntax/grant.md @@ -15,7 +15,7 @@ GRANT {{permission_name} [, ...] | ALL [PRIVILEGES]} ON {path_to_scheme_object [ `WITH GRANT OPTION` - использование этой конструкции наделяет пользователя или группу пользователей правом управлять правами доступа - назначать или отзывать определенные права. Конструкция имеет функциональность аналогичную выдаче права `"ydb.access.grant"` или `GRANT`. Субъект, обладающий правом `ydb.access.grant`, не может выдавать права шире, чем обладает сам на объекте доступа `path_to_scheme_object`. -{% include [x](_includes/permissions/permissions_list.md) %} +{% include [x](../_includes/permissions_list.md) %} ## Примеры diff --git a/ydb/docs/ru/core/yql/reference/syntax/group_by.md b/ydb/docs/ru/core/yql/reference/syntax/group_by.md new file mode 100644 index 000000000000..d69010762f8d --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/group_by.md @@ -0,0 +1,352 @@ +{% if select_command == "SELECT STREAM" %} + + ## GROUP BY ... HOP + +Сгруппировать таблицу по значениям указанных столбцов или выражений, а также окну времени. + +Если GROUP BY присутствует в запросе, то при выборке столбцов (между `SELECT STREAM ... FROM`) допустимы **только** следующие конструкции: + +1. Столбцы, по которым производится группировка (присутствующие в аргументе `GROUP BY`). +2. Агрегатные функции (см. следующий раздел). Столбцы, по которым **не** идет группировка, можно включать только в качестве аргументов агрегатной функции. +3. Функции, выдающие начальное и конечное время текущего окна (`HOP_START` и `HOP_END`) +4. Произвольные вычисления, комбинирующие пункты 1-3. + +Имеется возможность выполнять группировку по результату вычисления произвольного выражения от исходных столбцов. В этом случае для получения доступа к результату этого выражения рекомендуется присваивать ему имя с помощью `AS`, см. второй пример. + +Агрегатные функции автоматически пропускают `NULL` в своих аргументах. + +Среди столбцов, по которым производится группировка, должна присутствовать конструкция `HOP`, определяющая характеристики окна времени для группировки. +```yql +HOP(time_extractor, hop, interval, delay) +``` +Реализованный вариант окна времени называется **hopping window**. Это окно, продвигающееся вперёд дискретными интервалами (параметр `hop`). Общая длительность окна задаётся параметром `interval`. Для определения времени каждого входного события используется параметр `time_extractor`. Это выражение, зависящее только от входных значений столбцов стрима, должно иметь тип `Timestamp`. Оно указывает, откуда именно во входных событиях доставать значение времени. + +В каждом потоке, определяемом значениями всех столбцов группировки, окно продвигается независимо от других потоков. Продвижение окна полностью зависит от самого позднего события потока. Поскольку записи в потоках слегка перемешиваются во времени, добавлен параметр `delay`, позволяющий отложить закрытие окна на указанную величину. События, приходящие до текущего окна, игнорируются. + +Параметры `interval` и `delay` следует задавать кратными параметру `hop`. Некратные интервалы будут округлены в меньшую сторону. + +Для задания `hop`, `interval` и `delay` используется строковое выражение, соответствующее стандарту [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). Это формат, который используется для конструирования встроенного типа `Interval` [из строки](../builtins/basic.md#data-type-literals). + +Функции без параметров `HOP_START` и `HOP_END` возвращают значение типа `Timestamp` и соответствуют началу и концу текущего окна. + +Известное в других системах **tumbling window** является частным случаем **hopping window**, когда `interval` == `hop`. + +### Примеры + +```yql +SELECT STREAM + key, + COUNT(*) +FROM my_stream +GROUP BY + HOP(CAST(subkey AS Timestamp), "PT10S", "PT1M", "PT30S"), + key; +-- hop = 10 секунд +-- interval = 1 минута +-- delay = 30 секунд +``` + +```yql +SELECT STREAM + double_key, + HOP_END() as time, + COUNT(*) as count +FROM my_stream +GROUP BY + key + key AS double_key, + HOP(ts, "PT1М", "PT1M", "PT1M"); +``` + + + ## HAVING {#having} + +Фильтрация выборки `SELECT STREAM` по результатам вычисления [агрегатных функций](../builtins/aggregation.md). Синтаксис аналогичен [WHERE](select_stream.md#where). + +### Примеры + +```yql +SELECT STREAM + key +FROM my_table +GROUP BY key, HOP(ts, "PT1M", "PT1M", "PT1M") +HAVING COUNT(value) > 100; +``` + +{% else %} + +## GROUP BY + +Группирует результаты `SELECT` по значениям указанных столбцов или выражений. Вместе с `GROUP BY` часто применяются [агрегатные функции](../builtins/aggregation.md) (`COUNT`, `MAX`, `MIN`, `SUM`, `AVG`) для выполнения вычислений в каждой группе. + +### Синтаксис + +```yql +SELECT -- В SELECT можно использовать: + column1, -- ключевые колонки, заданные в GROUP BY + key_n, -- именованные выражения, заданные в GROUP BY + column1 + key_n, -- произвольные неагрегатные функции от них + Aggr_Func1( column2 ), -- агрегатные функции, содержащие в аргументах любые колонки, + Aggr_Func2( key_n + column2 ), -- включая именованные выражения, заданные в GROUP BY + ... +FROM table +GROUP BY + column1, column2, ..., + AS key_n -- При группировке по выражению ему может быть задано имя через AS, + -- которое может быть использовано в SELECT +``` + +Запрос вида `SELECT * FROM table GROUP BY k1, k2, ...` вернет все колонки, перечисленные в GROUP BY, то есть экивалентент запросу `SELECT DISTINCT k1, k2, ... FROM table`. + +Звездочка может также применяться в качестве аргумента агрегатной функции `COUNT`. `COUNT(*)` означает "число строк в группе". + + +{% note info %} + +Агрегатные функции не учитывают `NULL` в своих аргументах, за исключением функции `COUNT`. + +{% endnote %} + +Также в YQL доступен механизм фабрик агрегатных функций, реализованный с помощью функций [`AGGREGATION_FACTORY`](../builtins/basic.md#aggregationfactory) и [`AGGREGATE_BY`](../builtins/aggregation.md#aggregateby). + +### Примеры + +```yql +SELECT key, COUNT(*) FROM my_table +GROUP BY key; +``` + +```yql +SELECT double_key, COUNT(*) FROM my_table +GROUP BY key + key AS double_key; +``` + +```yql +SELECT + double_key, -- ОК: ключевая колонка + COUNT(*) AS group_size, -- OK: COUNT(*) + SUM(key + subkey) AS sum1, -- ОК: агрегатная функция + CAST(SUM(1 + 2) AS String) AS sum2, -- ОК: агрегатная функция с константным аргументом + SUM(SUM(1) + key) AS sum3, -- ОШИБКА: вложенные агрегации не допускаются + key AS k1, -- ОШИБКА: использование неключевой колонки key без агрегации + key * 2 AS dk1, -- ОШИБКА в YQL: использование неключевой колонки key без агрегации +FROM my_table +GROUP BY + key * 2 AS double_key, + subkey as sk, + +``` + + +{% note warning %} + +Возможность указывать имя для колонки или выражения в `GROUP BY .. AS foo` является расширением YQL. Такое имя становится видимым в `WHERE` несмотря на то, что фильтрация по `WHERE` выполняется [раньше](select/index.md#selectexec) группировки. В частности, если в таблице `T` есть две колонки `foo` и `bar`, то в запросе `SELECT foo FROM T WHERE foo > 0 GROUP BY bar AS foo` фильтрация фактически произойдет по колонке `bar` из исходной таблицы. + +{% endnote %} + + +## GROUP BY ... SessionWindow() {#session-window} + +В YQL поддерживаются группировки по сессиям. К обычным выражениям в `GROUP BY` можно добавить специальную функцию `SessionWindow`: + +```yql +SELECT + user, + session_start, + SessionStart() AS same_session_start, -- то же что и session_start + COUNT(*) AS session_size, + SUM(value) AS sum_over_session, +FROM my_table +GROUP BY user, SessionWindow(, ) AS session_start +``` + +При этом происходит следующее: + +1. Входная таблица партиционируется по ключам группировки, указанным в `GROUP BY`, без учета SessionWindow (в данном случае по `user`). Если кроме SessionWindow в `GROUP BY` ничего нет, то входная таблица попадает в одну партицию +2. Каждая партиция делится на непересекающие подмножества строк (сессии). Для этого партиция сортируется по возрастанию значения выражения `time_expr`. Границы сессий проводятся между соседними элементами партиции, разница значений `time_expr` для которых превышает `timeout_expr` +3. Полученные таким образом сессии и являются финальными партициями, на которых вычисляются агрегатные функции. + +Ключевая колонка SessionWindow() (в примере `session_start`) имеет значение "минимальный `time_expr` в сессии". +Кроме того, при наличии SessionWindow() в `GROUP BY` может использоваться специальная агрегатная функция +[SessionStart](../builtins/aggregation.md#session-start). + +Поддерживается также расширенный вариант SessionWindow с четырьмя аргументами: + +`SessionWindow(, , , )` + +Здесь: + +* `` – выражение по которому сортируется исходная партиция +* `` – лямбда-функция для инициализации состояния расчета сессий. Имеет сигнатуру `(TableRow())->State`. Вызывается один раз на первом (по порядку сортировки) элементе исходной партиции +* `` – лямбда-функция для обновления состояния расчета сессий и определения границ сессий. Имеет сигнатуру `(TableRow(), State)->Tuple`. Вызывается на каждом элементе исходной партиции, кроме первого. Новое значения состояния вычисляется на основе текущей строки таблицы и предыдущего состояния. Если первый элемент возвращенного кортежа имеет значение `True`, то с _текущей_ строки начнется новая сессия. Ключ новой сессии получается путем применения `` ко второму элементу кортежа. +* `` – лямбда-функция для вычисления ключа сессии ("значения" SessionWindow(), которое также доступно через SessionStart()). Функция имеет сигнатуру `(TableRow(), State)->SessionKey`. Вызывается на первом элемента партиции (после ``) и на тех элементах, для которых `` вернула `True` в качестве первого элемента кортежа. Стоит отметить, что для начала новой сессии необходимо, чтобы `` вернула значение, которое отличается от предыдущего ключа сессии. При этом сессии с одинаковыми ключами не объединяются. Например, если `` последовательно возвращает `0, 1, 0, 1`, то это будут четыре различные сессии. + +С помощью расширенного варианта SessionWindow можно решить, например, такую задачу: разделить партицию на сессии как в варианте SessionWindow с двумя аргументами, но с ограничением максимальной длины сессии некоторой константой: + +### Пример + +```yql +$max_len = 1000; -- максимальная длина сессии +$timeout = 100; -- таймаут (timeout_expr в упрощенном варианте SessionWindow) + +$init = ($row) -> (AsTuple($row.ts, $row.ts)); -- состояние сессии - тапл из 1) значения временной колонки ts на первой строчке сессии и 2) на текущей строчке +$update = ($row, $state) -> { + $is_end_session = $row.ts - $state.0 > $max_len OR $row.ts - $state.1 > $timeout; + $new_state = AsTuple(IF($is_end_session, $row.ts, $state.0), $row.ts); + return AsTuple($is_end_session, $new_state); +}; +$calculate = ($row, $state) -> ($row.ts); +SELECT + user, + session_start, + SessionStart() AS same_session_start, -- то же что и session_start + COUNT(*) AS session_size, + SUM(value) AS sum_over_session, +FROM my_table +GROUP BY user, SessionWindow(ts, $init, $update, $calculate) AS session_start +``` + +`SessionWindow` может использоваться в `GROUP BY` только один раз. + + +{% if feature_group_by_rollup_cube %} + + ## ROLLUP, CUBE и GROUPING SETS {#rollup} + +Результаты вычисления агрегатной функции в виде промежуточных итогов для групп и общих итогов для отдельных столбцов или всей таблицы. + +### Синтаксис + +```yql +SELECT + c1, c2, -- столбцы, по которым производится группировка + +AGGREGATE_FUNCTION(c3) AS outcome_c -- агрегатная функция (SUM, AVG, MIN, MAX, COUNT) + +FROM table_name + +GROUP BY + GROUP_BY_EXTENSION(c1, c2) -- расширение GROUP BY: ROLLUP, CUBE или GROUPING SETS +``` + +* `ROLLUP` — группирует значения столбцов в порядке их перечисления в аргументах (строго слева направо), формирует промежуточные итоги для каждой группы и общий итог. +* `CUBE` — группирует значения для всех возможных комбинаций столбцов, формирует промежуточные итоги для каждой группы и общий итог. +* `GROUPING SETS` — задает группы для промежуточных итогов. + +`ROLLUP`, `CUBE` и `GROUPING SETS` можно комбинировать через запятую. + +### GROUPING {#grouping} + +В промежуточном итоге значения столбцов, которые не участвуют в вычислениях, заменяются на `NULL`. В общем итоге на `NULL` заменяются значения всех столбцов. `GROUPING` — функция, которая позволяет отличить исходные значения `NULL` от `NULL`, которые были добавлены при формировании общих и промежуточных итогов. + +`GROUPING` возвращает битовую маску: + +* `0` — `NULL` для исходного пустого значения. +* `1` — `NULL`, добавленный для промежуточного или общего итога. + +### Пример + +```yql +SELECT + column1, + column2, + column3, + + CASE GROUPING( + column1, + column2, + column3, + ) + WHEN 1 THEN "Subtotal: column1 and column2" + WHEN 3 THEN "Subtotal: column1" + WHEN 4 THEN "Subtotal: column2 and column3" + WHEN 6 THEN "Subtotal: column3" + WHEN 7 THEN "Grand total" + ELSE "Individual group" + END AS subtotal, + + COUNT(*) AS rows_count + +FROM my_table + +GROUP BY + ROLLUP( + column1, + column2, + column3 + ), + GROUPING SETS( + (column2, column3), + (column3) + -- если добавить сюда ещё (column2), то в сумме + -- эти ROLLUP и GROUPING SETS дали бы результат, + -- аналогичный CUBE + ) +; +``` + + +{% endif %} + +## DISTINCT {#distinct} + +Применение [агрегатных функций](../builtins/aggregation.md) только к уникальным значениям столбца. + +{% note info %} + +Применение `DISTINCT` к вычислимым значениям на данный момент не реализовано. С этой целью можно использовать [подзапрос](select/from.md) или выражение `GROUP BY ... AS ...`. + +{% endnote %} + +### Пример + +```yql +SELECT + key, + COUNT(DISTINCT value) AS count -- топ-3 ключей по количеству уникальных значений +FROM my_table +GROUP BY key +ORDER BY count DESC +LIMIT 3; +``` + +Также ключевое слово `DISTINCT` может использоваться для выборки уникальных строк через [`SELECT DISTINCT`](select/distinct.md). + + + +## COMPACT + +Наличие [SQL хинта](lexer.md#sql-hints) `COMPACT` непосредственно после ключевого слова `GROUP` позволяет более эффективно выполнять агрегацию в тех случаях, когда автору запроса заранее известно, что ни по одному из ключей агрегации не встречаются большие объемы данных (больше примерно гигабайт или миллионов строк). Если это предположение на практике окажется неверным, то операция может завершиться ошибкой из-за превышения потребления оперативной памяти или работать значительно медленнее не-COMPACT версии. + +В отличие от обычного GROUP BY, отключается стадия Map-side combiner и дополнительные Reduce для каждого поля с [DISTINCT](#distinct) агрегацией. + +### Пример + +```yql +SELECT + key, + COUNT(DISTINCT value) AS count -- топ-3 ключей по количеству уникальных значений +FROM my_table +GROUP /*+ COMPACT() */ BY key +ORDER BY count DESC +LIMIT 3; +``` + + +## HAVING {#having} + +Фильтрация выборки `SELECT` по результатам вычисления [агрегатных функций](../builtins/aggregation.md). Синтаксис аналогичен конструкции [`WHERE`](select/where.md). + +### Пример + +```yql +SELECT + key +FROM my_table +GROUP BY key +HAVING COUNT(value) > 100; +``` + + +{% endif %} + + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/index.md b/ydb/docs/ru/core/yql/reference/syntax/index.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/index.md rename to ydb/docs/ru/core/yql/reference/syntax/index.md diff --git a/ydb/docs/ru/core/yql/reference/syntax/insert_into.md b/ydb/docs/ru/core/yql/reference/syntax/insert_into.md new file mode 100644 index 000000000000..b2b1030cd4e8 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/insert_into.md @@ -0,0 +1,115 @@ + +# INSERT INTO + +{% if oss == true and backend_name == "YDB" %} + +{% note warning %} + +{% include [OLAP_not_allow_text](../../../_includes/not_allow_for_olap_text.md) %} + +{% include [ways_add_data_to_olap](../../../_includes/ways_add_data_to_olap.md) %} + +{% endnote %} + +{% endif %} + +{% if select_command != "SELECT STREAM" %} +Добавляет строки в {% if oss == true and backend_name == "YDB" %}строковую{% endif %} таблицу. {% if feature_bulk_tables %} Если целевая таблица уже существует и не является сортированной, операция `INSERT INTO` дописывает строки в конец таблицы. В случае сортированной таблицы, YQL пытается сохранить сортированность путем запуска сортированного слияния. {% endif %}{% if feature_map_tables %} При попытке вставить в таблицу строку с уже существующим значением первичного ключа операция завершится ошибкой с кодом `PRECONDITION_FAILED` и текстом `Operation aborted due to constraint violation: insert_pk`.{% endif %} + +{% if feature_mapreduce %}Таблица по имени ищется в базе данных, заданной оператором [USE](use.md).{% endif %} + +`INSERT INTO` позволяет выполнять следующие операции: + +* Добавление константных значений с помощью [`VALUES`](values.md). + + ```yql + INSERT INTO my_table (Key1, Key2, Value1, Value2) + VALUES (345987,'ydb', 'Яблочный край', 1414); + COMMIT; + ``` + + ```yql + INSERT INTO my_table (key, value) + VALUES ("foo", 1), ("bar", 2); + ``` + +* Сохранение результата выборки `SELECT`. + + ```yql + INSERT INTO my_table + SELECT Key AS Key1, "Empty" AS Key2, Value AS Value1 + FROM my_table1; + ``` + +{% else %} + +Направить результат вычисления [SELECT STREAM](select_stream.md) в указанный стрим на кластере, заданном оператором [USE](use.md). Стрим должен существовать и иметь схему, подходящую результату запроса. + +## Примеры + +```yql +INSERT INTO my_stream_dst +SELECT STREAM key FROM my_stream_src; +``` + +Существует возможность указать в качестве цели таблицу на кластере ydb. Таблица должна существовать на момент создания операции. Схема таблицы должна быть совместима с типом результата запроса. + +## Примеры + +```yql +INSERT INTO ydb_cluster.`my_table_dst` +SELECT STREAM * FROM rtmr_cluster.`my_stream_source`; +``` + +{% endif %} + + +{% if feature_insert_with_truncate %} + +Запись может выполняться с одним или несколькими модификаторами. Модификатор указывается после ключевого слова `WITH` после имени таблицы: `INSERT INTO ... WITH SOME_HINT`. +Если у модификатора есть значение, то оно указывается после знака `=`: `INSERT INTO ... WITH SOME_HINT=value`. +Если необходимо указать несколько модификаторов, то они заключаются в круглые скобки: `INSERT INTO ... WITH (SOME_HINT1=value, SOME_HINT2, SOME_HINT3=value)`. + +Чтобы перед записью очистить таблицу от имевшихся данных, достаточно добавить модификатор: `INSERT INTO ... WITH TRUNCATE`. + +## Примеры + +```yql +INSERT INTO my_table WITH TRUNCATE +SELECT key FROM my_table_source; +``` + +{% endif %} + + +{% if feature_federated_queries %} + +При работе с [внешними файловыми источниками данных](../../../concepts/datamodel/external_data_source.md) можно дополнительно указывать ряд параметров: + +* `FORMAT` - формат хранимых данных в файловых хранилищах в [федеративных запросах](../../../concepts/federated_query/s3/formats.md). Допустимые значения: `csv_with_names`, `tsv_with_names`, `json_list`, `json_each_row`, `json_as_string`, `parquet`, `raw`. +* `COMPRESSION` - формат сжатия файлов в файловых хранилищах в [федеративных запросах](../../../concepts/federated_query/s3/partition_projection). Допустимые значения: [gzip](https://ru.wikipedia.org/wiki/Gzip), [zstd](https://ru.wikipedia.org/wiki/Zstandard), [lz4](https://ru.wikipedia.org/wiki/LZ4), [brotli](https://ru.wikipedia.org/wiki/Brotli), [bzip2](https://ru.wikipedia.org/wiki/Bzip2), [xz](https://ru.wikipedia.org/wiki/XZ). +* `PARTITIONED_BY` - список [колонок партиционирования](../../../concepts/federated_query/s3/partitioning.md) данных в файловых хранилищах в федеративных запросах. Содержит список колонок в порядке их размещения в файловом хранилище. +* `projection.enabled` - флаг включения [расширенного партиционирования данных](../../../concepts/federated_query/s3/partition_projection.md). Допустимые значения: `true`, `false`. +* `projection..type` - тип поля [расширенного партиционирования данных](../../../concepts/federated_query/s3/partition_projection.md). Допустимые значения: `integer`, `enum`, `date`. +* `projection..` - расширенные свойства поля [расширенного партиционирования данных](../../../concepts/federated_query/s3/partition_projection.md). + + +## Пример + +```yql +INSERT INTO `connection`.`test/` +WITH +( + FORMAT = "csv_with_names" +) +SELECT + "value" AS value, "name" AS name +``` + +Где: + +* `connection` — название соединения с S3 ({{ objstorage-full-name }}). +* `test/`— путь внутри бакета, куда будут записаны данные. При записи создаются файлы со случайными именами. + +{% endif %} + diff --git a/ydb/docs/ru/core/yql/reference/syntax/into_result.md b/ydb/docs/ru/core/yql/reference/syntax/into_result.md new file mode 100644 index 000000000000..f47f09cff0f0 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/into_result.md @@ -0,0 +1,19 @@ + +# INTO RESULT + +Позволяет задать пользовательскую метку для [SELECT](select/index.md){% if feature_mapreduce and process_command == "PROCESS" %}, [PROCESS](process.md) или [REDUCE](reduce.md){% endif %}.{% if backend_name != "YDB" %} Не может быть задано одновременно с [DISCARD](discard.md).{% endif %} + +## Примеры + +```yql +SELECT 1 INTO RESULT foo; +``` + +```yql +SELECT * FROM +my_table +WHERE value % 2 == 0 +INTO RESULT `Название результата`; +``` + + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/join.md b/ydb/docs/ru/core/yql/reference/syntax/join.md similarity index 99% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/join.md rename to ydb/docs/ru/core/yql/reference/syntax/join.md index 847764d787f6..42f5717f2dbd 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/join.md +++ b/ydb/docs/ru/core/yql/reference/syntax/join.md @@ -1,3 +1,4 @@ + # JOIN Позволяет объединить несколько источников данных (подзапросов или таблиц) по равенству значений указанных столбцов или выражений (ключей `JOIN`). @@ -38,7 +39,7 @@ WHERE ... * `CROSS` — декартово произведение двух таблиц целиком без указания ключевых колонок, секция с `ON/USING` явно не пишется; * `EXCLUSION` — обе стороны минус пересечение. -![JOIN](../_assets/join-YQL-06.png) +![JOIN](_assets/join-YQL-06.png) {% note info %} @@ -144,3 +145,5 @@ ON a.key == b.key; |"2"|"v122"|"v222"| {% endif %} + + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/lexer.md b/ydb/docs/ru/core/yql/reference/syntax/lexer.md similarity index 77% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/lexer.md rename to ydb/docs/ru/core/yql/reference/syntax/lexer.md index 8f754b5d40dd..e3770419ad58 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/lexer.md +++ b/ydb/docs/ru/core/yql/reference/syntax/lexer.md @@ -1,4 +1,5 @@ + # Лексическая структура @@ -88,7 +89,7 @@ SELECT 1 as "column with "" double quoute"; -- имя колонки будет: SQL хинты – это специальные настройки, которые позволяют пользователю влиять на план выполнения запроса (например, включать/выключать определенные оптимизации, форсировать стратегию JOIN-а и т.п.). -В отличие от [PRAGMA](../pragma.md), SQL хинты обладают локальным действием – они привязаны к определенной точке YQL запроса (обычно следуют после ключевого слова) +В отличие от [PRAGMA](pragma.md), SQL хинты обладают локальным действием – они привязаны к определенной точке YQL запроса (обычно следуют после ключевого слова) и влияют только на соответствующий statement или даже его часть. SQL хинты представляют собой набор настроек "имя-список значений" и задаются внутри комментариев специального вида – первым символом комментария с SQL хинтами должен быть `+`: @@ -159,7 +160,7 @@ SELECT "string with\n newline, \x0a newline and \" backtick "; SELECT 'string with '' quote'; -- результат: string with ' quote ``` -На основании строковых литералов могут быть получены [литералы простых типов](../../builtins/basic#data-type-literals). +На основании строковых литералов могут быть получены [литералы простых типов](../builtins/basic#data-type-literals). ### Многострочные строковые литералы {#multiline-string-literals} @@ -183,7 +184,7 @@ SELECT $text; ### Типизированные строковые литералы {#typed-string-literals} -* Для строкового литерала, включая [многострочный](#multiline-string-literals), по умолчанию используется тип `String` (см. также [PRAGMA UnicodeLiterals](../pragma.md#UnicodeLiterals)). +* Для строкового литерала, включая [многострочный](#multiline-string-literals), по умолчанию используется тип `String` (см. также [PRAGMA UnicodeLiterals](pragma.md#UnicodeLiterals)). * С помощью следующих суффиксов можно явно управлять типом литерала: * `s` — `String`; @@ -230,4 +231,101 @@ SELECT Строковые и числовые литералы Pg типов можно создавать с помощью специальных суффиксов (аналогично простым [строковым](#string-literals) и [числовым](#literal-numbers) литералам). -{% include [pgliterals](../../udf/list/_includes/pgliterals.md) %} +### Целочисленные литералы {#intliterals} + +Суффикс | Тип | Комментарий +----- | ----- | ----- +`p` | `PgInt4` | 32-битное знаковое целое (в PostgreSQL нет беззнаковых типов) +`ps`| `PgInt2` | 16-битное знаковое целое +`pi`| `PgInt4` | +`pb`| `PgInt8` | 64-битное знаковое цело +`pn`| `PgNumeric` | знаковое целое произвольной точности (до 131072 цифр) + +### Литералы с плавающей точкой {#floatliterals} + +Суффикс | Тип | Комментарий +----- | ----- | ----- +`p` | `PgFloat8` | число с плавающей точкой (64 бит double) +`pf4`| `PgFloat4` | число с плавающей точкой (32 бит float) +`pf8`| `PgFloat8` | +`pn` | `PgNumeric` | число с плавающей точкой произвольной точности (до 131072 цифр перед запятой, до 16383 цифр после запятой) + +### Строковые литералы {#stringliterals} + +Суффикс | Тип | Комментарий +----- | ----- | ----- +`p` | `PgText` | текстовая строка +`pt`| `PgText` | +`pv`| `PgVarchar` | текстовая строка +`pb`| `PgBytea` | бинарная строка + +{% note warning "Внимание" %} + +Значения строковых/числовых литералов (т.е. то что идет перед суффиксом) должны быть валидной строкой/числом с точки зрения YQL. +В частности, должны соблюдаться правила эскейпинга YQL, а не PostgreSQL. + +{% endnote %} + +Пример: + +```yql +SELECT + 1234p, -- pgint4 + 0x123pb, -- pgint8 + "тест"pt, -- pgtext + 123e-1000pn; -- pgnumeric +; +``` + +### Литерал массива + +Для построения литерала массива используется функция `PgArray`: + +```yql +SELECT + PgArray(1p, NULL ,2p) -- {1,NULL,2}, тип _int4 +; +``` + +### Конструктор литералов произвольного типа {#literals_constructor} + +Литералы всех типов (в том числе и Pg типов) могут создаваться с помощью конструктора литералов со следующей сигнатурой: +`Имя_типа(<строковая константа>)`. + +Напрмер: + +```yql +DECLARE $foo AS String; +SELECT + PgInt4("1234"), -- то же что и 1234p + PgInt4(1234), -- в качестве аргумента можно использовать литеральные константы + PgInt4($foo), -- и declare параметры + PgBool(true), + PgInt8(1234), + PgDate("1932-01-07"), +; +``` + +Также поддерживается встроенная функция `PgConst` со следующей сигнатурой: `PgConst(<строковое значение>, <тип>)`. +Такой способ более удобен для кодогенерации. + +Например: + +```yql +SELECT + PgConst("1234", PgInt4), -- то же что и 1234p + PgConst("true", PgBool) +; +``` + +Для некоторых типов в функции `PgConst` можно указать дополнительные модификаторы. Возможные модификаторы для типа `pginterval` перечислены в [документации PostgreSQL](https://www.postgresql.org/docs/16/datatype-datetime.html). + +```yql +SELECT + PgConst(90, pginterval, "day"), -- 90 days + PgConst(13.45, pgnumeric, 10, 1); -- 13.5 +; +``` + + + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/not_yet_supported.md b/ydb/docs/ru/core/yql/reference/syntax/not_yet_supported.md similarity index 90% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/not_yet_supported.md rename to ydb/docs/ru/core/yql/reference/syntax/not_yet_supported.md index d8c105463d4c..742174bd9757 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/not_yet_supported.md +++ b/ydb/docs/ru/core/yql/reference/syntax/not_yet_supported.md @@ -10,4 +10,5 @@ ## NOW() / CURRENT_TIME() {#now} -Доступный альтернативный вариант — воспользоваться функциями [CurrentUtcDate, CurrentUtcDatetime и CurrentUtcTimestamp](../../builtins/basic.md#current-utc). +Доступный альтернативный вариант — воспользоваться функциями [CurrentUtcDate, CurrentUtcDatetime и CurrentUtcTimestamp](../builtins/basic.md#current-utc). + diff --git a/ydb/docs/ru/core/yql/reference/syntax/pragma.md b/ydb/docs/ru/core/yql/reference/syntax/pragma.md new file mode 100644 index 000000000000..d90b314af134 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/pragma.md @@ -0,0 +1,544 @@ +# PRAGMA + +## Определение + +Переопределение настроек. + +### Синтаксис + +`PRAGMA x.y = "z";` или `PRAGMA x.y("z", "z2", "z3");`: + +* `x` — (опционально) категория настройки. +* `y` — название настройки. +* `z` — (опционально для флагов) значение настройки. Допустимо использование следующих суффиксов: + + * `Kb`, `Mb`, `Gb` — для объема информации. + * `sec`, `min`, `h`, `d` — для временных значений. + +### Примеры + +```yql +PRAGMA AutoCommit; +``` + +```yql +PRAGMA TablePathPrefix = "home/yql"; +``` + +```yql +PRAGMA Warning("disable", "1101"); +``` + +За некоторым исключением, значение настроек можно вернуть в состояние по умолчанию с помощью `PRAGMA my_pragma = default;`. + +Полный список доступных настроек [см. в таблице ниже](#pragmas). + +### Область действия {#pragmascope} + +Если не указано иное, прагма влияет на все идущие следом выражения вплоть до конца модуля, в котором она встречается. +При необходимости и логической возможности допустимо менять значение настройки несколько раз в одном запросе, чтобы оно было разным на разных этапах выполнения. +Существуют также специальные scoped прагмы, область действия которых определяется по тем же правилам, что и область видимости [именованных выражений](expressions.md#named-nodes). +В отличие от scoped прагм, обычные прагмы могут использоваться только в глобальной области видимости (не внутри лямбда-функций, ACTION{% if feature_subquery %}, SUBQUERY{% endif %} и т.п.). + +## Глобальные {#pragmas} + +### AutoCommit {#autocommit} + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Автоматически выполнять [COMMIT](commit.md) после каждого выражения. + +### TablePathPrefix {#table-path-prefix} + +| Тип значения | По умолчанию | +| --- | --- | +| Строка | — | + +Добавить указанный префикс к путям таблиц внутри кластеров. Работает по принципу объединения путей в файловой системе: поддерживает ссылки на родительский каталог `..` и не требует добавления слеша справа. Например, + +```yql +PRAGMA TablePathPrefix = "home/yql"; +SELECT * FROM test; +``` + +Префикс не добавляется, если имя таблицы указано как абсолютный путь (начинается с /). + +### UDF {#udf} + +| Тип значения | По умолчанию | Статическая /
динамическая | +| --- | --- | --- | +| Строка | — | Статическая | +| Строка - имя префикса, добавляемого ко всем модулям | "" | Статическая | + +Импорт всех UDF из указанной приложенной к запросу скомпилированной под Linux x64 разделяемой библиотеки (.so). +При указании префикса, он добавляется перед названием всех загруженных модулей, например, CustomPrefixIp::IsIPv4 вместо Ip::IsIPv4. +Указание префикса позволяет подгрузить одну и ту же UDF разных версий. + +### UseTablePrefixForEach {#use-table-prefix-for-each} + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +`EACH` использует [TablePathPrefix](#table-path-prefix) для каждого элемента списка. + +### Warning {#warning} + +| Тип значения | По умолчанию | +| --- | --- | +| 1. Действие
2. Код предупреждения либо символ "*"| — | + +Действие: + +* `disable` — отключить; +* `error` — приравнять к ошибке; +* `default` — вернуть поведение по умолчанию. + +Код предупреждения возвращается вместе с самим текстом (в веб-интерфейсе отображается справа). + +Примеры: + +`PRAGMA Warning("error", "*");` +`PRAGMA Warning("disable", "1101");` +`PRAGMA Warning("default", "4503");` + +В данном случае все предупреждения будут считаться ошибками, за исключением предупреждение с кодом `1101`, которое будет отключено, и `4503`, которое будет обрабатываться по умолчанию (то есть останется предупреждением). Поскольку предупреждения могут добавляться в новых релизах YQL, следует с осторожностью пользоваться конструкцией `PRAGMA Warning("error", "*");` (как минимум покрывать такие запросы автотестами). + + + +### Greetings {#greetings} + +| Тип значения | По умолчанию | +| --- | --- | +| Текст | — | + +Выдать указанный текст в качестве Info сообщения запроса. + +Пример: +`PRAGMA Greetings("It's a good day!");` + +### WarningMsg {#warningmsg} + +| Тип значения | По умолчанию | +| --- | --- | +| Текст | — | + +Выдать указанный текст в качестве Warning сообщения запроса. + +Пример: +`PRAGMA WarningMsg("Attention!");` + +{% if feature_mapreduce %} + +### DqEngine {#dqengine} + +| Тип значения | По умолчанию | +| --- | --- | +| Строка disable/auto/force | "auto" | + +При значении "auto" включает новый движок вычислений. Вычисления по возможности делаются без создания map/reduce операций. При значении "force" вычисление идет в новый движок безусловно. +{% endif %} + +{% if feature_join %} + +### SimpleColumns {#simplecolumns} + +`SimpleColumns` / `DisableSimpleColumns` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | true | + +При использовании `SELECT foo.* FROM ... AS foo` убрать префикс `foo.` у имен результирующих колонок. + +Работает в том числе и для [JOIN](join.md), но в этом случае имеет право упасть в случае конфликта имен (который можно разрешить с помощью [WITHOUT](select/without.md) и переименования колонок). Для JOIN в режиме SimpleColumns производится неявный Coalesce для ключевых колонок: запрос `SELECT * FROM T1 AS a JOIN T2 AS b USING(key)` в режиме SimpleColumns работает как `SELECT a.key ?? b.key AS key, ... FROM T1 AS a JOIN T2 AS b USING(key)` + +### CoalesceJoinKeysOnQualifiedAll + +`CoalesceJoinKeysOnQualifiedAll` / `DisableCoalesceJoinKeysOnQualifiedAll` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | true | + +Управляет неявным Coalesce для ключевых колонок `JOIN` в режиме SimpleColumns. Если флаг установлен, то Coalesce ключевых колонок происходит при наличии хотя бы одного выражения вида `foo.*` или `*` в SELECT - например `SELECT a.* FROM T1 AS a JOIN T2 AS b USING(key)`. Если флаг сброшен, то Coalesce ключей JOIN происходит только при наличии '*' после `SELECT` + +### StrictJoinKeyTypes + +`StrictJoinKeyTypes` / `DisableStrictJoinKeyTypes` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Если флаг установлен, то [JOIN](join.md) будет требовать строгого совпадения типов ключей. +По умолчанию JOIN предварительно конвертирует ключи к общему типу, что может быть нежелательно с точки зрения производительности. +StrictJoinKeyTypes является [scoped](#pragmascope) настройкой. + +{% endif %} + +### AnsiInForEmptyOrNullableItemsCollections + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Наличие этой прагмы приводит поведение оператора `IN` в соответствие со стандартом в случае наличия `NULL` в левой или правой части оператора `IN`. Также изменено поведение `IN` в случае, когда справа был Tuple с элементами разных типов. Примеры: + +`1 IN (2, 3, NULL) = NULL (было Just(False))` +`NULL IN () = Just(False) (было NULL)` +`(1, null) IN ((2, 2), (3, 3)) = Just(False) (было NULL)` + +Подробнее про поведение `IN` при наличии `NULL`ов в операндах можно почитать [здесь](expressions.md#in). Явным образом выбрать старое поведение можно указав прагму `DisableAnsiInForEmptyOrNullableItemsCollections`. Если никакой прагмы не задано, то выдается предупреждение и работает старый вариант. + +### AnsiRankForNullableKeys + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Приводит поведение RANK/DENSE_RANK в соответствие со стандартом при наличии опциональных типов в ключах сортировки окна или в аргументе этих оконных функций. А именно: + +* типом результата всегда является Uint64, а не Uint64?; +* null-ы в ключах считаются равными друг другу (текущая реализация возвращает NULL). + +Явным образом выбрать старое поведению можно указав прагму `DisableAnsiRankForNullableKeys`. Если никакой прагмы не задано, то выдается предупреждение и работает старый вариант. + +### AnsiCurrentRow + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Приводит неявное задание рамки окна при наличии ORDER BY в соответствие со стандартом. +Если AnsiCurrentRow не установлен, то окно `(ORDER BY key)` эквивалентно `(ORDER BY key ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. +Стандарт же требует, чтобы такое окно вело себя как `(ORDER BY key RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. +Разница состоит в трактовке `CURRENT ROW`. В режиме `ROWS` `CURRENT ROW` трактуется буквально – текущая строка в партиции. +А в режиме `RANGE` конец рамки `CURRENT ROW` означает "последняя строка в партиции с ключом сортировки, равным текущей строке". + +### OrderedColumns {#orderedcolumns} + +`OrderedColumns` / `DisableOrderedColumns` + +Выводить [порядок колонок](select/index.md#orderedcolumns) в SELECT/JOIN/UNION ALL и сохранять его при записи результатов. По умолчанию порядок колонок не определен. + +### PositionalUnionAll {#positionalunionall} + +Включить соответствующий стандарту поколоночный режим выполнения [UNION ALL](select/union.md#union-all). При этом автоматически включается +[упорядоченность колонок](#orderedcolumns). + +### RegexUseRe2 + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Использовать Re2 UDF вместо Pcre для выполнения SQL операторов `REGEX`,`MATCH`,`RLIKE`. Re2 UDF поддерживает корректную обработку Unicode-символов в отличие от используемой по умолчанию Pcre UDF. + +### ClassicDivision + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | true | + +В классическом варианте результат целочисленного деления остаётся целочисленным (по умолчанию). +Если отключить — результат всегда становится Double. +ClassicDivision является [scoped](#pragmascope) настройкой. + +### CheckedOps + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +При включенном режиме если в результате выполнения агрегационных функций SUM/SUM_IF, бинарных операций `+`,`-`,`*`,`/`,`%` или унарной операции `-` над целыми числами происходит выход за границы целевого типа аргументов или результата, то возвращается `NULL`. +Если отключить - переполнение не проверяется. +Не влияет на операции с числами с плавающей точкой или `Decimal`. +CheckedOps является [scoped](#pragmascope) настройкой. + +### UnicodeLiterals + +`UnicodeLiterals`/`DisableUnicodeLiterals` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +При включенном режиме строковые литералы без суффиксов вида "foo"/'bar'/@@multiline@@ будут иметь тип `Utf8`, при выключенном - `String`. +UnicodeLiterals является [scoped](#pragmascope) настройкой. + +### WarnUntypedStringLiterals + +`WarnUntypedStringLiterals`/`DisableWarnUntypedStringLiterals` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +При включенном режиме для строковых литералов без суффиксов вида "foo"/'bar'/@@multiline@@ будет генерироваться предупреждение. Его можно подавить, если явно выбрать суффикс `s` для типа `String`, либо `u` для типа `Utf8`. +WarnUntypedStringLiterals является [scoped](#pragmascope) настройкой. + +### AllowDotInAlias + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Разрешить использовать точку в именах результирующих колонок. По умолчанию отключено, т.к. дальнейшее использование таких колонок в JOIN полностью не реализовано. + +### WarnUnnamedColumns + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Генерировать предупреждение если для безымянного выражения в `SELECT` было автоматически сгенерировано имя колонки (вида `column[0-9]+`). + +### GroupByLimit + +| Тип значения | По умолчанию | +| --- | --- | +| Положительное число | 32 | + +Увеличение лимита на число группировок в [GROUP BY](group_by.md). + +{% if feature_group_by_rollup_cube %} + +### GroupByCubeLimit + +| Тип значения | По умолчанию | +| --- | --- | +| Положительное число | 5 | + +Увеличение лимита на число размерностей [GROUP BY](group_by.md#rollup-cube-group-sets). + +Использовать нужно аккуратно, так как вычислительная сложность запроса растет экспоненциально по отношению к числу размерностей. + +{% endif %} + + +## Yson + +Управление поведением Yson UDF по умолчанию, подробнее см. в [документации по ней](../udf/list/yson.md) и в частности [Yson::Options](../udf/list/yson.md#ysonoptions). + +### `yson.AutoConvert` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Автоматическое конвертация значений в требуемый тип данных во всех вызовах Yson UDF, в том числе и неявных. + +### `yson.Strict` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | true | + +Управление строгим режимом во всех вызовах Yson UDF, в том числе и неявных. Без значения или при значении `"true"` - включает строгий режим. Со значением `"false"` - отключает. + +### `yson.DisableStrict` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Инвертированная версия `yson.Strict`. Без значения или при значении `"true"` - отключает строгий режим. Со значением `"false"` - включает. + + + +{% if feature_mapreduce %} + +## Работа с файлами + +### File + +| Тип значения | По умолчанию | Статическая /
динамическая | +| --- | --- | --- | +| Два или три строковых аргумента — алиас, URL и опциональное имя токена | — | Статическая | + +Приложить файл к запросу по URL. Использовать приложенные файлы можно с помощью встроенных функций [FilePath и FileContent](../builtins/basic.md#filecontent).{% if oss != true %} Данная `PRAGMA` является универсальной альтернативой прикладыванию файлов с использованием встроенных механизмов [веб-](../interfaces/web.md#attach) или [консольного](../interfaces/cli.md#attach) клиентов.{% endif %} + +Сервис YQL оставляет за собой право кешировать находящиеся за URL файлы на неопределенный срок, по-этому при значимом изменении находящегося за ней содержимого настоятельно рекомендуется модифицировать URL за счет добавления/изменения незначащих параметров. + +При указании имени токена, его значение будет использоваться для обращения к целевой системе. + +### FileOption + +| Тип значения | По умолчанию | Статическая /
динамическая | +|-------------------------------------------------|--------------|--------------------------------| +| Три строковых аргумента — алиас, ключ, значение | — | Статическая | + +Установить у указанного файла опцию по заданному ключу в заданное значение. Файл с этим алиасом уже должен быть объявлен +через [PRAGMA File](#file) или приложен к запросу. + + + +### Folder + +| Тип значения | По умолчанию | Статическая /
динамическая | +| --- | --- | --- | +| Два или три строковых аргумента — префикс, URL и опциональное имя токена | — | Статическая | + +Приложить набор файлов к запросу по URL. Работает аналогично добавлению множества файлов через [PRAGMA File](#file) по прямым ссылкам на файлы с алиасами, полученными объединением префикса с именем файла через `/`. + +При указании имени токена, его значение будет использоваться для обращения к целевой системе. + +### Library + +| Тип значения | По умолчанию | Статическая /
динамическая | +| --- | --- | --- | +| Один или два аргумента - имя файла и опциональный URL | — | Статическая | + +Интерпретировать указанный приложенный файл как библиотеку, из которой можно делать [IMPORT](export_import.md). Тип синтаксиса библиотеки определяется по расширению файла: +* `.sql` для YQL диалекта SQL (рекомендуется); +* `.yql` для [s-expressions](/docs/s_expressions). + +Пример с приложенным файлом к запросу: + +```yql +PRAGMA library("a.sql"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +В случае указания URL библиотека скачивается с него, а не с предварительного приложенного файла, как в следующем примере: + +```yql +PRAGMA library("a.sql","{{ corporate-paste }}/5618566/text"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +При этом можно использовать подстановку текстовых параметров в URL: + +```yql +DECLARE $_ver AS STRING; -- "5618566" +PRAGMA library("a.sql","{{ corporate-paste }}/{$_ver}/text"); +IMPORT a SYMBOLS $x; +SELECT $x; +``` + +### Package + +| Тип значения | По умолчанию | Статическая /
динамическая | +| --- | --- | --- | +| Два или три аргумента - имя пакета, URL и опциональный токен | — | Статическая | + +Приложить иерархический набор файлов к запросу по URL, интерпретируя их в качестве пакета с указанным именем - взаимосвязанного набора библиотек. + +Имя пакета ожидается в формате ``project_name.package_name``; из библиотек пакета в дальнейшнем можно делать [IMPORT](export_import.md) с именем модуля вида ``pkg.project_name.package_name.maybe.nested.module.name``. + +Пример для пакета с плоской иерархией, состоящего из двух библиотек - foo.sql и bar.sql: + +```yql +PRAGMA package("project.package", "{{ corporate-yt }}/{{ corporate-yt-cluster }}/path/to/package"); +IMPORT pkg.project.package.foo SYMBOLS $foo; +IMPORT pkg.project.package.bar SYMBOLS $bar; +SELECT $foo, $bar; +``` + +При этом можно использовать подстановку текстовых параметров в URL: + +```yql +DECLARE $_path AS STRING; -- "path" +PRAGMA package("project.package","{{ corporate-yt }}/{{ corporate-yt-cluster }}/{$_path}/to/package"); +IMPORT pkg.project.package.foo SYMBOLS $foo; +IMPORT pkg.project.package.bar SYMBOLS $bar; +SELECT $foo, $bar; +``` + +### OverrideLibrary + +| Тип значения | По умолчанию | Статическая /
динамическая | +| --- | --- | --- | +| Один аргумент - имя файла | — | Статическая | + +Интерпретировать указанный приложенный файл как библиотеку и перекрыть ей одну из библиотек пакета. + +Имя файла ожидается в формате ``project_name/package_name/maybe/nested/module/name.EXTENSION``, поддерживаются аналогичные [PRAGMA Library](#library) расширения. + +Пример: + +```yql +PRAGMA package("project.package", "{{ corporate-yt }}/{{ corporate-yt-cluster }}/path/to/package"); +PRAGMA override_library("project/package/maybe/nested/module/name.sql"); + +IMPORT pkg.project.package.foo SYMBOLS $foo; +SELECT $foo; +``` + +{% endif %} + + +{% if backend_name == "YDB" %} + +## YDB + +### `ydb.CostBasedOptimizationLevel` {#costbasedoptimizationlevel} + +| Уровень | Поведение оптимизатора | +| ------- | ---------------------- | +| 0 | Cтоимостный оптимизатор выключен | +| 1 | Cтоимостный оптимизатор выключен, считаются предсказания оптимизатора | +| 2 | Cтоимостный оптимизатор включается только для запросов, где участвуют {% if backend_name == "YDB" and oss == true %}[колоночные таблицы](../../../concepts/glossary.md#column-oriented-table){% else %}колоночные таблицы{% endif %} | +| 3 | Cтоимостный оптимизатор включается для всех запросов, но для строковых таблиц предпочитается алгоритм джоина LookupJoin | +| 4 | Cтоимостный оптимизатор включен для всех запросов | + +{% if tech %} + +### `kikimr.IsolationLevel` + +| Тип значения | По умолчанию | +| --- | --- | +| Serializable, ReadCommitted, ReadUncommitted или ReadStale. | Serializable | + +Экспериментальная pragma, позволяет ослабить уровень изоляции текущей транзакции в YDB. + +{% endif %} + + +{% endif %} + +{% if tech %} + +## Отладочные и служебные {#debug} + +{% if feature_webui %} + +### `DirectRead` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Служебная настройка для работы preview таблиц в [HTTP API](../interfaces/http.md) (для веб-интерфейса и консольного клиента). +{% endif %} + +### `config.flags("ValidateUdf", "Lazy")` + +| Тип значения | По умолчанию | +| --- | --- | +| Строка: None / Lazy / Greedy | None | + +Валидация результатов UDF на соответствие объявленной сигнатуре. Greedy режим форсирует материализацию «ленивых» контейнеров, а Lazy — нет. + +### `{{ backend_name_lower }}.DefaultCluster` + +| Тип значения | По умолчанию | +| --- | --- | +| Строка с именем кластера | hahn | + +Выбор кластера для выполнения вычислений, не использующих таблицы. + +### `config.flags("Diagnostics")` + +| Тип значения | По умолчанию | +| --- | --- | +| Флаг | false | + +Получение диагностической информации от YQL в виде дополнительного результата запроса. + +{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/process.md b/ydb/docs/ru/core/yql/reference/syntax/process.md similarity index 84% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/process.md rename to ydb/docs/ru/core/yql/reference/syntax/process.md index f260f96e3fbe..0987308f6ac2 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/process.md +++ b/ydb/docs/ru/core/yql/reference/syntax/process.md @@ -1,8 +1,8 @@ # {{ process_command }} -Преобразовать входную таблицу с помощью {% if oss != true %}UDF на [C++](../../udf/cpp.md){% if yt %}, [Python](../../udf/python.md) или [JavaScript](../../udf/javascript.md){% endif %} или {% endif %}[лямбда функции](../../syntax/expressions.md#lambda), которая применяется последовательно к каждой строке входа и имеет возможность для каждой строки входа создать ноль, одну или несколько строк результата (аналог Map в терминах MapReduce). +Преобразовать входную таблицу с помощью {% if oss != true %}UDF на [C++](../udf/cpp.md){% if yt %}, [Python](../udf/python.md) или [JavaScript](../udf/javascript.md){% endif %} или {% endif %}[лямбда функции](expressions.md#lambda), которая применяется последовательно к каждой строке входа и имеет возможность для каждой строки входа создать ноль, одну или несколько строк результата (аналог Map в терминах MapReduce). -{% if feature_mapreduce %}Таблица по имени ищется в базе данных, заданной оператором [USE](../use.md).{% endif %} +{% if feature_mapreduce %}Таблица по имени ищется в базе данных, заданной оператором [USE](use.md).{% endif %} В параметрах вызова функции после ключевого слова `USING` явно указывается, значения из каких колонок и в каком порядке передавать для каждой строки входа. @@ -17,7 +17,7 @@ В качестве `OutputType` может выступать один из типов: * `Struct<...>` — у `{{ process_command }}` будет ровно один выход с записями заданной структуры, представляющий собой плоскую таблицу с колонками соответствующими полям `Struct<...>` -* `Variant,...>` — у `{{ process_command }}` число выходов будет равно числу альтернатив в `Variant`. Записи каждого выхода представлены плоской таблицей с колонками по полям из соответствующей альтернативы. Ко множеству выходов `{{ process_command }}` в этом случае можно обратиться как к кортежу (`Tuple`) списков, который можно распаковать в отдельные [именованные выражения](../expressions.md#named-nodes) и использовать независимо. +* `Variant,...>` — у `{{ process_command }}` число выходов будет равно числу альтернатив в `Variant`. Записи каждого выхода представлены плоской таблицей с колонками по полям из соответствующей альтернативы. Ко множеству выходов `{{ process_command }}` в этом случае можно обратиться как к кортежу (`Tuple`) списков, который можно распаковать в отдельные [именованные выражения](expressions.md#named-nodes) и использовать независимо. В списке аргументов функции после ключевого слова `USING` можно передать одно из двух специальных именованных выражений: @@ -26,13 +26,13 @@ {% note info "Примечание" %} -После выполнения `{{ process_command }}` в рамках того же запроса по результирующей таблице (или таблицам) можно выполнить {% if select_command != "SELECT STREAM" %}[SELECT](../select/index.md), [REDUCE](../reduce.md){% else %}[SELECT STREAM](../select_stream.md){% endif %}, [INSERT INTO](../insert_into.md), ещё один `{{ process_command }}` и так далее в зависимости от необходимого результата. +После выполнения `{{ process_command }}` в рамках того же запроса по результирующей таблице (или таблицам) можно выполнить {% if select_command != "SELECT STREAM" %}[SELECT](select/index.md), [REDUCE](reduce.md){% else %}[SELECT STREAM](select_stream.md){% endif %}, [INSERT INTO](insert_into.md), ещё один `{{ process_command }}` и так далее в зависимости от необходимого результата. {% endnote %} Ключевое слово `USING` и указание функции необязательны: если они не указаны, то возвращается исходная таблица. {% if feature_subquery %}Это может быть удобно для применения [шаблона подзапроса](subquery.md).{% endif %} -В `{{ process_command }}` можно передать несколько входов (под входом здесь подразумевается таблица,{% if select_command != "PROCESS STREAM" %} {% if feature_bulk_tables %}[диапазон таблиц](../select/concat.md){% else %}диапазон таблиц{% endif %}{% endif %}, подзапрос, [именованное выражение](../expressions.md#named-nodes)), разделенных запятой. В функцию из `USING` в этом случае можно передать только специальные именованные выражения `TableRow()` или `TableRows()`, которые будут иметь следующий тип: +В `{{ process_command }}` можно передать несколько входов (под входом здесь подразумевается таблица,{% if select_command != "PROCESS STREAM" %} {% if feature_bulk_tables %}[диапазон таблиц](select/concat.md){% else %}диапазон таблиц{% endif %}{% endif %}, подзапрос, [именованное выражение](expressions.md#named-nodes)), разделенных запятой. В функцию из `USING` в этом случае можно передать только специальные именованные выражения `TableRow()` или `TableRows()`, которые будут иметь следующий тип: * `TableRow()` — альтернатива (`Variant`), где каждый элемент имеет тип структуры записи из соответствущего входа. Для каждой входной строки в альтернативе заполнен элемент, соответствущий номеру входа этой строки * `TableRows()` — ленивый итератор по альтернативам, с точки зрения типов — `Stream>`. Альтернатива имеет такую же семантику, что и для `TableRow()` @@ -125,3 +125,4 @@ SELECT STREAM * FROM $p; ``` {% endif %} + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/reduce.md b/ydb/docs/ru/core/yql/reference/syntax/reduce.md similarity index 84% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/reduce.md rename to ydb/docs/ru/core/yql/reference/syntax/reduce.md index 4195e5a1484f..f12aabe3beed 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/reduce.md +++ b/ydb/docs/ru/core/yql/reference/syntax/reduce.md @@ -1,10 +1,11 @@ + # REDUCE Выполняет группировку входа по указанным ключевым столбцам, затем передает текущие ключи и ленивый итератор соответствующих им значений из остальных колонок на обработку в указанную UDF. По аналогии с `PROCESS` UDF может вернуть произвольное количество строк результата на каждый вызов, а также возвращать альтернативы (`Variant`) для создания множества выходов. В терминах MapReduce очень близок к Reduce. Указываемые следом ключевые слова: -* `PRESORT` (опционально)— указание порядка внутри каждой группы, синтаксис аналогичен [ORDER BY](../select/order_by.md); +* `PRESORT` (опционально)— указание порядка внутри каждой группы, синтаксис аналогичен [ORDER BY](select/order_by.md); * `ON` (обязательно) — указание ключевых столбцов; * `USING` или `USING ALL` (обязательно) — вызов UDF, о правилах подробнее ниже. @@ -22,9 +23,9 @@ * Ключ для передачи в UDF формируется по следующему правилу. Если ключевая колонка одна, то её значение формирует ключ как есть, если несколько (список колонок указывается по аналогии с `GROUP BY` через запятую), то ключ будет формироваться как кортеж (`Tuple`) со значениями из перечисленных колонок в указанном порядке. * При вызове `REDUCE` в запросе в круглых скобках после имени UDF указываются только выражение, значения которого будут переданы в качестве элементов итератора (второй аргумент UDF для `USING` или второй элемент кортежа для `USING ALL`). -Результат формируется аналогичным [PROCESS](../process.md) образом. Также доступно ключевое слово `TableRow()` для получения строки целиком в виде структуры. +Результат формируется аналогичным [PROCESS](process.md) образом. Также доступно ключевое слово `TableRow()` для получения строки целиком в виде структуры. -В `REDUCE` можно передать несколько входов (под входом здесь подразумевается таблица, [диапазон таблиц](../select/concat.md), подзапрос, [именованное выражение](../expressions.md#named-nodes)), разделенных запятой. Все входы обязаны иметь указанные в `ON` ключевые колонки совпадающего типа. В функцию из `USING` в этом случае можно передать только специальное именованное выражение `TableRow()`. Второй аргумент (или второй элемент кортежа для `USING ALL`) будет содержать ленивый итератор альтернатив с заполненным элементом, соответствущим номеру входа текущей записи. +В `REDUCE` можно передать несколько входов (под входом здесь подразумевается таблица, [диапазон таблиц](select/concat.md), подзапрос, [именованное выражение](expressions.md#named-nodes)), разделенных запятой. Все входы обязаны иметь указанные в `ON` ключевые колонки совпадающего типа. В функцию из `USING` в этом случае можно передать только специальное именованное выражение `TableRow()`. Второй аргумент (или второй элемент кортежа для `USING ALL`) будет содержать ленивый итератор альтернатив с заполненным элементом, соответствущим номеру входа текущей записи. После `USING` в `REDUCE` можно опционально указать `ASSUME ORDER BY` со списком столбцов. Результат такого `REDUCE` будет считаться сортированным, но без выполнения фактической сортировки. Проверка сортированности осуществляется на этапе исполнения запроса. Поддерживается задание порядка сортировки с помощью ключевых слов `ASC` (по возрастанию) и `DESC` (по убыванию). Выражения в `ASSUME ORDER BY` не поддерживается. @@ -94,7 +95,7 @@ $udf = Python::MyReducer(Callable<( $script ); -REDUCE hahn.`home/yql/tutorial/users` +REDUCE my_table ON region USING $udf((name, last_visit_time)); ``` @@ -106,3 +107,4 @@ $udf = Python::MyReducer(Callable<(String, Stream,Struct<... REDUCE my_table1, my_table2 ON key USING $udf(TableRow()); ``` + diff --git a/ydb/docs/ru/core/yql/reference/syntax/replace_into.md b/ydb/docs/ru/core/yql/reference/syntax/replace_into.md new file mode 100644 index 000000000000..6426dad9f108 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/replace_into.md @@ -0,0 +1,36 @@ +# REPLACE INTO + +{% if oss == true and backend_name == "YDB" %} + +{% note warning %} + +{% include [OLAP_not_allow_text](../../../_includes/not_allow_for_olap_text.md) %} + +{% include [ways_add_data_to_olap](../../../_includes/ways_add_data_to_olap.md) %} + +{% endnote %} + +{% endif %} + +В отличие от [`INSERT INTO`](insert_into.md) и [`UPDATE`](update.md), запросы [`UPSERT INTO`](upsert_into.md) и `REPLACE INTO` не требуют предварительного чтения данных, поэтому выполняются быстрее. `REPLACE INTO` сохраняет данные в {% if backend_name == "YDB" and oss == true %}строковую таблицу{% else %}таблицу{% endif %} с перезаписью строк по первичному ключу.{% if feature_mapreduce %} Таблица по имени ищется в базе данных, заданной оператором [USE](use.md).{% endif %} Если заданный первичный ключ отсутствует, в таблицу будет добавлена новая строка. Если задан существующий `PRIMARY_KEY`, строка будет перезаписана. При этом значения столбцов, не участвующих в операции, заменяются на значения по умолчанию. + +## Примеры + +* Задание значений для `REPLACE INTO` c помощью `VALUES`: + +```yql + REPLACE INTO my_table (Key1, Key2, Value2) VALUES + (1u, "One", 101), + (2u, "Two", 102); + COMMIT; + ``` + +* Получение значений для `REPLACE INTO` с помощью выборки `SELECT`: + +```yql + REPLACE INTO my_table + SELECT Key AS Key1, "Empty" AS Key2, Value AS Value1 + FROM my_table1; + COMMIT; + ``` + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/revoke.md b/ydb/docs/ru/core/yql/reference/syntax/revoke.md similarity index 97% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/revoke.md rename to ydb/docs/ru/core/yql/reference/syntax/revoke.md index f847e7e87e78..f1d979597ab6 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/revoke.md +++ b/ydb/docs/ru/core/yql/reference/syntax/revoke.md @@ -14,7 +14,7 @@ REVOKE [GRANT OPTION FOR] {{permission_name} [, ...] | ALL [PRIVILEGES]} ON {pat `GRANT OPTION FOR` - использование этой конструкции отзывает у пользователя или группы право управлять правами доступа. Все ранее выданные этим пользователем права остаются в силе. Конструкция имеет функцианальность аналогичную отзыву права `"ydb.access.grant"` или `GRANT`. -{% include [x](_includes/permissions/permissions_list.md) %} +{% include [x](../_includes/permissions_list.md) %} ## Примеры diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/assume_order_by.md b/ydb/docs/ru/core/yql/reference/syntax/select/assume_order_by.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/assume_order_by.md rename to ydb/docs/ru/core/yql/reference/syntax/select/assume_order_by.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/concat.md b/ydb/docs/ru/core/yql/reference/syntax/select/concat.md similarity index 82% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/select/concat.md rename to ydb/docs/ru/core/yql/reference/syntax/select/concat.md index a52384d50929..93c4f9fc0538 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/concat.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select/concat.md @@ -1,6 +1,6 @@ # Обращение к нескольким таблицам в одном запросе -В стандартном SQL для выполнения запроса по нескольким таблицам используется [UNION ALL](../select/union.md#union_all), который объединяет результаты двух и более `SELECT`. Это не совсем удобно для сценария использования, в котором требуется выполнить один и тот же запрос по нескольким таблицам (например, содержащим данные на разные даты). В YQL, чтобы было удобнее, в `SELECT` после `FROM` можно указывать не только одну таблицу или подзапрос, но и вызывать встроенные функции, позволяющие объединять данные нескольких таблиц. +В стандартном SQL для выполнения запроса по нескольким таблицам используется [UNION ALL](union.md#union-all), который объединяет результаты двух и более `SELECT`. Это не совсем удобно для сценария использования, в котором требуется выполнить один и тот же запрос по нескольким таблицам (например, содержащим данные на разные даты). В YQL, чтобы было удобнее, в `SELECT` после `FROM` можно указывать не только одну таблицу или подзапрос, но и вызывать встроенные функции, позволяющие объединять данные нескольких таблиц. Для этих целей определены следующие функции: @@ -16,7 +16,7 @@ ```LIKE(`prefix`, `pattern`, `suffix`, `view`)``` и ```REGEXP(`prefix`, `pattern`, `suffix`, `view`)``` — аргумент pattern задается в формате, аналогичном одноименным бинарным операторам: [LIKE](../expressions.md#like) и [REGEXP](../expressions.md#regexp). -```FILTER(`prefix`, `callable`, `suffix`, `view`)``` — аргумент callable должен являться вызываемым выражением с сигнатурой `(String)->Bool`, который будет вызван для каждой таблицы/подкаталога в каталоге prefix. В запросе будут участвовать только те таблицы, для которых вызываемое значение вернуло `true`. В качестве вызываемого значения удобнее всего использовать [лямбда функции](../expressions.md#lambda){% if yql == true %}, либо UDF на [Python](../../../udf/python.md) или [JavaScript](../../../udf/javascript.md){% endif %}. +```FILTER(`prefix`, `callable`, `suffix`, `view`)``` — аргумент callable должен являться вызываемым выражением с сигнатурой `(String)->Bool`, который будет вызван для каждой таблицы/подкаталога в каталоге prefix. В запросе будут участвовать только те таблицы, для которых вызываемое значение вернуло `true`. В качестве вызываемого значения удобнее всего использовать [лямбда функции](../expressions.md#lambda){% if yql == true %}, либо UDF на [Python](../../udf/python.md) или [JavaScript](../../udf/javascript.md){% endif %}. {% note warning %} @@ -26,7 +26,7 @@ {% endnote %} -По умолчанию схемы всех участвующих таблиц объединяются по правилам [UNION ALL](./index.md#union_all). Если объединение схем не желательно, то можно использовать функции с суффиксом `_STRICT`, например `CONCAT_STRICT` или `RANGE_STRICT`, которые работают полностью аналогично оригинальным, но считают любое расхождение в схемах таблиц ошибкой. +По умолчанию схемы всех участвующих таблиц объединяются по правилам [UNION ALL](union.md#union-all). Если объединение схем не желательно, то можно использовать функции с суффиксом `_STRICT`, например `CONCAT_STRICT` или `RANGE_STRICT`, которые работают полностью аналогично оригинальным, но считают любое расхождение в схемах таблиц ошибкой. Для указания кластера объединяемых таблиц нужно указать его перед названием функции. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/distinct.md b/ydb/docs/ru/core/yql/reference/syntax/select/distinct.md similarity index 72% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/distinct.md rename to ydb/docs/ru/core/yql/reference/syntax/select/distinct.md index 8cf9a527521f..13ff5d78d5bd 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/distinct.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select/distinct.md @@ -4,7 +4,7 @@ {% note info %} -Применение `DISTINCT` к вычислимым значениям на данный момент не реализовано. С этой целью можно использовать подзапрос или выражение [`GROUP BY ... AS ...`](../../group_by.md). +Применение `DISTINCT` к вычислимым значениям на данный момент не реализовано. С этой целью можно использовать подзапрос или выражение [`GROUP BY ... AS ...`](../group_by.md). {% endnote %} @@ -15,4 +15,4 @@ SELECT DISTINCT value -- только уникальные значения из FROM my_table; ``` -Также ключевое слово `DISTINCT` может использоваться для применения [агрегатных функций](../../../builtins/aggregation.md) только к уникальным значениям. Подробнее см. в документации по [GROUP BY](../../group_by.md). \ No newline at end of file +Также ключевое слово `DISTINCT` может использоваться для применения [агрегатных функций](../../builtins/aggregation.md) только к уникальным значениям. Подробнее см. в документации по [GROUP BY](../group_by.md). diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/folder.md b/ydb/docs/ru/core/yql/reference/syntax/select/folder.md similarity index 81% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/folder.md rename to ydb/docs/ru/core/yql/reference/syntax/select/folder.md index c1de9ecb8640..cff35146332d 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/folder.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select/folder.md @@ -1,7 +1,7 @@ # Перечисление содержимого директории на кластере -Указывается как функция `FOLDER` в [FROM](../../select/from.md). +Указывается как функция `FOLDER` в [FROM](from.md). Аргументы: @@ -16,9 +16,9 @@ Рекомендации по использованию: -* Чтобы получить только список таблиц, нужно не забывать добавлять `...WHERE Type == "table"`. Затем, опционально добавив ещё условий, с помощью агрегатной функции [AGGREGATE_LIST](../../../builtins/aggregation.md#aggregate-list) от колонки Path можно получить только список путей и передать их в [EACH](#each). -* Так как колонка Path выдаётся в том же формате, что и результат функции [TablePath()](../../../builtins/basic.md#tablepath), то их можно использоваться для JOIN атрибутов таблицы к её строкам. -* C колонкой Attributes рекомендуется работать через [Yson UDF](../../../udf/list/yson.md). +* Чтобы получить только список таблиц, нужно не забывать добавлять `...WHERE Type == "table"`. Затем, опционально добавив ещё условий, с помощью агрегатной функции [AGGREGATE_LIST](../../builtins/aggregation.md#aggregate-list) от колонки Path можно получить только список путей и передать их в [EACH](concat.md). +* Так как колонка Path выдаётся в том же формате, что и результат функции [TablePath()](../../builtins/basic.md#tablepath), то их можно использоваться для JOIN атрибутов таблицы к её строкам. +* C колонкой Attributes рекомендуется работать через [Yson UDF](../../udf/list/yson.md). {% note warning %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/from.md b/ydb/docs/ru/core/yql/reference/syntax/select/from.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/select/from.md rename to ydb/docs/ru/core/yql/reference/syntax/select/from.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/from_as_table.md b/ydb/docs/ru/core/yql/reference/syntax/select/from_as_table.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/from_as_table.md rename to ydb/docs/ru/core/yql/reference/syntax/select/from_as_table.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/from_select.md b/ydb/docs/ru/core/yql/reference/syntax/select/from_select.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/from_select.md rename to ydb/docs/ru/core/yql/reference/syntax/select/from_select.md diff --git a/ydb/docs/ru/core/yql/reference/syntax/select/index.md b/ydb/docs/ru/core/yql/reference/syntax/select/index.md new file mode 100644 index 000000000000..f86d2398bdb5 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/select/index.md @@ -0,0 +1,255 @@ +## SELECT + +Возвращает результат вычисления выражений, указанных после `SELECT`. + +Может использоваться в сочетании с другими операциями для получения иного эффекта. + +### Примеры + +```yql +SELECT "Hello, world!"; +``` + +```yql +SELECT 2 + 2; +``` + + +## Процедура выполнения SELECT {#selectexec} + +Результат запроса `SELECT` вычисляется следующим образом: + +* определяется набор входных таблиц – вычисляются выражения после [FROM](../select/from.md); +* к входным таблицам применяется [SAMPLE](sample.md) / [TABLESAMPLE](sample.md) +* выполняется [FLATTEN COLUMNS](../flatten.md#flatten-columns) или [FLATTEN BY](../flatten.md); алиасы, заданные во `FLATTEN BY`, становятся видны после этой точки; +{% if feature_join %} +* выполняются все [JOIN](../join.md); +{% endif %} +* к полученным данным добавляются (или заменяются) колонки, заданные в [GROUP BY ... AS ...](../group_by.md); +* выполняется [WHERE](where.md) — все данные не удовлетворяющие предикату отфильтровываются; +* выполняется [GROUP BY](../group_by.md), вычисляются значения агрегатных функций; +* выполняется фильтрация [HAVING](../group_by.md#having); +{% if feature_window_functions %} +* вычисляются значения [оконных функций](../window.md); +{% endif %} +* вычисляются выражения в `SELECT`; +* выражениям в `SELECT` назначаются имена заданные алиасами; +* к полученным таким образом колонкам применяется top-level [DISTINCT](distinct.md); +* таким же образом вычисляются все подзапросы в [UNION ALL](union.md#union-all), выполняется их объединение (см. [PRAGMA AnsiOrderByLimitInUnionAll](../pragma.md#pragmas)); +* выполняется сортировка согласно [ORDER BY](order_by.md); +* к полученному результату применяются [OFFSET и LIMIT](limit_offset.md). + +## Порядок колонок в YQL {#orderedcolumns} + +В стандартном SQL порядок колонок указанных в проекции (в `SELECT`) имеет значение. Помимо того, что порядок колонок должен сохраняться при отображении результатов запроса или при записи в новую таблицу, некоторые конструкции SQL этот порядок используют. +Это относится в том числе к [UNION ALL](union.md#union-all) и к позиционному [ORDER BY](order_by.md) (ORDER BY ordinal). + +По умолчанию в YQL порядок колонок игнорируется: + +* порядок колонок в выходных таблицах и в результатах запроса не определен +* схема данных результата `UNION ALL` выводится по именам колонок, а не по позициям + +При включении `PRAGMA OrderedColumns;` порядок колонок сохраняется в результатах запроса и выводится из порядка колонок во входных таблицах по следующим правилам: + +* `SELECT` с явным перечислением колонок задает соответствующий порядок; +* `SELECT` со звездочкой (`SELECT * FROM ...`) наследует порядок из своего входа; + +{% if feature_join %} + +* порядок колонок после [JOIN](../join.md): сначала колонки левой стороны, потом правой. Если порядок какой-либо из сторон присутствующей в выходе `JOIN` не определен, порядок колонок результата также не определен; + +{% endif %} + +* порядок `UNION ALL` зависит от режима выполнения [UNION ALL](union.md#union-all); +* порядок колонок для [AS_TABLE](from_as_table.md) не определен; + + +## Комбинация запросов {#combining-queries} + +Результаты нескольких SELECT (или подзапросов) могут быть объединены с помощью ключевых слов `UNION` и `UNION ALL`. + +```yql +query1 UNION [ALL] query2 (UNION [ALL] query3 ...) +``` + +Объединение более двух запросов интерпретируется как левоассоциативная операция, то есть + +```yql +query1 UNION query2 UNION ALL query3 +``` + +интерпретируется как + +```yql +(query1 UNION query2) UNION ALL query3 +``` + +При наличии `ORDER BY/LIMIT/DISCARD/INTO RESULT` в объединяемых подзапросах применяются следующие правила: + +* `ORDER BY/LIMIT/INTO RESULT` допускается только после последнего подзапроса; +* `DISCARD` допускается только перед первым подзапросом; +* указанные операторы действуют на результат `UNION [ALL]`, а не на подзапрос; +* чтобы применить оператор к подзапросу, подзапрос необходимо взять в скобки. + + +## Обращение к нескольким таблицам в одном запросе + +В стандартном SQL для выполнения запроса по нескольким таблицам используется [UNION ALL](union.md#union-all), который объединяет результаты двух и более `SELECT`. Это не совсем удобно для сценария использования, в котором требуется выполнить один и тот же запрос по нескольким таблицам (например, содержащим данные на разные даты). В YQL, чтобы было удобнее, в `SELECT` после `FROM` можно указывать не только одну таблицу или подзапрос, но и вызывать встроенные функции, позволяющие объединять данные нескольких таблиц. + +Для этих целей определены следующие функции: + +```CONCAT(`table1`, `table2`, `table3` VIEW view_name, ...)``` — объединяет все перечисленные в аргументах таблицы. + +`EACH($list_of_strings)` или `EACH($list_of_strings VIEW view_name)` — объединяет все таблицы, имена которых перечислены в списке строк. Опционально можно передать несколько списков в отдельных аргументах по аналогии с `CONCAT`. + +```RANGE(`prefix`, `min`, `max`, `suffix`, `view`)``` — объединяет диапазон таблиц. Аргументы: + +* prefix — каталог для поиска таблиц, указывается без завершающего слеша. Единственный обязательный аргумент, если указан только он, то используются все таблицы в данном каталоге. +* min, max — следующие два аргумента задают диапазон имен для включения таблиц. Диапазон инклюзивный с обоих концов. Если диапазон не указан, используются все таблицы в каталоге prefix. Имена таблиц или директорий, находящихся в указанной в prefix директории, сравниваются с диапазоном `[min, max]` лексикографически, а не конкатенируются, таким образом важно указывать диапазон без лидирующих слешей. +* suffix — имя таблицы. Ожидается без начального слеша. Если suffix не указан, то аргументы `[min, max]` задают диапазон имен таблиц. Если suffix указан, то аргументы `[min, max]` задают диапазон папок, в которых существует таблица с именем, указанным в аргументе suffix. + +```LIKE(`prefix`, `pattern`, `suffix`, `view`)` и `REGEXP(`prefix`, `pattern`, `suffix`, `view`)``` — аргумент pattern задается в формате, аналогичном одноименным бинарным операторам: [LIKE](../expressions.md#like) и [REGEXP](../expressions.md#regexp). + +```FILTER(`prefix`, `callable`, `suffix`, `view`)``` — аргумент callable должен являться вызываемым выражением с сигнатурой `(String)->Bool`, который будет вызван для каждой таблицы/подкаталога в каталоге prefix. В запросе будут участвовать только те таблицы, для которых вызываемое значение вернуло `true`. В качестве вызываемого значения удобнее всего использовать [лямбда функции](../expressions.md#lambda){% if yql == true %}, либо UDF на [Python](../../udf/python.md) или [JavaScript](../../udf/javascript.md){% endif %}. + +{% note warning %} + +Порядок, в котором будут объединены таблицы, всеми вышеперечисленными функциями не гарантируется. + +Список таблиц вычисляется **до** запуска самого запроса. Поэтому созданные в процессе запроса таблицы не попадут в результаты функции. + +{% endnote %} + +По умолчанию схемы всех участвующих таблиц объединяются по правилам [UNION ALL](union.md#union-all). Если объединение схем не желательно, то можно использовать функции с суффиксом `_STRICT`, например `CONCAT_STRICT` или `RANGE_STRICT`, которые работают полностью аналогично оригинальным, но считают любое расхождение в схемах таблиц ошибкой. + +Для указания кластера объединяемых таблиц нужно указать его перед названием функции. + +Все аргументы описанных выше функций могут быть объявлены отдельно через [именованные выражения](../expressions.md#named-nodes). В этом случае в них также допустимы и простые выражения посредством неявного вызова [EvaluateExpr](../../builtins/basic.md#evaluate_expr_atom). + +Имя исходной таблицы, из которой изначально была получена каждая строка, можно получить при помощи функции [TablePath()](../../builtins/basic.md#tablepath). + +### Примеры + +```yql +USE some_cluster; +SELECT * FROM CONCAT( + `table1`, + `table2`, + `table3`); +``` + +```yql +USE some_cluster; +$indices = ListFromRange(1, 4); +$tables = ListMap($indices, ($index) -> { + RETURN "table" || CAST($index AS String); +}); +SELECT * FROM EACH($tables); -- идентично предыдущему примеру +``` + +```yql +USE some_cluster; +SELECT * FROM RANGE(`my_folder`); +``` + +```yql +SELECT * FROM some_cluster.RANGE( -- Кластер можно указать перед названием функции + `my_folder`, + `from_table`, + `to_table`); +``` + +```yql +USE some_cluster; +SELECT * FROM RANGE( + `my_folder`, + `from_folder`, + `to_folder`, + `my_table`); +``` + +```yql +USE some_cluster; +SELECT * FROM RANGE( + `my_folder`, + `from_table`, + `to_table`, + ``, + `my_view`); +``` + +```yql +USE some_cluster; +SELECT * FROM LIKE( + `my_folder`, + "2017-03-%" +); +``` + +```yql +USE some_cluster; +SELECT * FROM REGEXP( + `my_folder`, + "2017-03-1[2-4]?" +); +``` + +```yql +$callable = ($table_name) -> { + return $table_name > "2017-03-13"; +}; + +USE some_cluster; +SELECT * FROM FILTER( + `my_folder`, + $callable +); +``` + +## Поддерживаемые конструкции в SELECT + +* [FROM](from.md) +* [FROM AS_TABLE](from_as_table.md) +* [FROM SELECT](from_select.md) +* [DISTINCT](distinct.md) +* [UNIQUE DISTINCT](unique_distinct_hints.md) +* [UNION](union.md) +* [WITH](with.md) +* [WITHOUT](without.md) +* [WHERE](where.md) +* [ORDER BY](order_by.md) +* [ASSUME ORDER BY](assume_order_by.md) +* [LIMIT OFFSET](limit_offset.md) +* [SAMPLE](sample.md) +* [TABLESAMPLE](sample.md) + +{% if yt %} + +* [FOLDER](folder.md) +* [WalkFolders](walk_folders.md) + +{% endif %} + +{% if feature_mapreduce %} + +* [VIEW](view.md) + +{% endif %} + +{% if feature_temp_table %} + +* [TEMPORARY TABLE](temporary_table.md) + +{% endif %} + +{% if feature_bulk_tables %} + +* [CONCAT](concat.md) + +{% endif %} + +{% if feature_secondary_index %} + +* [VIEW INDEX](secondary_index.md) + +{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/limit_offset.md b/ydb/docs/ru/core/yql/reference/syntax/select/limit_offset.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/limit_offset.md rename to ydb/docs/ru/core/yql/reference/syntax/select/limit_offset.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/order_by.md b/ydb/docs/ru/core/yql/reference/syntax/select/order_by.md similarity index 97% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/order_by.md rename to ydb/docs/ru/core/yql/reference/syntax/select/order_by.md index df08aea2c960..42405409d821 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/order_by.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select/order_by.md @@ -19,6 +19,6 @@ ORDER BY key DESC, LENGTH(string_column) ASC; {% if feature_window_functions %} -Ключевое слово `ORDER BY` также может использоваться в механизме [оконных функций](../../window.md). +Ключевое слово `ORDER BY` также может использоваться в механизме [оконных функций](../window.md). {% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/sample.md b/ydb/docs/ru/core/yql/reference/syntax/select/sample.md similarity index 97% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/sample.md rename to ydb/docs/ru/core/yql/reference/syntax/select/sample.md index 5ac3fe9dfb9c..2d462b75a022 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/sample.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select/sample.md @@ -2,7 +2,7 @@ {% if oss == true and backend_name == "YDB" %} -{% include [olap_warning_note](../../../../../_includes/not_allow_for_olap_note.md) %} +{% include [olap_warning_note](../../../../_includes/not_allow_for_olap_note.md) %} {% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/secondary_index.md b/ydb/docs/ru/core/yql/reference/syntax/select/secondary_index.md similarity index 73% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/secondary_index.md rename to ydb/docs/ru/core/yql/reference/syntax/select/secondary_index.md index 776580367692..d41b23a61e1f 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/secondary_index.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select/secondary_index.md @@ -2,7 +2,7 @@ {% if oss == true and backend_name == "YDB" %} -{% include [olap_warning_note](../../../../../_includes/not_allow_for_olap_note.md) %} +{% include [olap_warning_note](../../../../_includes/not_allow_for_olap_note.md) %} {% endif %} @@ -24,7 +24,7 @@ SELECT series_id, title, info, release_date, views, uploaded_user_id WHERE views >= someValue ``` -Сделать [`JOIN`](../../join.md) строковых таблиц `series` и `users` c заданным полем `userName` по индексам `users_index` и `name_index` соответственно: +Сделать [`JOIN`](../join.md) строковых таблиц `series` и `users` c заданным полем `userName` по индексам `users_index` и `name_index` соответственно: ```yql SELECT t1.series_id, t1.title diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/temporary_table.md b/ydb/docs/ru/core/yql/reference/syntax/select/temporary_table.md similarity index 97% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/temporary_table.md rename to ydb/docs/ru/core/yql/reference/syntax/select/temporary_table.md index 4f427f7fdecf..782ba2140bfe 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/temporary_table.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select/temporary_table.md @@ -20,7 +20,7 @@ UNION ALL SELECT * FROM @my_temp_table WHERE value = "456"; ``` -В имени временной таблицы может использоваться [именованное выражение](../../expressions.md#named-nodes): +В имени временной таблицы может использоваться [именованное выражение](../expressions.md#named-nodes): ```yql $tmp_name = "my_temp_table"; @@ -31,4 +31,4 @@ SELECT 1 AS one, 2 AS two, 3 AS three; COMMIT; SELECT * FROM @$tmp_name; -``` \ No newline at end of file +``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/toc_i.yaml b/ydb/docs/ru/core/yql/reference/syntax/select/toc_i.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/select/toc_i.yaml rename to ydb/docs/ru/core/yql/reference/syntax/select/toc_i.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/toc_p.yaml b/ydb/docs/ru/core/yql/reference/syntax/select/toc_p.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/select/toc_p.yaml rename to ydb/docs/ru/core/yql/reference/syntax/select/toc_p.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/union_all.md b/ydb/docs/ru/core/yql/reference/syntax/select/union.md similarity index 67% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/union_all.md rename to ydb/docs/ru/core/yql/reference/syntax/select/union.md index 76a67eec05c8..6ea31a32d0f7 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/union_all.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select/union.md @@ -1,12 +1,38 @@ +# Объединение результатов подзапросов (UNION) + +{% if oss == true and backend_name == "YDB" %} + +{% include [olap_warning_note](../../../../_includes/not_allow_for_olap_note.md) %} + +{% endif %} + +## UNION {#union} + +Объединение результатов нескольких подзапросов с удалением дубликатов. +Поведение идентично последовательному исполнению `UNION ALL` и `SELECT DISTINCT *`. +См. [UNION ALL](#union-all) для информации о деталях поведения. + +### Примеры + +```yql +SELECT key FROM T1 +UNION +SELECT key FROM T2 -- возвращает таблицу различных ключей, лежащих хотя бы в одной из исходных таблиц +``` + + ## UNION ALL {#union-all} Конкатенация результатов нескольких `SELECT` (или подзапросов). -Поддерживаются два режима выполнения `UNION ALL` – по именам колонок (режим по умолчанию) и по позициям колонок (соответствует стандарту ANSI SQL и включается через соответствующую [PRAGMA](../../pragma.md#positionalunionall)). +Поддерживаются два режима выполнения `UNION ALL` – по именам колонок (режим по умолчанию) и по позициям колонок (соответствует стандарту ANSI SQL и включается через соответствующую [PRAGMA](../pragma.md#positionalunionall)). В режиме "по именам" результирующая схема данных выводится по следующим правилам: -{% include [union all rules](union_all_rules.md) %} +* в результирующую таблицу включаются все колонки, которые встречались хоть в одной из входных таблиц; +* если колонка присутствовала не во всех входных таблицах, то ей автоматически присваивается [опциональный тип данных](../../types/optional.md) (допускающий значение `NULL`); +* если колонка в разных входных таблицах имела разные типы, то выводится общий тип (наиболее широкий); +* если колонка в разных входных таблицах имела разнородный тип, например строку и число, то это считается ошибкой. Порядок выходных колонок в этом режиме выводится как наибольший общий префикс порядка входов, после чего следуют все остальные колонки в алфавитном порядке. Если наибольший общий префикс пуст (в том числе и из-за отсутствия порядка на одном из входов), то порядок выхода не определен. @@ -70,3 +96,4 @@ SELECT * FROM @tmp; {% endnote %} {% endif %} + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/unique_distinct_hints.md b/ydb/docs/ru/core/yql/reference/syntax/select/unique_distinct_hints.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/unique_distinct_hints.md rename to ydb/docs/ru/core/yql/reference/syntax/select/unique_distinct_hints.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/view.md b/ydb/docs/ru/core/yql/reference/syntax/select/view.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/view.md rename to ydb/docs/ru/core/yql/reference/syntax/select/view.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/walk_folders.md b/ydb/docs/ru/core/yql/reference/syntax/select/walk_folders.md similarity index 96% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/walk_folders.md rename to ydb/docs/ru/core/yql/reference/syntax/select/walk_folders.md index b26048d37350..6e820bf72d7a 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/walk_folders.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select/walk_folders.md @@ -3,7 +3,7 @@ Итератор по дереву целевого кластера, с возможностью накопить состояние, обычно список путей к таблицам. Для потомков каждого узла вызываются пользовательские функции, где можно накопить состояние; выбрать атрибуты и узлы для дальнейшего обхода. -Указывается как функция `WalkFolders` в [FROM](../../select/from.md). +Указывается как функция `WalkFolders` в [FROM](from.md). Возвращает одну колонку `State` с таким же типом, как и у `InitialState`. @@ -63,9 +63,9 @@ * **WalkFolders может создавать большую нагрузку на мастер.** Следует с осторожностью использовать WalkFolders с атрибутами, содержащими большие значения, (`schema` может быть одним из таких); обходить поддерево большого размера и/или глубины. - Запросы листинга директорий внутри одного вызова WalkFolders могут выполняться параллельно, при запросе атрибутов с большими значениями нужно **уменьшить** количество одновременных запросов прагмой [`yt.BatchListFolderConcurrency`](../pragma_yt.md#ytbatchlistfolderconcurrency). + Запросы листинга директорий внутри одного вызова WalkFolders могут выполняться параллельно, при запросе атрибутов с большими значениями нужно **уменьшить** количество одновременных запросов прагмой [`yt.BatchListFolderConcurrency`](../pragma.md#ytbatchlistfolderconcurrency). -* Хендлеры выполняются через [EvaluateExpr](../../../builtins/basic.md#evaluate_expr_atom), существует ограничение на количество узлов YQL AST. Использовать в State контейнеры очень большого размера не получиться. +* Хендлеры выполняются через [EvaluateExpr](../../builtins/basic.md#evaluate_expr_atom), существует ограничение на количество узлов YQL AST. Использовать в State контейнеры очень большого размера не получиться. Ограничение можно обойти несколькими вызовами WalkFolders с объединением результатов или сериализуя новое состояние в строку без промежуточной десериализации (например, JSON/Yson lines). @@ -77,7 +77,7 @@ Рекомендации по использованию: -* C колонкой Attributes рекомендуется работать через [Yson UDF](../../../udf/list/yson.md) +* C колонкой Attributes рекомендуется работать через [Yson UDF](../../udf/list/yson.md) * В одном запросе результат листинга для каждой директории кешируется, одно и то же поддерево можно быстро обойти заново в другом вызове WalkFolders, если так удобно @@ -231,3 +231,4 @@ $_, $paths = Unwrap($walkFoldersRes); SELECT $paths; ``` + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/where.md b/ydb/docs/ru/core/yql/reference/syntax/select/where.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/where.md rename to ydb/docs/ru/core/yql/reference/syntax/select/where.md diff --git a/ydb/docs/ru/core/yql/reference/syntax/select/with.md b/ydb/docs/ru/core/yql/reference/syntax/select/with.md new file mode 100644 index 000000000000..11ac1fbee5f6 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/syntax/select/with.md @@ -0,0 +1,62 @@ +# WITH + +Задается после источника данных во `FROM` и используется для указания дополнительных подсказок использования {% if backend_name == "YDB" %}строковых и колоночных{% endif %} таблиц. Подсказки нельзя задать для подзапросов и [именованных выражений](../expressions.md#named-nodes). + +Поддерживаются следующие значения: + +* `INFER_SCHEMA` — задает флаг вывода схемы таблицы. Поведение аналогично заданию [прагмы yt.InferSchema](../pragma.md#inferschema), только для конкретного источника данных. Можно задать число строк для выведения (число от 1 до 1000). +* `FORCE_INFER_SCHEMA` — задает флаг вывода схемы таблицы. Поведение аналогично заданию [прагмы yt.ForceInferSchema](../pragma.md#inferschema), только для конкретного источника данных. Можно задать число строк для выведения (число от 1 до 1000). +* `DIRECT_READ` — подавляет работу некоторых оптимизаторов и заставляет использовать содержимое таблицы как есть. Поведение аналогично заданию отладочной [прагмы DirectRead](../pragma.md#debug), только для конкретного источника данных. +* `INLINE` — указание на то, что содержимое таблицы небольшое и нужно использовать его представление в памяти для обработки запроса. Реальный объем таблицы при этом не контролируется, и если он большой, то запрос может упасть по превышению памяти. +* `UNORDERED` — подавляет использование исходной сортировки таблицы. +* `XLOCK` — указание на то, что нужно брать эксклюзивный лок на таблицу. Полезен, когда чтение таблицы происходит на стадии обработки [метапрограммы запроса](../action.md), а затем ее содержимое обновляется в основном запросе. Позволяет избежать потери данных, если между исполнением фазы метапрограммы и основной частью запроса внешний процесс успел изменить таблицу. +* `SCHEMA` type — указание на то, что следует использовать указанную схему таблицы целиком, игнорируя схему в метаданных. +* `COLUMNS` type — указание на то, что следует использовать указанные типы для колонок, чьи имена совпадают с именами колонок таблицы в метаданных, а также какие колонки дополнительно присутствуют в таблице. +* `IGNORETYPEV3`, `IGNORE_TYPE_V3` — задает флаг игнорирования type_v3 типов в таблице. Поведение аналогично заданию [прагмы yt.IgnoreTypeV3](../pragma.md#ignoretypev3), только для конкретного источника данных. + +{% if feature_federated_queries %} + +При работе с [внешними файловыми источниками данных](../../../../concepts/datamodel/external_data_source.md) можно дополнительно указывать ряд параметров: + +* `FORMAT` - формат хранимых данных в файловых хранилищах в [федеративных запросах](../../../../concepts/federated_query/s3/formats.md). Допустимые значения: `csv_with_names`, `tsv_with_names`, `json_list`, `json_each_row`, `json_as_string`, `parquet`, `raw`. +* `COMPRESSION` - формат сжатия файлов в файловых хранилищах в [федеративных запросах](../../../../concepts/federated_query/s3/partition_projection). Допустимые значения: [gzip](https://ru.wikipedia.org/wiki/Gzip), [zstd](https://ru.wikipedia.org/wiki/Zstandard), [lz4](https://ru.wikipedia.org/wiki/LZ4), [brotli](https://ru.wikipedia.org/wiki/Brotli), [bzip2](https://ru.wikipedia.org/wiki/Bzip2), [xz](https://ru.wikipedia.org/wiki/XZ). +* `PARTITIONED_BY` - список [колонок партиционирования](../../../../concepts/federated_query/s3/partitioning.md) данных в файловых хранилищах в федеративных запросах. Содержит список колонок в порядке их размещения в файловом хранилище. +* `projection.enabled` - флаг включения [расширенного партиционирования данных](../../../../concepts/federated_query/s3/partition_projection.md). Допустимые значения: `true`, `false`. +* `projection..type` - тип поля [расширенного партиционирования данных](../../../../concepts/federated_query/s3/partition_projection.md). Допустимые значения: `integer`, `enum`, `date`. +* `projection..` - расширенные свойства поля [расширенного партиционирования данных](../../../../concepts/federated_query/s3/partition_projection.md). + +{% endif %} + +При задании подсказок `SCHEMA` и `COLUMNS` в качестве значения типа type должен быть задан тип [структуры](../../types/containers.md). + +{% if feature_bulk_tables %} + +Если задана подсказка `SCHEMA`, то при использовании табличных функций [EACH](concat.md), [RANGE](concat.md), [LIKE](concat.md), [REGEXP](concat.md), [FILTER](concat.md) допускается пустой список таблиц, который обрабатывается как пустая таблица с колонками, описанными в `SCHEMA`. + +{% endif %} + +## Примеры + +```yql +SELECT key FROM my_table WITH INFER_SCHEMA; +SELECT key FROM my_table WITH FORCE_INFER_SCHEMA="42"; +``` + +```yql +$s = (SELECT COUNT(*) FROM my_table WITH XLOCK); + +INSERT INTO my_table WITH TRUNCATE +SELECT EvaluateExpr($s) AS a; +``` + +```yql +SELECT key, value FROM my_table WITH SCHEMA Struct; +``` + +```yql +SELECT key, value FROM my_table WITH COLUMNS Struct; +``` + +```yql +SELECT key, value FROM EACH($my_tables) WITH SCHEMA Struct>; +``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/without.md b/ydb/docs/ru/core/yql/reference/syntax/select/without.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/without.md rename to ydb/docs/ru/core/yql/reference/syntax/select/without.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select_stream.md b/ydb/docs/ru/core/yql/reference/syntax/select_stream.md similarity index 57% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select_stream.md rename to ydb/docs/ru/core/yql/reference/syntax/select_stream.md index d1f82596556d..f7d8e6028255 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select_stream.md +++ b/ydb/docs/ru/core/yql/reference/syntax/select_stream.md @@ -1,6 +1,6 @@ # SELECT STREAM ... FROM -Для работы со стримами RTMR необходимо использовать конструкцию `SELECT STREAM` вместо `SELECT` для обычных таблиц в других системах. `FROM` используется для указания источника данных. Как правило, в качестве аргумента `FROM` выступает имя стрима, который ищется в кластере, заданном оператором [USE](../use.md), но может использоваться и результат другого `SELECT STREAM` (подзапрос). Также стрим можно указать через [именованное выражение](../expressions.md#named-nodes), содержащее строку. +Для работы со стримами RTMR необходимо использовать конструкцию `SELECT STREAM` вместо `SELECT` для обычных таблиц в других системах. `FROM` используется для указания источника данных. Как правило, в качестве аргумента `FROM` выступает имя стрима, который ищется в кластере, заданном оператором [USE](use.md), но может использоваться и результат другого `SELECT STREAM` (подзапрос). Также стрим можно указать через [именованное выражение](expressions.md#named-nodes), содержащее строку. В выражениях между `SELECT STREAM` и `FROM` можно указывать имена столбцов из источника (через запятую). Специальный символ `*` в этой позиции обозначает «все столбцы». @@ -35,7 +35,11 @@ WHERE value > 0; Конкатенация результатов нескольких `SELECT STREAM`, их схемы объединяются по следующим правилам: -{% include [union all rules](../_includes/select/union_all_rules.md) %} +* в результирующую таблицу включаются все колонки, которые встречались хоть в одной из входных таблиц; +* если колонка присутствовала не во всех входных таблицах, то ей автоматически присваивается [опциональный тип данных](../types/optional.md) (допускающий значение `NULL`); +* если колонка в разных входных таблицах имела разные типы, то выводится общий тип (наиболее широкий); +* если колонка в разных входных таблицах имела разнородный тип, например строку и число, то это считается ошибкой. + ### Примеры diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/subquery.md b/ydb/docs/ru/core/yql/reference/syntax/subquery.md similarity index 85% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/subquery.md rename to ydb/docs/ru/core/yql/reference/syntax/subquery.md index 34c38046562f..3e7f92351fa7 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/subquery.md +++ b/ydb/docs/ru/core/yql/reference/syntax/subquery.md @@ -1,13 +1,14 @@ + # Шаблоны подзапросов (subquery) ## DEFINE SUBQUERY {#define-subquery} -`DEFINE SUBQUERY` позволяет объявить шаблон подзапроса (subquery), который представляет собой параметризуемый блок из нескольких выражений верхнего уровня (statements), и затем многократно его использовать путем применения в секции `FROM` выражения [SELECT](../select/index.md){% if feature_mapreduce %} или входных данных в [PROCESS](../process.md)/[REDUCE](../reduce.md){% endif %} с указанием параметров. -В отличие от [действий](../action.md) шаблон подзапроса должен заканчиваться выражением `SELECT`{% if feature_mapreduce %}/`PROCESS`/`REDUCE`{% endif %}, чей результат и является возвращаемым значением подзапроса. При этом выражение верхнего уровня `SELECT`{% if feature_mapreduce %}/`PROCESS`/`REDUCE`{% endif %} нельзя использовать более одного раза, как и модифицирующие выражения (например, `INSERT`). +`DEFINE SUBQUERY` позволяет объявить шаблон подзапроса (subquery), который представляет собой параметризуемый блок из нескольких выражений верхнего уровня (statements), и затем многократно его использовать путем применения в секции `FROM` выражения [SELECT](select/index.md){% if feature_mapreduce %} или входных данных в [PROCESS](process.md)/[REDUCE](reduce.md){% endif %} с указанием параметров. +В отличие от [действий](action.md) шаблон подзапроса должен заканчиваться выражением `SELECT`{% if feature_mapreduce %}/`PROCESS`/`REDUCE`{% endif %}, чей результат и является возвращаемым значением подзапроса. При этом выражение верхнего уровня `SELECT`{% if feature_mapreduce %}/`PROCESS`/`REDUCE`{% endif %} нельзя использовать более одного раза, как и модифицирующие выражения (например, `INSERT`). После `DEFINE SUBQUERY` указывается: -1. [Именованное выражение](../expressions.md#named-nodes), по которому объявляемый шаблон будет доступен далее в запросе; +1. [Именованное выражение](expressions.md#named-nodes), по которому объявляемый шаблон будет доступен далее в запросе; 2. В круглых скобках список именованных выражений, по которым внутри шаблона подзапроса можно обращаться к параметрам; 3. Ключевое слово `AS`; 4. Сам список выражений верхнего уровня; @@ -19,7 +20,7 @@ {% note info %} -В больших запросах объявление шаблонов подзапросов можно выносить в отдельные файлы и подключать их в основной запрос с помощью [EXPORT](../export_import.md#export) + [IMPORT](../export_import.md#import), чтобы вместо одного длинного текста получилось несколько логических частей, в которых проще ориентироваться. Важный нюанс: директива `USE my_cluster;` в импортирующем запросе не влияет на поведение объявленных в других файлах подзапросов. +В больших запросах объявление шаблонов подзапросов можно выносить в отдельные файлы и подключать их в основной запрос с помощью [EXPORT](export_import.md#export) + [IMPORT](export_import.md#import), чтобы вместо одного длинного текста получилось несколько логических частей, в которых проще ориентироваться. Важный нюанс: директива `USE my_cluster;` в импортирующем запросе не влияет на поведение объявленных в других файлах подзапросов. {% endnote %} @@ -28,7 +29,7 @@ Даже если список параметров в определении шаблона подзапроса пустой при использовании его во `FROM` секции нужно указать скобки `()`. Такое может быть удобно использовать, чтобы ограничить область видимости именованных выражений, используемых только в одном подзапросе. {% if feature_mapreduce %} -В некоторых случаях вместо операции `DEFINE SUBQUERY` удобнее использовать эквивалентную форму в виде [лямбда функции](../expressions.md#lambda). +В некоторых случаях вместо операции `DEFINE SUBQUERY` удобнее использовать эквивалентную форму в виде [лямбда функции](expressions.md#lambda). В этом случае лямбда функция должна принимать первым аргументом специальный объект `world`, через который передаются зависимости о том, какие видны PRAGMA или COMMIT в точке использования шаблона запроса. Также этот объект нужно передавать первым аргументом вместе с остальными аргументами при их наличии другим шаблонам запросов, если они используются в лямбда функции. Возвращаемым значением лямбда функции должно быть значение с типом список структур (выходная таблица) или список вариантов над кортежом из структур (несколько выходных таблиц). В последнем случае в точке использования шаблона запроса обычно используется распаковка вида @@ -82,7 +83,7 @@ SELECT * FROM $clean(); -- a: 10, b: 100 {% if feature_mapreduce %} ```yql -USE hahn; +USE my_cluster; DEFINE SUBQUERY $input() as SELECT * FROM `home/yql/tutorial/users`; @@ -104,7 +105,7 @@ SELECT * FROM $myProcess2($input, ($x) -> { RETURN AsList($x, $x) }); ``` ```yql -USE hahn; +USE my_cluster; DEFINE SUBQUERY $runPartition($table) AS $paritionByAge = ($row) -> { @@ -134,7 +135,7 @@ SELECT * FROM $j; Эти функции объединяют результаты одного и более шаблонов подзапросов, переданных аргументами. Требуется совпадение количества параметров в этих шаблонах подзапросов. * `SubqueryExtend` требует совпадение схем подзапросов; -* `SubqueryUnionAll` работает по тем же правилам, что и [ListUnionAll](../../builtins/list.md#ListUnionAll); +* `SubqueryUnionAll` работает по тем же правилам, что и [ListUnionAll](../builtins/list.md#ListUnionAll); * `SubqueryMerge` использует те же ограничения, что и `SubqueryExtend`, а также выдает сортированный результат в случае если все подзапросы одинаково отсортированны; * `SubqueryUnionMerge` использует те же ограничения, что и `SubqueryUnionAll`, а также выдает сортированный результат в случае если все подзапросы одинаково отсортированны. @@ -163,7 +164,7 @@ PROCESS $s(); И выполняют подстановку в шаблон подзапроса в качестве параметра каждый элемент из списка, после чего объединяют полученные подзапросы. * `SubqueryExtendFor` требует совпадение схем подзапросов; -* `SubqueryUnionAllFor` работает по тем же правилам, что и [ListUnionAll](../../builtins/list.md#ListUnionAll); +* `SubqueryUnionAllFor` работает по тем же правилам, что и [ListUnionAll](../builtins/list.md#ListUnionAll); * `SubqueryMergeFor` использует те же ограничения, что и `SubqueryExtendFor`, а также выдает сортированный результат в случае если все подзапросы одинаково отсортированны; * `SubqueryUnionMergeFor` использует те же ограничения, что и `SubqueryUnionAllFor`, а также выдает сортированный результат в случае если все подзапросы одинаково отсортированны. @@ -198,3 +199,5 @@ $sub2 = SubqueryOrderBy($sub, [('x',false), ('y',true)]); PROCESS $sub2(); ``` + + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/toc_i.yaml b/ydb/docs/ru/core/yql/reference/syntax/toc_i.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/toc_i.yaml rename to ydb/docs/ru/core/yql/reference/syntax/toc_i.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/update.md b/ydb/docs/ru/core/yql/reference/syntax/update.md similarity index 76% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/update.md rename to ydb/docs/ru/core/yql/reference/syntax/update.md index c8e8e9cc0a9d..21d781396d88 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/update.md +++ b/ydb/docs/ru/core/yql/reference/syntax/update.md @@ -1,12 +1,13 @@ + # UPDATE {% if oss == true and backend_name == "YDB" %} {% note warning %} -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} +{% include [OLAP_not_allow_text](../../../_includes/not_allow_for_olap_text.md) %} -{% include [ways_add_data_to_olap.md](../../../../_includes/ways_add_data_to_olap.md) %} +{% include [ways_add_data_to_olap.md](../../../_includes/ways_add_data_to_olap.md) %} {% endnote %} @@ -14,7 +15,7 @@ `UPDATE` не может менять значение колонок, входящих в состав первичного ключа. -Изменяет данные в строковой таблице.{% if feature_mapreduce %} Таблица по имени ищется в базе данных, заданной оператором [USE](../use.md).{% endif %} После ключевого слова `SET` указываются столбцы, значение которых необходимо заменить, и сами новые значения. Список строк задается с помощью условия `WHERE`. Если `WHERE` отсутствует, изменения будут применены ко всем строкам таблицы. +Изменяет данные в строковой таблице.{% if feature_mapreduce %} Таблица по имени ищется в базе данных, заданной оператором [USE](use.md).{% endif %} После ключевого слова `SET` указываются столбцы, значение которых необходимо заменить, и сами новые значения. Список строк задается с помощью условия `WHERE`. Если `WHERE` отсутствует, изменения будут применены ко всем строкам таблицы. `UPDATE` не может менять значение `PRIMARY_KEY`. @@ -43,3 +44,5 @@ $to_update = ( UPDATE my_table ON SELECT * FROM $to_update; ``` + + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/upsert-object-type-secret.md b/ydb/docs/ru/core/yql/reference/syntax/upsert-object-type-secret.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/upsert-object-type-secret.md rename to ydb/docs/ru/core/yql/reference/syntax/upsert-object-type-secret.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/upsert_into.md b/ydb/docs/ru/core/yql/reference/syntax/upsert_into.md similarity index 75% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/upsert_into.md rename to ydb/docs/ru/core/yql/reference/syntax/upsert_into.md index 31919a203f3e..7695ee3e0a70 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/upsert_into.md +++ b/ydb/docs/ru/core/yql/reference/syntax/upsert_into.md @@ -1,12 +1,13 @@ + # UPSERT INTO {% if oss == true and backend_name == "YDB" %} {% note warning %} -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} +{% include [OLAP_not_allow_text](../../../_includes/not_allow_for_olap_text.md) %} -{% include [ways_add_data_to_olap](../../../../_includes/ways_add_data_to_olap.md) %} +{% include [ways_add_data_to_olap](../../../_includes/ways_add_data_to_olap.md) %} {% endnote %} @@ -16,13 +17,13 @@ UPSERT (расшифровывается как UPDATE or INSERT) обновля {% if feature_mapreduce %} -Таблица по имени ищется в базе данных, заданной оператором [USE](../use.md). +Таблица по имени ищется в базе данных, заданной оператором [USE](use.md). {% endif %} {% if feature_replace %} -`UPSERT` и [`REPLACE`](../replace_into.md) являются операциями модификации данных, которые не требует их предварительного чтения, за счет чего работают быстрее и дешевле других операций. +`UPSERT` и [`REPLACE`](replace_into.md) являются операциями модификации данных, которые не требует их предварительного чтения, за счет чего работают быстрее и дешевле других операций. {% else %} @@ -44,3 +45,4 @@ UPSERT INTO my_table ( pk_column1, pk_column2, data_column2, data_column5 ) VALUES ( 1, 10, 'Some text', Date('2021-10-07')), ( 2, 10, 'Some text', Date('2021-10-08')) ``` + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/use.md b/ydb/docs/ru/core/yql/reference/syntax/use.md similarity index 64% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/use.md rename to ydb/docs/ru/core/yql/reference/syntax/use.md index 28b5d375d7e2..b4dd3f41bb03 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/use.md +++ b/ydb/docs/ru/core/yql/reference/syntax/use.md @@ -2,13 +2,13 @@ Указать «базу данных». Как правило, в её роли выступает один из кластеров {{ backend_name }}. Это указание будет использоваться по умолчанию для поиска таблиц в тех случаях, где база данных не указана явно. -Если в запросе не используется `USE`, то кластер следует указывать в начале пути к таблице в формате ``` cluster.`path/to/table` ```, например ``` hahn.`home/yql/test` ```. Backticks используются для автоматического экранирования спецсимволов, в данном случае слешей. +Если в запросе не используется `USE`, то кластер следует указывать в начале пути к таблице в формате ``` cluster.`path/to/table` ```, например ``` cluster.`home/yql/test` ```. Backticks используются для автоматического экранирования спецсимволов, в данном случае слешей. -Обычно имя кластера указывается непосредственно, но есть возможность указать его в виде выражения. В частности, это позволит использовать параметры, объявленные через [DECLARE](../declare.md). -В этом случае для `USE` должна использоваться запись ```USE yt:$cluster_name```, где `$cluster_name` - [именованное выражение](../expressions.md#named-nodes) типа `String`. +Обычно имя кластера указывается непосредственно, но есть возможность указать его в виде выражения. В частности, это позволит использовать параметры, объявленные через [DECLARE](declare.md). +В этом случае для `USE` должна использоваться запись ```USE yt:$cluster_name```, где `$cluster_name` - [именованное выражение](expressions.md#named-nodes) типа `String`. Либо можно указывать кластер прямо в начале пути к таблице в формате ``` yt:$cluster_name.`path/to/table` ```. -Сам `USE` при этом можно использовать внутри [действий](../action.md){% if feature_subquery %} или [шаблонов подзапросов](../subquery.md){% endif %}. Значение текущего кластера наследуется на объявления вложенных действий{% if feature_subquery %} или подзапросов{% endif %}. Область влияния `USE` прекращается по окончании действия{% if feature_subquery %} или шаблона подзапроса{% endif %}, в котором оно объявлено. +Сам `USE` при этом можно использовать внутри [действий](action.md){% if feature_subquery %} или [шаблонов подзапросов](subquery.md){% endif %}. Значение текущего кластера наследуется на объявления вложенных действий{% if feature_subquery %} или подзапросов{% endif %}. Область влияния `USE` прекращается по окончании действия{% if feature_subquery %} или шаблона подзапроса{% endif %}, в котором оно объявлено. ## Примеры diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/values.md b/ydb/docs/ru/core/yql/reference/syntax/values.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/values.md rename to ydb/docs/ru/core/yql/reference/syntax/values.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/window.md b/ydb/docs/ru/core/yql/reference/syntax/window.md similarity index 93% rename from ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/window.md rename to ydb/docs/ru/core/yql/reference/syntax/window.md index ef1c08528aac..b3d80305b14e 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/window.md +++ b/ydb/docs/ru/core/yql/reference/syntax/window.md @@ -2,9 +2,9 @@ Механизм оконных функций, появившийся в стандарте SQL:2003 и расширенный в стандарте SQL:2011, позволяет выполнять вычисления над набором строк таблицы, который некоторым образом соотносится с текущей строкой. -В отличие от [агрегатных функций](../../builtins/aggregation.md) при этом не происходит группировка нескольких строк в одну – после применения оконных функций число строк в результирующей таблице всегда совпадает с числом строк в исходной. +В отличие от [агрегатных функций](../builtins/aggregation.md) при этом не происходит группировка нескольких строк в одну – после применения оконных функций число строк в результирующей таблице всегда совпадает с числом строк в исходной. -При наличии в запросе агрегатных и оконных функций сначала производится группировка и вычисляются значения агрегатных функций. Вычисленные значения агрегатных функций могут использоваться в качестве аргументов оконных (но не наоборот). Порядок, в котором вычисляются оконные функции относительно других элементов запроса, описан в разеделе [SELECT](../select/index.md). +При наличии в запросе агрегатных и оконных функций сначала производится группировка и вычисляются значения агрегатных функций. Вычисленные значения агрегатных функций могут использоваться в качестве аргументов оконных (но не наоборот). Порядок, в котором вычисляются оконные функции относительно других элементов запроса, описан в разеделе [SELECT](select/index.md). ## Синтаксис {#syntax} @@ -69,7 +69,7 @@ WINDOW Указание `PARTITION BY` группирует строки исходной таблицы в *разделы*, которые затем обрабатываются независимо друг от друга. Если `PARTITION BY` не указан, то все строки исходной таблицы попадают в один раздел. Указание `ORDER BY` определяет порядок строк в разделе. -В `PARTITION BY`, как и в [GROUP BY](../group_by.md) можно использовать алиасы и [SessionWindow](../group_by.md#session-window). +В `PARTITION BY`, как и в [GROUP BY](group_by.md) можно использовать алиасы и [SessionWindow](group_by.md#session-window). При отсутствии `ORDER BY` порядок строк в разделе не определен. @@ -88,7 +88,7 @@ WINDOW Далее, в зависимости от конкретной оконной функции производится ее вычисление либо на множестве строк раздела, либо на множестве строк рамки окна. -[Список доступных оконных функций](../../builtins/window.md) +[Список доступных оконных функций](../builtins/window.md) ### Примеры @@ -141,7 +141,7 @@ WINDOW w AS ( * Функции, вычисляемые на рамке окна `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING` либо `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`, реализованы эффективно (не требуют дополнительной памяти и вычисляются на разделе за O(размер раздела)). -* Для рамки окна `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING` есть возможность выбрать стратегию выполнения в оперативной памяти, указав [хинт](../lexer.md#sql-hints) `COMPACT` после ключевого слова `PARTITION`. +* Для рамки окна `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING` есть возможность выбрать стратегию выполнения в оперативной памяти, указав [хинт](lexer.md#sql-hints) `COMPACT` после ключевого слова `PARTITION`. Например: `PARTITION /*+ COMPACT() */ BY key` или `PARTITION /*+ COMPACT() */ BY ()` (в случае если `PARTITION BY` изначально отсутствовал). diff --git a/ydb/docs/ru/core/yql/reference/toc_i.yaml b/ydb/docs/ru/core/yql/reference/toc_i.yaml index 5ecab61267fa..8ed779c15e6f 100644 --- a/ydb/docs/ru/core/yql/reference/toc_i.yaml +++ b/ydb/docs/ru/core/yql/reference/toc_i.yaml @@ -1,2 +1,9 @@ +title: YQL over {{ backend_name }} +# href: index.md items: -- include: { mode: merge, path: yql-core/toc_m.yaml } +- name: Типы данных + include: { mode: link, path: types/toc_i.yaml } +- name: Синтаксис + include: { mode: link, path: syntax/toc_i.yaml } +- name: Встроенные функции + include: { mode: link, path: builtins/toc_i.yaml } diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/cast.md b/ydb/docs/ru/core/yql/reference/types/cast.md similarity index 98% rename from ydb/docs/ru/core/yql/reference/yql-core/types/_includes/cast.md rename to ydb/docs/ru/core/yql/reference/types/cast.md index 2a678ce49d24..a3a9ab616fd7 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/cast.md +++ b/ydb/docs/ru/core/yql/reference/types/cast.md @@ -1,4 +1,4 @@ -# Правила преобразования типов через оператор [CAST](../../syntax/expressions.md#cast) +# Правила преобразования типов через оператор [CAST](../syntax/expressions.md#cast) ## Правила преобразования примитивных типов данных @@ -11,7 +11,7 @@ * Если для определённого сочетания исходного и целевого типа преобразование не может быть выполнено для всех возможных значений исходного типа, то при неудачном преобразовании `CAST` вернёт `NULL`. В таких случаях к типу возвращаемого значения добавляется один уровень `Optional`, если его не было. Например, конструкции: `CAST("3.14" AS Float?)` и `CAST("3.14" AS Float)` полностью эквиваленты и возвращают `Float?`. * Если же преобразование возможно для всех значений исходного типа, то добавление '?' работает как `Just` сверху: `CAST(3.14 AS Utf8?)` то же, что и `Just(CAST(3.14 AS Utf8))` -Все сочетания примитивных типов, для которых возможен `CAST` описаны [тут](../primitive.md). +Все сочетания примитивных типов, для которых возможен `CAST` описаны [тут](primitive.md). ## Правила преобразований для контейнеров diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/containers.md b/ydb/docs/ru/core/yql/reference/types/containers.md similarity index 84% rename from ydb/docs/ru/core/yql/reference/yql-core/types/_includes/containers.md rename to ydb/docs/ru/core/yql/reference/types/containers.md index b2ba1e3ec666..7be09ec63cea 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/containers.md +++ b/ydb/docs/ru/core/yql/reference/types/containers.md @@ -2,7 +2,9 @@ YQL поддерживает контейнерные типы для определения сложных структур данных различной организации. Значения контейнерных типов могут быть переданы в запросы YQL в качестве входных параметров, либо возвращены из запросов YQL в качестве выходных колонок набора результатов. +{% if backend_name == "YDB" %} Контейнерные типы не могут быть использованы в качестве типов данных колонок таблиц. +{% endif %} | Тип | Объявление,
пример | Описание | | ------------ | ---------------- | ------------- | @@ -18,10 +20,10 @@ YQL поддерживает контейнерные типы для опред При необходимости контейнеры можно вкладывать друг в друга в произвольных комбинациях, например `List>`. -[Опциональные значения](../optional.md) в некоторых контекстах также могут рассматриваться как один из видов контейнеров (`Optional`), который ведёт себя как список длины 0 или 1. +[Опциональные значения](optional.md) в некоторых контекстах также могут рассматриваться как один из видов контейнеров (`Optional`), который ведёт себя как список длины 0 или 1. -Для создания литералов контейнеров списка, словаря, множества, кортежа, структуры можно использовать [операторную запись](../../builtins/basic.md#containerliteral). -Для создания литерала варианта над кортежем или структурой используется функция [Variant](../../builtins/basic.md#variant). -Для создания литерала перечисления используется функция [Enum](../../builtins/basic.md#enum). +Для создания литералов контейнеров списка, словаря, множества, кортежа, структуры можно использовать [операторную запись](../builtins/basic.md#containerliteral). +Для создания литерала варианта над кортежем или структурой используется функция [Variant](../builtins/basic.md#variant). +Для создания литерала перечисления используется функция [Enum](../builtins/basic.md#enum). -Для обращения к элементам контейнера используется [точка или квадратные скобки](../../syntax/expressions.md#items-access), в зависимости от его типа. +Для обращения к элементам контейнера используется [точка или квадратные скобки](../syntax/expressions.md#items-access), в зависимости от его типа. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/index.md b/ydb/docs/ru/core/yql/reference/types/index.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/types/index.md rename to ydb/docs/ru/core/yql/reference/types/index.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/json.md b/ydb/docs/ru/core/yql/reference/types/json.md similarity index 99% rename from ydb/docs/ru/core/yql/reference/yql-core/types/_includes/json.md rename to ydb/docs/ru/core/yql/reference/types/json.md index 4013069ca8a6..d13c56004c15 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/json.md +++ b/ydb/docs/ru/core/yql/reference/types/json.md @@ -1,3 +1,4 @@ + # Передача параметров и данных в формате JSON YQL позволяет задавать параметры используя DECLARE выражение. Сами параметры передаются с помощью restricted JSON формата. @@ -192,4 +193,4 @@ YQL позволяет задавать параметры используя DE Сингулярный тип данных с единственным возможным значением `null`. * Тип в JSON - `string`. -* Значение JSON - `"Void"`. \ No newline at end of file +* Значение JSON - `"Void"`. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/optional.md b/ydb/docs/ru/core/yql/reference/types/optional.md similarity index 63% rename from ydb/docs/ru/core/yql/reference/yql-core/types/_includes/optional.md rename to ydb/docs/ru/core/yql/reference/types/optional.md index 3f4a471a6b17..1415d2e52cfd 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/optional.md +++ b/ydb/docs/ru/core/yql/reference/types/optional.md @@ -1,17 +1,18 @@ + ## Типы данных, допускающие значение NULL Любые типизированные данные в YQL, включая столбцы таблиц, бывают как гарантированно имеющие значение, так и потенциально пустые (что обозначается как `NULL`). Типы данных, которые могут содержать значения `NULL`, называются *опциональными* или, в терминах SQL, — *nullable*. -Опциональные типы данных в [текстовом виде](../type_string.md) обозначаются вопросительным знаком в конце (например, `String?`) или как `Optional<...>`. +Опциональные типы данных в [текстовом виде](type_string.md) обозначаются вопросительным знаком в конце (например, `String?`) или как `Optional<...>`. Наиболее часто на опциональных типах данных выполняются следующие операции: -* [IS NULL](../../syntax/expressions.md#is-null) - проверка на пустое значение -* [COALESCE](../../builtins/basic.md#coalesce) - оставить заполненные значения без изменений, а `NULL` заменить на указанное следом значение по умолчанию -* [UNWRAP](../../builtins/basic.md#optional-ops) - извлечь значение оригинального типа из опционального, `T?` преобразуется в `T` -* [JUST](../../builtins/basic#optional-ops) — добавить опциональность к текущему типу, `T` преобразуется в `T?` -* [NOTHING](../../builtins/basic.md#optional-ops) — создать пустое значение с указанным типом. +* [IS NULL](../syntax/expressions.md#is-null) - проверка на пустое значение +* [COALESCE](../builtins/basic.md#coalesce) - оставить заполненные значения без изменений, а `NULL` заменить на указанное следом значение по умолчанию +* [UNWRAP](../builtins/basic.md#optional-ops) - извлечь значение оригинального типа из опционального, `T?` преобразуется в `T` +* [JUST](../builtins/basic#optional-ops) — добавить опциональность к текущему типу, `T` преобразуется в `T?` +* [NOTHING](../builtins/basic.md#optional-ops) — создать пустое значение с указанным типом. -`Optional` (nullable) является не свойством типа данных или колонки, а одним из видов [контейнеров](../containers.md), которые могут быть произвольным образом вложены друг в друга. Так, например, столбец с типом `Optional>` может принимать 4 значения - `NULL` всего контейнера, `NULL` внутреннего контейнера, `TRUE` и `FALSE`. Описанный тип отличается от `List>` тем, что роль пустого списка в нем играет `NULL` и отсутствует возможность положить больше одного содержательного элемента. Также значения типа `Optional>` возвращаются в качестве результата поиска по ключу в словаре `Dict(k,v)` со значениями типа `Optional`. Такой тип данных результата позволяет отличать лежащий в словаре `NULL` от ситуации отсутствия ключа. +`Optional` (nullable) является не свойством типа данных или колонки, а одним из видов [контейнеров](containers.md), которые могут быть произвольным образом вложены друг в друга. Так, например, столбец с типом `Optional>` может принимать 4 значения - `NULL` всего контейнера, `NULL` внутреннего контейнера, `TRUE` и `FALSE`. Описанный тип отличается от `List>` тем, что роль пустого списка в нем играет `NULL` и отсутствует возможность положить больше одного содержательного элемента. Также значения типа `Optional>` возвращаются в качестве результата поиска по ключу в словаре `Dict(k,v)` со значениями типа `Optional`. Такой тип данных результата позволяет отличать лежащий в словаре `NULL` от ситуации отсутствия ключа. {% if backend_name == "YDB" and oss == true %} @@ -66,11 +67,11 @@ SELECT ## Типы данных, не допускающие значение NULL {#notnull} -[Примитивные типы](../primitive.md) YQL не могут хранить в себе значение `NULL`: для хранения `NULL` предназначен описанный выше контейнер `Optional`. В терминах SQL примитивные типы YQL являются *non-nullable* типами. +[Примитивные типы](primitive.md) YQL не могут хранить в себе значение `NULL`: для хранения `NULL` предназначен описанный выше контейнер `Optional`. В терминах SQL примитивные типы YQL являются *non-nullable* типами. В YQL отсутствует неявное преобразование типов из `Optional` в `T`, поэтому выполнимость `NOT NULL` ограничения на колонку таблицы обеспечивается на этапе компиляции запроса {{ ydb-short-name }}. -Создать non-nullable колонку в таблице {{ ydb-short-name }} можно с помощью операции [CREATE TABLE](../../../reference/syntax/create_table/index.md), пользуясь ключевым словом `NOT NULL`. +Создать non-nullable колонку в таблице {{ ydb-short-name }} можно с помощью операции [CREATE TABLE](../syntax/create_table/index.md), пользуясь ключевым словом `NOT NULL`. ### Пример @@ -97,6 +98,7 @@ INSERT INTO t(c) SELECT CAST('q' AS Utf8); ``` -не может быть исполнен. Причиной этому является несоответствие типов колонки `c`, имеющей тип `Utf8`, и результата функции `CAST`, имеющей тип `Optional`. Для корректной работы запроса в таких сценариях требуется использовать функцию [COALESCE](../../builtins/basic.md#coalesce), аргументом которой можно указать fallback-значение для вставки в таблицу для случая, когда функция (в примере `CAST`) вернет пустой `Optional`. Если же в случае пустого `Optional` нужно не выполнять вставку, а вернуть ошибку, то для этого подойдет функция [UNWRAP](../../builtins/basic.md#optional-ops), позволяющая распаковать содержимое опционального типа. +не может быть исполнен. Причиной этому является несоответствие типов колонки `c`, имеющей тип `Utf8`, и результата функции `CAST`, имеющей тип `Optional`. Для корректной работы запроса в таких сценариях требуется использовать функцию [COALESCE](../builtins/basic.md#coalesce), аргументом которой можно указать fallback-значение для вставки в таблицу для случая, когда функция (в примере `CAST`) вернет пустой `Optional`. Если же в случае пустого `Optional` нужно не выполнять вставку, а вернуть ошибку, то для этого подойдет функция [UNWRAP](../builtins/basic.md#optional-ops), позволяющая распаковать содержимое опционального типа. {% endif %} + diff --git a/ydb/docs/ru/core/yql/reference/types/primitive.md b/ydb/docs/ru/core/yql/reference/types/primitive.md new file mode 100644 index 000000000000..581365d89e94 --- /dev/null +++ b/ydb/docs/ru/core/yql/reference/types/primitive.md @@ -0,0 +1,217 @@ +# Примитивные типы данных + + + +Термины «простые», «примитивные» и «элементарные» типы данных используются как синонимы. + +## Числовые типы {#numeric} + +Тип | Описание | Примечания +----- | ----- | ----- +`Bool` | Логическое значение. | +`Int8` | Целое число со знаком.
Допустимые значения: от –27 до 27–1. | +`Int16` | Целое число со знаком.
Допустимые значения: от –215 до 215–1. | +`Int32` | Целое число со знаком.
Допустимые значения: от –231 до 231–1. | +`Int64` | Целое число со знаком.
Допустимые значения: от –263 до 263–1. | +`Uint8` | Беззнаковое целое число.
Допустимые значения: от 0 до 28–1. | +`Uint16` | Беззнаковое целое число.
Допустимые значения: от 0 до 216–1. | +`Uint32` | Беззнаковое целое число.
Допустимые значения: от 0 до 232–1. | +`Uint64` | Беззнаковое целое число.
Допустимые значения: от 0 до 264–1. | +`Float` | Вещественное число с переменной точностью размером 4 байта. | {% if feature_map_tables %}Не может быть использован в первичном ключе{% endif %} +`Double` | Вещественное число с переменной точностью размером 8 байт. | {% if feature_map_tables %}Не может быть использован в первичном ключе{% endif %} +`Decimal` | Вещественное число с указанной точностью, до 35 десятичных знаков | {% if feature_map_tables %}При использовании в колонках таблиц точность фиксирована: Decimal (22,9).{% endif %} +{% if feature_map_tables %} +`DyNumber` | Бинарное представление вещественного числа точностью до 38 знаков.
Допустимые значения: положительные от 1×10-130 до 1×10126–1, отрицательные от -1×10126–1 до -1×10-130 и 0.
Совместим с типом `Number` AWS DynamoDB. Не рекомендуется для использования в {{ backend_name_lower }}-native приложениях. | +{% endif %} + + +## Строковые типы {#string} + +Тип | Описание | Примечания +----- | ----- | ----- +`String` | Строка, может содержать произвольные бинарные данные | +`Utf8` | Текст в кодировке [UTF-8](https://en.wikipedia.org/wiki/UTF-8) | +`Json` | [JSON](https://en.wikipedia.org/wiki/JSON) в текстовом представлении|Не поддерживает возможность сравнения{% if feature_map_tables %}, не может быть использован в первичном ключе{% endif %} +`JsonDocument` | [JSON](https://en.wikipedia.org/wiki/JSON) в бинарном индексированном представлении | Не поддерживает возможность сравнения{% if feature_map_tables %}, не может быть использован в первичном ключе{% endif %} +`Yson` | [YSON](yson.md) в текстовом или бинарном представлении | Не поддерживает возможность сравнения{% if feature_map_tables %}, не может быть использован в первичном ключе{% endif %} +`Uuid` | Универсальный идентификатор [UUID](https://tools.ietf.org/html/rfc4122) | + +{% note info "Ограничения на размер" %} + +Максимальный размер значения в ячейке {% if feature_map_tables %} неключевого столбца {% endif %} с любым строковым типом данных — 8 МБ. + +{% endnote %} + +В отличие от типа данных `Json`, который хранит исходное текстовое представление, переданное пользователем, `JsonDocument` использует бинарное индексированное представление. Важное отличие с точки зрения семантики состоит в том, что `JsonDocument` не сохраняет форматирование, порядок ключей в объектах и их дубликаты. + +За счет индексированного представления `JsonDocument` позволяет обходить документную модель с использованием `JsonPath` без необходимости парсинга всего содержимого. Это позволяет эффективно выполнять операции из [JSON API](../builtins/json.md), уменьшая задержки и стоимость пользовательских запросов. Выполнение запросов над `JsonDocument` может быть до нескольких раз эффективнее в зависимости от типа нагрузки. + +Из-за добавленной избыточности `JsonDocument` менее эффективен в хранении. Дополнительные накладные расходы на хранение зависят от конкретного содержимого и в среднем составляют 20–30% от исходного объема. Сохранение данных в формате `JsonDocument` требует дополнительной конвертации из текстового представления, что делает его запись менее эффективной. Тем не менее, для большинства read-intensive сценариев, подразумевающих обработку данных из JSON, этот тип данных является предпочтительным и рекомендуется к использованию. + +{% note warning %} + +Для хранения чисел (JSON Number) в `JsonDocument`, а также для арифметических операций над ними в [JSON API](../builtins/json.md) используется тип [Double](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). Возможна потеря точности при использовании нестандартных представлений чисел в исходном JSON-документе. + +{% endnote %} + +## Дата и время {#datetime} + +Тип | Описание | Примечания +----- | ----- | ----- +`Date` | Дата, точность до дней | Диапазон значений для всех временных типов кроме `Interval` - от нуля часов 01.01.1970 до нуля часов 01.01.2106. Внутреннее представление `Date` – беззнаковое целое 16 бит | +`Datetime` | Дата/время, точность до секунд | Внутреннее представление – беззнаковое целое 32 бит | +`Timestamp` | Дата/время, точность до микросекунд | Внутреннее представление – беззнаковое целое 64 бит | +`Interval` | Интервал времени (знаковый), точность до микросекунд | Диапазон значений – от -136 лет до +136 лет. Внутреннее представление – знаковое целое 64 бит. {% if feature_map_tables %}Не может быть использован в первичном ключе{% endif %} +`TzDate` | Дата с меткой временной зоны, точность до дней | Не поддерживается в столбцах таблиц +`TzDateTime` | Дата/время с меткой временной зоны, точность до секунд | Не поддерживается в столбцах таблиц +`TzTimestamp` | Дата/время с меткой временной зоны, точность до микросекунд | Не поддерживается в столбцах таблиц + +### Особенности поддержки типов с меткой временной зоны + +Метка временной зоны у типов `TzDate`, `TzDatetime`, `TzTimestamp` это атрибут, который используется: + +* При преобразовании ([CAST](../syntax/expressions.md#cast), [DateTime::Parse](../udf/list/datetime.md#parse), [DateTime::Format](../udf/list/datetime.md#format)) в строку и из строки. +* В [DateTime::Split](../udf/list/datetime.md#split) - появляется компонент таймзоны в `Resource`. + +Само значение позиции во времени у этих типов хранится в UTC, и метка таймзоны никак не участвует в прочих расчётах. Например: + +```yql +SELECT --эти выражения всегда true для любых таймзон: таймзона не влияет на точку во времени. + AddTimezone(CurrentUtcDate(), "Europe/Moscow") == + AddTimezone(CurrentUtcDate(), "America/New_York"), + AddTimezone(CurrentUtcDatetime(), "Europe/Moscow") == + AddTimezone(CurrentUtcDatetime(), "America/New_York"); +``` + +Важно понимать, что при преобразованиях между `TzDate` и `TzDatetime` или `TzTimestamp` дате соответствует не полночь по локальному времени таймзоны, а полночь по UTC для даты в UTC. + + +## Приведение простых типов данных {#cast} + +### Явное приведение {#explicit-cast} + +Явное приведение при помощи [CAST](../syntax/expressions.md#cast): + +#### Приведение к численным типам + +Тип | Bool | Int8 | Int16 | Int32 | Int64 | Uint8 | Uint16 | Uint32 | Uint64 | Float | Double | Decimal +--- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- +**Bool** | — | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Нет +**Int8** | Да2 | — | Да | Да | Да | Да3 | Да3 | Да3 | Да3 | Да | Да | Да +**Int16** | Да2 | Да4 | — | Да | Да | Да3,4 | Да3 | Да3 | Да3 | Да | Да | Да +**Int32** | Да2 | Да4 | Да4 | — | Да | Да3,4 | Да3,4 | Да3 | Да3 | Да | Да | Да +**Int64** | Да2 | Да4 | Да4 | Да4 | — | Да3,4 | Да3,4 | Да3,4 | Да3 | Да | Да | Да +**Uint8** | Да2 | Да4 | Да | Да | Да | — | Да | Да | Да | Да | Да | Да +**Uint16** | Да2 | Да4 | Да4 | Да | Да | Да4 | — | Да | Да | Да | Да | Да +**Uint32** | Да2 | Да4 | Да4 | Да4 | Да | Да4 | Да4 | — | Да | Да | Да | Да +**Uint64** | Да2 | Да4 | Да4 | Да4 | Да4 | Да4 | Да4 | Да4 | — | Да | Да | Да +**Float** | Да2 | Да4 | Да4 | Да4 | Да4 | Да3,4 | Да3,4 | Да3,4 | Да3,4 | — | Да | Нет +**Double** | Да2 | Да4 | Да4 | Да4 | Да4 | Да3,4 | Да3,4 | Да3,4 | Да3,4 | Да | — | Нет +**Decimal** | Нет | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | — +**String** | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да +**Utf8** | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да +**Json** | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет +**Yson** | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Нет +**Uuid** | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет +**Date** | Нет | Да4 | Да4 | Да | Да | Да4 | Да | Да | Да | Да | Да | Да | Нет +**Datetime** | Нет | Да4 | Да4 | Да4 | Да | Да4 | Да4 | Да | Да | Да | Да | Нет +**Timestamp** | Нет | Да4 | Да4 | Да4 | Да4 | Да4 | Да4 | Да4 | Да | Да | Да | Нет +**Interval** | Нет | Да4 | Да4 | Да4 | Да | Да3,4 | Да3,4 | Да3,4 | Да3 | Да | Да | Нет + +1 `True` преобразуется в `1`, `False` преобразуется в `0`. +2 Любое значение кроме `0` преобразуется в `True`, `0` преобразуется в `False`. +3 Возможно только в случае неотрицательного значения. +4 Возможно только в случае попадания в диапазон допустимых значений. +5 При помощи встроенной функции [Yson::ConvertTo](../udf/list/yson.md#ysonconvertto). + +#### Приведение к типам данных даты и времени + +Тип | Date | Datetime | Timestamp | Interval +--- | --- | --- | --- | --- +**Bool** | Нет | Нет | Нет | Нет +**Int8** | Да | Да | Да | Да +**Int16** | Да | Да | Да | Да +**Int32** | Да | Да | Да | Да +**Int64** | Да | Да | Да | Да +**Uint8** | Да | Да | Да | Да +**Uint16** | Да | Да | Да | Да +**Uint32** | Да | Да | Да | Да +**Uint64** | Да | Да | Да | Да +**Float** | Нет | Нет | Нет | Нет +**Double** | Нет | Нет | Нет | Нет +**Decimal** | Нет | Нет | Нет | Нет +**String** | Да | Да | Да | Да +**Utf8** | Да | Да | Да | Да +**Json** | Нет | Нет | Нет | Нет +**Yson** | Нет | Нет | Нет | Нет +**Uuid** | Нет | Нет | Нет | Нет +**Date** | — | Да | Да | Нет +**Datetime** | Да | — | Да | Нет +**Timestamp** | Да | Да | — | Нет +**Interval** | Нет | Нет | Нет | — | — + +#### Приведение к другим типам данных + +Тип | String | Utf8 | Json | Yson | Uuid +--- | --- | --- | --- | --- | --- +**Bool** | Да | Нет | Нет | Нет | Нет | +**Int8** | Да | Нет | Нет | Нет | Нет +**Int16** | Да | Нет | Нет | Нет | Нет +**Int32** | Да | Нет | Нет | Нет | Нет +**Int64** | Да | Нет | Нет | Нет | Нет +**Uint8** | Да | Нет | Нет | Нет | Нет +**Uint16** | Да | Нет | Нет | Нет | Нет +**Uint32** | Да | Нет | Нет | Нет | Нет +**Uint64** | Да | Нет | Нет | Нет | Нет +**Float** | Да | Нет | Нет | Нет | Нет +**Double** | Да | Нет | Нет | Нет | Нет +**Decimal** | Да | Нет | Нет | Нет | Нет +**String** | — | Да | Да | Да | Да +**Utf8** | Да | — | Нет | Нет | Нет +**Json** | Да | Да | — | Нет | Нет +**Yson** | Да1 | Нет | Нет | Нет | Нет +**Uuid** | Да | Да | Нет | Нет | — +**Date** | Да | Да | Нет | Нет | Нет +**Datetime** | Да | Да | Нет | Нет | Нет +**Timestamp** | Да | Да | Нет | Нет | Нет +**Interval** | Да | Да | Нет | Нет | Нет + +1 При помощи встроенной функции [Yson::ConvertTo](../udf/list/yson.md#ysonconvertto). + +##### Примеры + +{% include [x](../_includes/cast_examples.md) %} + +### Неявное приведение {#implicit-cast} + +Неявное приведение типов, которое возникает в базовых операциях (`+`, `-`, `*`, `/`, `%`) между разными типами данных. В ячейках таблицы указан тип результата операции, если она возможна: + +#### Численные типы + +При несовпадении численных типов сначала выполняется BitCast обоих аргументов к типу результата, а потом уже операция. + +Тип | Int8 | Int16 | Int32 | Int64 | Uint8 | Uint16 | Uint32 | Uint64 | Float | Double +--- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- +**Int8** | — | `Int16` | `Int32` | `Int64` | `Int8` | `Uint16` | `Uint32` | `Uint64` | `Float` | `Double` +**Int16** | `Int16` | — | `Int32` | `Int64` | `Int16` | `Int16` | `Uint32` | `Uint64` | `Float` | `Double` +**Int32** | `Int32` | `Int32` | — | `Int64` | `Int32` | `Int32` | `Int32` | `Uint64` | `Float` | `Double` +**Int64** | `Int64` | `Int64` | `Int64` | — | `Int64` | `Int64` | `Int64` | `Int64` | `Float` | `Double` +**Uint8** | `Int8` | `Int16` | `Int32` | `Int64` | — | `Uint16` | `Uint32` | `Uint64` | `Float` | `Double` +**Uint16** | `Uint16` | `Int16` | `Int32` | `Int64` | `Uint16` | — | `Uint32` | `Uint64` | `Float` | `Double` +**Uint32** | `Uint32` | `Uint32` | `Int32` | `Int64` | `Uint32` | `Uint32` | — | `Uint64` | `Float` | `Double` +**Uint64** | `Uint64` | `Uint64` | `Uint64` | `Int64` | `Uint64` | `Uint64` | `Uint64` | — | `Float` | `Double` +**Float** | `Float` | `Float` | `Float` | `Float` | `Float` | `Float` | `Float` | `Float` | — | `Double` +**Double** | `Double` | `Double` | `Double` | `Double` | `Double` | `Double` | `Double` | `Double` | `Double` | — + + +#### Типы даты и времени + +Тип | Date | Datetime | Timestamp | Interval | TzDate | TzDatetime | TzTimestamp +--- | --- | --- | --- | --- | --- | --- | --- +**Date** | — | — | — | `Date` | — | — | — +**Datetime** | — | — | — | `Datetime` | — | — | — +**Timestamp** | — | — | — | `Timestamp` | — | — | — +**Interval** | `Date` | `Datetime` | `Timestamp` | — | `TzDate` | `TzDatetime` | `TzTimestamp` +**TzDate** | — | — | — | `TzDate` | — | — | — +**TzDatetime** | — | — | — | `TzDatetime` | — | — | — +**TzTimestamp** | — | — | — | `TzTimestamp` | — | — | — diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/serial.md b/ydb/docs/ru/core/yql/reference/types/serial.md similarity index 93% rename from ydb/docs/ru/core/yql/reference/yql-core/types/_includes/serial.md rename to ydb/docs/ru/core/yql/reference/types/serial.md index 72eb5a11491c..34a63b730b9d 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/serial.md +++ b/ydb/docs/ru/core/yql/reference/types/serial.md @@ -1,3 +1,4 @@ + # Серийные типы данных Серийные типы данных представляют собой целые числа, но с дополнительным механизмом генерации значений. Эти типы данных используются для создания автоинкрементных колонок, а именно для каждой новой строки, добавляемой в таблицу, будет автоматически генерироваться уникальное значение для такой колонки (подобно типу [SERIAL](https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-SERIAL) в PostgreSQL или свойству [AUTO_INCREMENT](https://dev.mysql.com/doc/refman/9.0/en/example-auto-increment.html) в MySQL). @@ -61,4 +62,5 @@ Error: Failed to get next val for sequence: /dev/test/users/_serial_column_user_ Отметим, что следующее значение выдаётся генератором до непосредственной вставки в таблицу и уже будет считаться использованным, даже если строка, содержащая это значение, не была успешно вставлена, например, при откате транзакции. Поэтому множество значений такой колонки может содержать пропуски и состоять из нескольких промежутков. -Для таблиц с автоинкрементными колонками поддержаны операции [copy](../../../../reference/ydb-cli/tools-copy.md), [dump](../../../../reference/ydb-cli/export-import/tools-dump.md), [restore](../../../../reference/ydb-cli/export-import/import-file.md) и [import](../../../../reference/ydb-cli/export-import/import-s3.md)/[export](../../../../reference/ydb-cli/export-import/export-s3.md). +Для таблиц с автоинкрементными колонками поддержаны операции [copy](../../../reference/ydb-cli/tools-copy.md), [dump](../../../reference/ydb-cli/export-import/tools-dump.md), [restore](../../../reference/ydb-cli/export-import/import-file.md) и [import](../../../reference/ydb-cli/export-import/import-s3.md)/[export](../../../reference/ydb-cli/export-import/export-s3.md). + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/special.md b/ydb/docs/ru/core/yql/reference/types/special.md similarity index 99% rename from ydb/docs/ru/core/yql/reference/yql-core/types/_includes/special.md rename to ydb/docs/ru/core/yql/reference/types/special.md index 33393b3dca97..b3f5cd264fe1 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/special.md +++ b/ydb/docs/ru/core/yql/reference/types/special.md @@ -1,3 +1,4 @@ + # Специальные типы данных Тип | Описание @@ -12,3 +13,4 @@ `EmptyList` | сингулярный тип данных с единственным возможным значением []; является типом литерала `[]` и может преобразовываться к любому `List` типу. `EmptyDict` | сингулярный тип данных с единственным возможным значением {}; является типом литерала `{}` и может преобразовываться к любому `Dict` или `Set` типу. + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/toc_i.yaml b/ydb/docs/ru/core/yql/reference/types/toc_i.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/types/toc_i.yaml rename to ydb/docs/ru/core/yql/reference/types/toc_i.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/type_string.md b/ydb/docs/ru/core/yql/reference/types/type_string.md similarity index 89% rename from ydb/docs/ru/core/yql/reference/yql-core/types/_includes/type_string.md rename to ydb/docs/ru/core/yql/reference/types/type_string.md index 1d6922c334ec..5b0d6342bc19 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/type_string.md +++ b/ydb/docs/ru/core/yql/reference/types/type_string.md @@ -4,12 +4,12 @@ Так как YQL является строго типизированным языком, во многих аспектах работы с ним тип данных имеет большое значение. Для удобства работы с типами существует конвенция описания типов данных YQL в текстовом виде. Она используется в разных местах документации, а также существует библиотека, предоставляющая функции для построения типа данных по текстовому описанию (например, при ручном описании сигнатуры вызываемого значения) или для сериализации типа данных в строку для отладки. -Функции для работы с типами данных [описаны в статье](../../builtins/types.md), а ниже описан сам формат текстового представления типов данных. +Функции для работы с типами данных [описаны в статье](../builtins/types.md), а ниже описан сам формат текстового представления типов данных. ## Общие правила {#rules} -* [Примитивные типы данных](../primitive.md) представляются в текстовом виде просто своим именем. -* Сложный тип данных представляет собой композицию из других типов данных. Если представить эту композицию в виде дерева, то на листьях окажутся [примитивные типы данных](../primitive.md), а в остальных узлах — [контейнеры](../containers.md). [Специальные типы данных](../special.md) можно рассматривать как исключение, они могут находиться и там и там. +* [Примитивные типы данных](primitive.md) представляются в текстовом виде просто своим именем. +* Сложный тип данных представляет собой композицию из других типов данных. Если представить эту композицию в виде дерева, то на листьях окажутся [примитивные типы данных](primitive.md), а в остальных узлах — [контейнеры](containers.md). [Специальные типы данных](special.md) можно рассматривать как исключение, они могут находиться и там и там. * Текстовое представление повторяет структуру этого дерева в порядке от корня к листьям: в каждом узле дерева указывается имя текущего типа данных, а переход на уровень глубже обозначается различными видами скобок. * Допустимо использование пробелов и переносов строк, если это облегчает чтение. * Если идентификатор состоит не только из английских букв и цифр, то его нужно записывать в одиночных кавычках и использовать C-escaping. @@ -67,3 +67,4 @@ * В отличие от контейнеров, ресурс параметризуется не типом элемента (ресурс является указателем в памяти и YQL ничего не знает о его содержимом), а строковой меткой, которая может использоваться для защиты от передачи ресурсов между несовместимыми функциями. Пример: `Resource`. + diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/yson.md b/ydb/docs/ru/core/yql/reference/types/yson.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/types/yson.md rename to ydb/docs/ru/core/yql/reference/types/yson.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/datetime.md b/ydb/docs/ru/core/yql/reference/udf/list/datetime.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/datetime.md rename to ydb/docs/ru/core/yql/reference/udf/list/datetime.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/digest.md b/ydb/docs/ru/core/yql/reference/udf/list/digest.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/digest.md rename to ydb/docs/ru/core/yql/reference/udf/list/digest.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/histogram.md b/ydb/docs/ru/core/yql/reference/udf/list/histogram.md similarity index 73% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/histogram.md rename to ydb/docs/ru/core/yql/reference/udf/list/histogram.md index 366f855c29fd..1be48ecdbf73 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/histogram.md +++ b/ydb/docs/ru/core/yql/reference/udf/list/histogram.md @@ -1,6 +1,6 @@ # Histogram -Набор вспомогательных функций для [агрегатной функции HISTOGRAM](../../../builtins/aggregation.md). В описании сигнатур ниже под HistogramStruct подразумевается результат работы агрегатной функции `HISTOGRAM`, `LinearHistogram` или `LogarithmicHistogram`, который является структурой определенного вида. +Набор вспомогательных функций для [агрегатной функции HISTOGRAM](../../builtins/aggregation.md). В описании сигнатур ниже под HistogramStruct подразумевается результат работы агрегатной функции `HISTOGRAM`, `LinearHistogram` или `LogarithmicHistogram`, который является структурой определенного вида. ## Список функций @@ -15,5 +15,5 @@ * `Histogram::CalcUpperBoundSafe(HistogramStruct{Flags:AutoMap}, Double) -> Double` * `Histogram::CalcLowerBoundSafe(HistogramStruct{Flags:AutoMap}, Double) -> Double` -У `Histogram::Print` есть опциональный числовой аргумент, который задает максимальную длину столбцов гистограммы (в символах, так как гистограмма рисуется в технике ASCII-арт). Значение по умолчанию — 25. Данная функция предназначена в первую очередь для просмотра гистограмм в консоли{% if feature_webui %}. [Веб-интерфейс](../../../interfaces/web.md) автоматически делает их интерактивную визуализацию{% endif %}. +У `Histogram::Print` есть опциональный числовой аргумент, который задает максимальную длину столбцов гистограммы (в символах, так как гистограмма рисуется в технике ASCII-арт). Значение по умолчанию — 25. Данная функция предназначена в первую очередь для просмотра гистограмм в консоли{% if feature_webui %}. [Веб-интерфейс](../../interfaces/web.md) автоматически делает их интерактивную визуализацию{% endif %}. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/hyperscan.md b/ydb/docs/ru/core/yql/reference/udf/list/hyperscan.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/hyperscan.md rename to ydb/docs/ru/core/yql/reference/udf/list/hyperscan.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/index/intro.md b/ydb/docs/ru/core/yql/reference/udf/list/index.md similarity index 60% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/index/intro.md rename to ydb/docs/ru/core/yql/reference/udf/list/index.md index 36fd3117066b..9cc26c205656 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/index/intro.md +++ b/ydb/docs/ru/core/yql/reference/udf/list/index.md @@ -2,3 +2,19 @@ Многие прикладные функции, которые с одной стороны слишком специфичны, чтобы стать частью ядра YQL, а с другой — могут быть полезны широкому кругу пользователей, доступны через встроенные C++ библиотеки. + + +* [DateTime](datetime.md) +* [Digest](digest.md) +* [Histogram](histogram.md) +* [Hyperscan](hyperscan.md) +* [Ip](ip.md) +* [Knn](knn.md) +* [Math](math.md) +* [Pcre](pcre.md) +* [Pire](pire.md) +* [Re2](re2.md) +* [String](string.md) +* [Unicode](unicode.md) +* [Url](url.md) +* [Yson](yson.md) diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/ip.md b/ydb/docs/ru/core/yql/reference/udf/list/ip.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/ip.md rename to ydb/docs/ru/core/yql/reference/udf/list/ip.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/knn.md b/ydb/docs/ru/core/yql/reference/udf/list/knn.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/knn.md rename to ydb/docs/ru/core/yql/reference/udf/list/knn.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/math.md b/ydb/docs/ru/core/yql/reference/udf/list/math.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/math.md rename to ydb/docs/ru/core/yql/reference/udf/list/math.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/pcre.md b/ydb/docs/ru/core/yql/reference/udf/list/pcre.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/pcre.md rename to ydb/docs/ru/core/yql/reference/udf/list/pcre.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/pire.md b/ydb/docs/ru/core/yql/reference/udf/list/pire.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/pire.md rename to ydb/docs/ru/core/yql/reference/udf/list/pire.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/postgres.md b/ydb/docs/ru/core/yql/reference/udf/list/postgres.md similarity index 69% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/postgres.md rename to ydb/docs/ru/core/yql/reference/udf/list/postgres.md index 5081b338d879..1a81354874ab 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/postgres.md +++ b/ydb/docs/ru/core/yql/reference/udf/list/postgres.md @@ -11,9 +11,104 @@ ## Литералы {#literals} -Строковые и числовые литералы Pg типов можно создавать с помощью специальных суффиксов (аналогично простым [строковым](../yql/reference/yql-core/syntax/lexer#string-literals) и [числовым](../yql/reference/yql-core/syntax/lexer#literal-numbers) литералам). +Строковые и числовые литералы Pg типов можно создавать с помощью специальных суффиксов (аналогично простым [строковым](../../syntax/lexer.md#string-literals) и [числовым](../../syntax/lexer.md#literal-numbers) литералам). + +### Целочисленные литералы {#intliterals} + +Суффикс | Тип | Комментарий +----- | ----- | ----- +`p` | `PgInt4` | 32-битное знаковое целое (в PostgreSQL нет беззнаковых типов) +`ps`| `PgInt2` | 16-битное знаковое целое +`pi`| `PgInt4` | +`pb`| `PgInt8` | 64-битное знаковое цело +`pn`| `PgNumeric` | знаковое целое произвольной точности (до 131072 цифр) + +### Литералы с плавающей точкой {#floatliterals} + +Суффикс | Тип | Комментарий +----- | ----- | ----- +`p` | `PgFloat8` | число с плавающей точкой (64 бит double) +`pf4`| `PgFloat4` | число с плавающей точкой (32 бит float) +`pf8`| `PgFloat8` | +`pn` | `PgNumeric` | число с плавающей точкой произвольной точности (до 131072 цифр перед запятой, до 16383 цифр после запятой) + +### Строковые литералы {#stringliterals} + +Суффикс | Тип | Комментарий +----- | ----- | ----- +`p` | `PgText` | текстовая строка +`pt`| `PgText` | +`pv`| `PgVarchar` | текстовая строка +`pb`| `PgBytea` | бинарная строка + +{% note warning "Внимание" %} + +Значения строковых/числовых литералов (т.е. то что идет перед суффиксом) должны быть валидной строкой/числом с точки зрения YQL. +В частности, должны соблюдаться правила эскейпинга YQL, а не PostgreSQL. + +{% endnote %} + +Пример: + +```yql +SELECT + 1234p, -- pgint4 + 0x123pb, -- pgint8 + "тест"pt, -- pgtext + 123e-1000pn; -- pgnumeric +; +``` + +### Литерал массива + +Для построения литерала массива используется функция `PgArray`: + +```yql +SELECT + PgArray(1p, NULL ,2p) -- {1,NULL,2}, тип _int4 +; +``` + +### Конструктор литералов произвольного типа {#literals_constructor} + +Литералы всех типов (в том числе и Pg типов) могут создаваться с помощью конструктора литералов со следующей сигнатурой: +`Имя_типа(<строковая константа>)`. + +Напрмер: + +```yql +DECLARE $foo AS String; +SELECT + PgInt4("1234"), -- то же что и 1234p + PgInt4(1234), -- в качестве аргумента можно использовать литеральные константы + PgInt4($foo), -- и declare параметры + PgBool(true), + PgInt8(1234), + PgDate("1932-01-07"), +; +``` + +Также поддерживается встроенная функция `PgConst` со следующей сигнатурой: `PgConst(<строковое значение>, <тип>)`. +Такой способ более удобен для кодогенерации. + +Например: + +```yql +SELECT + PgConst("1234", PgInt4), -- то же что и 1234p + PgConst("true", PgBool) +; +``` + +Для некоторых типов в функции `PgConst` можно указать дополнительные модификаторы. Возможные модификаторы для типа `pginterval` перечислены в [документации PostgreSQL](https://www.postgresql.org/docs/16/datatype-datetime.html). + +```yql +SELECT + PgConst(90, pginterval, "day"), -- 90 days + PgConst(13.45, pgnumeric, 10, 1); -- 13.5 +; +``` -{% include [pgliterals](./_includes/pgliterals.md) %} ## Операторы {#operators} @@ -104,13 +199,13 @@ SELECT Таблица соответствия типов данных YQL и PostgreSQL при использовании функции `ToPg`: -{% include [topg](_includes/topg.md) %} +{% include [topg](../../_includes/topg.md) %} ### Таблица соответствия типов `FromPg` {#frompg} Таблица соответствия типов данных PostgreSQL и YQL при использовании функции `FromPg`: -{% include [frompg](_includes/frompg.md) %} +{% include [frompg](../../_includes/frompg.md) %} ## Вызов PostgreSQL функций {#callpgfunction} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/re2.md b/ydb/docs/ru/core/yql/reference/udf/list/re2.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/re2.md rename to ydb/docs/ru/core/yql/reference/udf/list/re2.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/string.md b/ydb/docs/ru/core/yql/reference/udf/list/string.md similarity index 92% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/string.md rename to ydb/docs/ru/core/yql/reference/udf/list/string.md index 43461ddf3ba9..4ddcd1dbcc80 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/string.md +++ b/ydb/docs/ru/core/yql/reference/udf/list/string.md @@ -47,14 +47,14 @@ SELECT String::Strip("YQL "); -- "YQL" Проверяет наличие подстроки в строке. -* `String::Find(string:String{Flags:AutoMap}, String, [Uint64?]) -> Int64` - Устаревшая: используйте встроенную функцию [Find](../../../builtins/_includes/basic/find.md#find) -* `String::ReverseFind(string:String{Flags:AutoMap}, String, [Uint64?]) -> Int64` - Устаревшая: используйте встроенную функцию [RFind](../../../builtins/_includes/basic/find.md#rfind) -* `String::Substring(string:String{Flags:AutoMap}, [Uint64?, Uint64?]) -> String` - Устаревшая: используйте встроенную функцию [Substring](../../../builtins/_includes/basic/substring.md#substring) -* `String::HasPrefix(string:String?, prefix:String) -> Bool` - Устаревшая: используйте встроенную функцию [StartsWith](../../../builtins/_includes/basic/starts_ends_with.md) -* `String::StartsWith(string:String?, prefix:String) -> Bool` - Устаревшая: используйте встроенную функцию [StartsWith](../../../builtins/_includes/basic/starts_ends_with.md) -* `String::HasSuffix(string:String?, suffix:String) -> Bool` - Устаревшая: используйте встроенную функцию [EndsWith](../../../builtins/_includes/basic/starts_ends_with.md) -* `String::EndsWith(string:String?, suffix:String) -> Bool` - Устаревшая: используйте встроенную функцию [EndsWith](../../../builtins/_includes/basic/starts_ends_with.md) -* `String::Reverse(string:String?) -> String?` - Устаревшая: используйте [Unicode::Reverse](../unicode.md) +* `String::Find(string:String{Flags:AutoMap}, String, [Uint64?]) -> Int64` - Устаревшая: используйте встроенную функцию [Find](../../builtins/basic.md#find) +* `String::ReverseFind(string:String{Flags:AutoMap}, String, [Uint64?]) -> Int64` - Устаревшая: используйте встроенную функцию [RFind](../../builtins/basic.md#rfind) +* `String::Substring(string:String{Flags:AutoMap}, [Uint64?, Uint64?]) -> String` - Устаревшая: используйте встроенную функцию [Substring](../../builtins/basic.md#substring) +* `String::HasPrefix(string:String?, prefix:String) -> Bool` - Устаревшая: используйте встроенную функцию [StartsWith](../../builtins/basic.md#starts_ends_with) +* `String::StartsWith(string:String?, prefix:String) -> Bool` - Устаревшая: используйте встроенную функцию [StartsWith](../../builtins/basic.md#starts_ends_with) +* `String::HasSuffix(string:String?, suffix:String) -> Bool` - Устаревшая: используйте встроенную функцию [EndsWith](../../builtins/basic.md#starts_ends_with) +* `String::EndsWith(string:String?, suffix:String) -> Bool` - Устаревшая: используйте встроенную функцию [EndsWith](../../builtins/basic.md#starts_ends_with) +* `String::Reverse(string:String?) -> String?` - Устаревшая: используйте [Unicode::Reverse](unicode.md) Устаревшие функции, к использованию не рекомендуются. @@ -147,6 +147,6 @@ SELECT String::SplitToList("1,2,3,4,5,6,7", ",", 3 as Limit); -- ["1", "2", "3", {% note alert %} -Функции из библиотеки String не поддерживают кириллицу и умеют работать только с ASCII символами. Для работы со строками в кодировке UTF-8 используйте функции из [Unicode](../unicode.md). +Функции из библиотеки String не поддерживают кириллицу и умеют работать только с ASCII символами. Для работы со строками в кодировке UTF-8 используйте функции из [Unicode](unicode.md). {% endnote %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/toc_base.yaml b/ydb/docs/ru/core/yql/reference/udf/list/toc_base.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/toc_base.yaml rename to ydb/docs/ru/core/yql/reference/udf/list/toc_base.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/toc_i.yaml b/ydb/docs/ru/core/yql/reference/udf/list/toc_i.yaml similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/toc_i.yaml rename to ydb/docs/ru/core/yql/reference/udf/list/toc_i.yaml diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/unicode.md b/ydb/docs/ru/core/yql/reference/udf/list/unicode.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/unicode.md rename to ydb/docs/ru/core/yql/reference/udf/list/unicode.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/url.md b/ydb/docs/ru/core/yql/reference/udf/list/url.md similarity index 100% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/url.md rename to ydb/docs/ru/core/yql/reference/udf/list/url.md diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/yson.md b/ydb/docs/ru/core/yql/reference/udf/list/yson.md similarity index 98% rename from ydb/docs/ru/core/yql/reference/yql-core/udf/list/yson.md rename to ydb/docs/ru/core/yql/reference/udf/list/yson.md index 12080398de49..2cc6377c3cc7 100644 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/yson.md +++ b/ydb/docs/ru/core/yql/reference/udf/list/yson.md @@ -2,7 +2,7 @@ -{% include [_includes/yson/intro_header.md](_includes/yson/intro_header.md) %} +YSON — разработанный в Яндексе формат данных, похожий на JSON. * Сходства с JSON: @@ -37,7 +37,7 @@ * `Yson::Parse*** -> Yson::Lookup -> Yson::Serialize***` — извлечение значения указанного поддерева в исходном дереве YSON; * `Yson::Parse*** -> Yson::ConvertToList -> ListMap -> Yson::Lookup***` — извлечение элементов по ключу из YSON списка. -{% include [_includes/yson/intro_footer.md](_includes/yson/intro_footer.md) %} + ## Примеры @@ -244,7 +244,7 @@ Yson::YPathList(Resource<'Yson2.Node'>{Flags:AutoMap}, String) -> ListList -AGGREGATE_LIST(T [, limit:Uint64])->List -AGGREGATE_LIST_DISTINCT(T? [, limit:Uint64])->List -AGGREGATE_LIST_DISTINCT(T [, limit:Uint64])->List -``` - -Получить все значения столбца в виде списка. В сочетании с `DISTINCT` возвращает только уникальные значения. Опциональный второй параметр задает максимальное количество получаемых значений. Значение 0 равносильно отсутствию лимита. - -Если заранее известно, что уникальных значений не много, то лучше воспользоваться агрегатной функцией `AGGREGATE_LIST_DISTINCT`, которая строит тот же результат в памяти (которой при большом числе уникальных значений может не хватить). - -Порядок элементов в результирующем списке зависит от реализации и снаружи не задается. Чтобы получить упорядоченный список, необходимо отсортировать результат, например с помощью [ListSort](../../list.md#listsort). - -Чтобы получить список нескольких значений с одной строки, важно *НЕ* использовать функцию `AGGREGATE_LIST` несколько раз, а сложить все нужные значения в контейнер, например через [AsList](../../basic.md#aslist) или [AsTuple](../../basic.md#astuple) и передать этот контейнер в один вызов `AGGREGATE_LIST`. - -Например, можно использовать в сочетании с `DISTINCT` и функцией [String::JoinFromList](../../../udf/list/string.md) (аналог `','.join(list)` из Python) для распечатки в строку всех значений, которые встретились в столбце после применения [GROUP BY](../../../syntax/group_by.md). - -### Примеры - -```yql -SELECT - AGGREGATE_LIST( region ), - AGGREGATE_LIST( region, 5 ), - AGGREGATE_LIST( DISTINCT region ), - AGGREGATE_LIST_DISTINCT( region ), - AGGREGATE_LIST_DISTINCT( region, 5 ) -FROM users -``` - -```yql --- Аналог GROUP_CONCAT из MySQL -SELECT - String::JoinFromList(CAST(AGGREGATE_LIST(region, 2) AS List), ",") -FROM users -``` - -Существует также короткая форма записи этих функций - `AGG_LIST` и `AGG_LIST_DISTINCT`. - -{% note alert %} - -Выполняется **НЕ** ленивым образом, поэтому при использовании нужно быть уверенным, что список получится разумных размеров, примерно в пределах тысячи элементов. Чтобы подстраховаться, можно воспользоваться вторым опциональным числовым аргументом, который включает ограничение на число элементов в списке. - -{% endnote %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/aggregate_by.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/aggregate_by.md deleted file mode 100644 index b51e300a211f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/aggregate_by.md +++ /dev/null @@ -1,31 +0,0 @@ - -## AGGREGATE_BY и MULTI_AGGREGATE_BY {#aggregate-by} - -{% if backend_name == "YDB" and oss == true %} - -{% include [not_allow_for_olap_note](../../../../../_includes/not_allow_for_olap_note.md) %} - -{% endif %} - -Применение [фабрики агрегационной функции](../../basic.md#aggregationfactory) ко всем значениям колонки или выражения. Функция `MULTI_AGGREGATE_BY` требует, чтобы в значении колонки или выражения была структура, кортеж или список, и применяет фабрику поэлементно, размещая результат в контейнере той же формы. Если в разных значениях колонки или выражения содержатся списки разной длины, результирующий список будет иметь наименьшую из длин этих списков. - -1. Колонка, `DISTINCT` колонка или выражение; -2. Фабрика. - -### Примеры - -```yql -$count_factory = AggregationFactory("COUNT"); - -SELECT - AGGREGATE_BY(DISTINCT column, $count_factory) as uniq_count -FROM my_table; - -SELECT - MULTI_AGGREGATE_BY(nums, AggregationFactory("count")) as count, - MULTI_AGGREGATE_BY(nums, AggregationFactory("min")) as min, - MULTI_AGGREGATE_BY(nums, AggregationFactory("max")) as max, - MULTI_AGGREGATE_BY(nums, AggregationFactory("avg")) as avg, - MULTI_AGGREGATE_BY(nums, AggregationFactory("percentile", 0.9)) as p90 -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/bool_bit.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/bool_bit.md deleted file mode 100644 index e5b22e775495..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/bool_bit.md +++ /dev/null @@ -1,71 +0,0 @@ -## BOOL_AND, BOOL_OR и BOOL_XOR {#bool-and-or-xor} - -### Сигнатура - -```yql -BOOL_AND(Bool?)->Bool? -BOOL_OR(Bool?)->Bool? -BOOL_XOR(Bool?)->Bool? -``` - -Применение соответствующей логической операции (`AND`/`OR`/`XOR`) ко всем значениям булевой колонки или выражения. - -В отличие от большинства агрегатных функций, эти функции **не пропускают** `NULL` значение при агрегации и действуют по правилу: - -- `true AND null == null` -- `false OR null == null` - -Для `BOOL_AND`: - -- Для любого количества значений `true` и хотя бы одного `NULL` значения, результатом будет `NULL`. -- В случае хотя бы одного `false` значения, результатом будет `false`, независимо от наличия `NULL`. - -Для `BOOL_OR`: - -- Для любого количества значений `false` и хотя бы одного `NULL` значения, результатом будет `NULL`. -- В случае хотя бы одного `true` значения, результатом будет `true`, независимо от наличия `NULL`. - -Для `BOOL_XOR`: - -- В случае хотя бы одного `NULL` значения, результатом будет `NULL`. - -Примеры описанного поведения приведены ниже. - -Для агрегации с пропуском `NULL`-ов можно использовать функции `MIN`/`MAX` или `BIT_AND`/`BIT_OR`/`BIT_XOR`. - -### Примеры - -```yql -$data = [ - <|nonNull: true, nonFalse: true, nonTrue: NULL, anyVal: true|>, - <|nonNull: false, nonFalse: NULL, nonTrue: NULL, anyVal: NULL|>, - <|nonNull: false, nonFalse: NULL, nonTrue: false, anyVal: false|>, -]; - -SELECT - BOOL_AND(nonNull) as nonNullAnd, -- false - BOOL_AND(nonFalse) as nonFalseAnd, -- NULL - BOOL_AND(nonTrue) as nonTrueAnd, -- false - BOOL_AND(anyVal) as anyAnd, -- false - BOOL_OR(nonNull) as nonNullOr, -- true - BOOL_OR(nonFalse) as nonFalseOr, -- true - BOOL_OR(nonTrue) as nonTrueOr, -- NULL - BOOL_OR(anyVal) as anyOr, -- true - BOOL_XOR(nonNull) as nonNullXor, -- true - BOOL_XOR(nonFalse) as nonFalseXor, -- NULL - BOOL_XOR(nonTrue) as nonTrueXor, -- NULL - BOOL_XOR(anyVal) as anyXor, -- NULL -FROM AS_TABLE($data); -``` - -## BIT_AND, BIT_OR и BIT_XOR {#bit-and-or-xor} - -Применение соответствующей битовой операции ко всем значениям числовой колонки или выражения. - -### Примеры - -```yql -SELECT - BIT_XOR(unsigned_numeric_value) -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/corr_covar.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/corr_covar.md deleted file mode 100644 index 974bf2fab9a1..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/corr_covar.md +++ /dev/null @@ -1,35 +0,0 @@ -## CORRELATION и COVARIANCE {#correlation-covariance} - -### Сигнатура - -```yql -CORRELATION(Double?, Double?)->Double? -COVARIANCE(Double?, Double?)->Double? -COVARIANCE_SAMPLE(Double?, Double?)->Double? -COVARIANCE_POPULATION(Double?, Double?)->Double? -``` - -Корреляция и ковариация двух колонок. - -Также доступны сокращенные версии `CORR` или `COVAR`, а для ковариации - версии с суффиксом `SAMPLE` / `POPULATION` по аналогии с описанной выше [VARIANCE](stddev_variance.md). - -В отличие от большинства других агрегатных функций не пропускают `NULL`, а считают его за 0. - -При использовании [фабрики агрегационной функции](../../basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](../../aggregation.md#aggregateby) передается `Tuple` из двух значений. - -### Примеры - -```yql -SELECT - CORRELATION(numeric_column, another_numeric_column), - COVARIANCE(numeric_column, another_numeric_column) -FROM my_table; -``` - -```yql -$corr_factory = AggregationFactory("CORRELATION"); - -SELECT - AGGREGATE_BY(AsTuple(numeric_column, another_numeric_column), $corr_factory) -FROM my_table; -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/count_distinct_estimate.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/count_distinct_estimate.md deleted file mode 100644 index 2755a77ccba3..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/count_distinct_estimate.md +++ /dev/null @@ -1,35 +0,0 @@ -## CountDistinctEstimate, HyperLogLog и HLL {#countdistinctestimate} - -### Сигнатура - -```yql -CountDistinctEstimate(T)->Uint64? -HyperLogLog(T)->Uint64? -HLL(T)->Uint64? -``` - -Примерная оценка числа уникальных значений по алгоритму [HyperLogLog](https://en.wikipedia.org/wiki/HyperLogLog). Логически делает то же самое, что и [COUNT(DISTINCT ...)](../../aggregation.md#count), но работает значительно быстрее ценой некоторой погрешности. - -Аргументы: - -1. Значение для оценки; -2. Точность (от 4 до 18 включительно, по умолчанию 14). - -Выбор точности позволяет разменивать дополнительное потребление вычислительных ресурсов и оперативной памяти на уменьшение погрешности. - -На данный момент все три функции являются алиасами, но в будущем `CountDistinctEstimate` может начать использовать другой алгоритм. - -### Примеры - -```yql -SELECT - CountDistinctEstimate(my_column) -FROM my_table; -``` - -```yql -SELECT - HyperLogLog(my_column, 4) -FROM my_table; -``` - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/histogram.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/histogram.md deleted file mode 100644 index 2ccc42e68181..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/histogram.md +++ /dev/null @@ -1,166 +0,0 @@ -## HISTOGRAM {#histogram} - -### Сигнатура - -```yql -HISTOGRAM(Double?)->HistogramStruct? -HISTOGRAM(Double?, weight:Double)->HistogramStruct? -HISTOGRAM(Double?, intervals:Uint32)->HistogramStruct? -HISTOGRAM(Double?, weight:Double, intervals:Uint32)->HistogramStruct? -``` - -В описании сигнатур под HistogramStruct подразумевается результат работы агрегатной функции, который является структурой определенного вида. - -Построение примерной гистограммы по числовому выражению с автоматическим выбором корзин. - -[Вспомогательные функции](../../../udf/list/histogram.md) - -### Базовые настройки - -Ограничение на число корзин можно задать с помощью опционального аргумента, значение по умолчанию — 100. Следует иметь в виду, что дополнительная точность стоит дополнительных вычислительных ресурсов и может негативно сказываться на времени выполнения запроса, а в экстремальных случаях — и на его успешности. - -### Поддержка весов - -Имеется возможность указать «вес» для каждого значения, участвующего в построении гистограммы. Для этого вторым аргументом в агрегатную функцию нужно передать выражение для вычисления веса. По умолчанию всегда используется вес `1.0`. Если используются нестандартные веса, ограничение на число корзин можно задать третьим аргументом. - -В случае, если передано два аргумента, смысл второго аргумента определяется по его типу (целочисленный литерал — ограничение на число корзин, в противном случае — вес). - -{% if tech %} - -### Алгоритмы - -* [Оригинальный whitepaper](http://jmlr.org/papers/volume11/ben-haim10a/ben-haim10a.pdf); - -Доступны разные модификации алгоритма: - -```yql -AdaptiveDistanceHistogram -AdaptiveWeightHistogram -AdaptiveWardHistogram -BlockWeightHistogram -BlockWardHistogram -``` - -По умолчанию `HISTOGRAM` является синонимом к `AdaptiveWardHistogram`. Обе функции эквивалентны и взаимозаменимы во всех контекстах. - -Алгоритмы Distance, Weight и Ward отличаются формулами объединения двух точек в одну: - -```c++ -TWeightedValue CalcDistanceQuality(const TWeightedValue& left, const TWeightedValue& right) { - return TWeightedValue(right.first - left.first, left.first); -} - -TWeightedValue CalcWeightQuality(const TWeightedValue& left, const TWeightedValue& right) { - return TWeightedValue(right.second + left.second, left.first); -} - -TWeightedValue CalcWardQuality(const TWeightedValue& left, const TWeightedValue& right) { - const double N1 = left.second; - const double N2 = right.second; - const double mu1 = left.first; - const double mu2 = right.first; - return TWeightedValue(N1 * N2 / (N1 + N2) * (mu1 - mu2) * (mu1 - mu2), left.first); -} -``` - -Чем отличается Adaptive и Block: - -{% block info %} - -Contrary to adaptive histogram, block histogram doesn't rebuild bins after the addition of each point. Instead, it accumulates points and in case the amount of points overflows specified limits, it shrinks all the points at once to produce histogram. Indeed, there exist two limits and two shrinkage operations: - -1. FastGreedyShrink is fast but coarse. It is used to shrink from upper limit to intermediate limit (override FastGreedyShrink to set specific behaviour). -2. SlowShrink is slow, but produces finer histogram. It shrinks from the intermediate limit to the actual number of bins in a manner similar to that in adaptive histogram (set CalcQuality in constuctor) - -While FastGreedyShrink is used most of the time, SlowShrink is mostly used for histogram finalization - -{% endblock %} - -{% endif %} - -### Если нужна точная гистограмма - -1. Можно воспользоваться описанными ниже агрегатными функциями с фиксированными сетками корзин: [LinearHistogram](#linearhistogram) или [LogarithmicHistogram](#linearhistogram). -2. Можно самостоятельно вычислить номер корзины для каждой строки и сделать по нему [GROUP BY](../../../syntax/group_by.md). - -При использовании [фабрики агрегационной функции](../../basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](../../aggregation.md#aggregateby) передается `Tuple` из значения и веса. - -### Примеры - -```yql -SELECT - HISTOGRAM(numeric_column) -FROM my_table; -``` - -```yql -SELECT - Histogram::Print( - HISTOGRAM(numeric_column, 10), - 50 - ) -FROM my_table; -``` - -```yql -$hist_factory = AggregationFactory("HISTOGRAM"); - -SELECT - AGGREGATE_BY(AsTuple(numeric_column, 1.0), $hist_factory) -FROM my_table; -``` - -## LinearHistogram, LogarithmicHistogram и LogHistogram {#linearhistogram} - -Построение гистограммы по явно указанной фиксированной шкале корзин. - -### Сигнатура - -```yql -LinearHistogram(Double?)->HistogramStruct? -LinearHistogram(Double? [, binSize:Double [, min:Double [, max:Double]]])->HistogramStruct? - -LogarithmicHistogram(Double?)->HistogramStruct? -LogarithmicHistogram(Double? [, logBase:Double [, min:Double [, max:Double]]])->HistogramStruct? -LogHistogram(Double?)->HistogramStruct? -LogHistogram(Double? [, logBase:Double [, min:Double [, max:Double]]])->HistogramStruct? -``` - -Аргументы: - -1. Выражение, по значению которого строится гистограмма. Все последующие — опциональны. -2. Расстояние между корзинами для `LinearHistogram` или основание логарифма для `LogarithmicHistogram` / `LogHistogram` (это алиасы). В обоих случаях значение по умолчанию — 10. -3. Минимальное значение. По умолчанию минус бесконечность. -4. Максимальное значение. По умолчанию плюс бесконечность. - -Формат результата полностью аналогичен [адаптивным гистограммам](#histogram), что позволяет использовать тот же [набор вспомогательных функций](../../../udf/list/histogram.md). - -Если разброс входных значений неконтролируемо велик, рекомендуется указывать минимальное и максимальное значение для предотвращения потенциальных падений из-за высокого потребления памяти. - -### Примеры - -```yql -SELECT - LogarithmicHistogram(numeric_column, 2) -FROM my_table; -``` - -## CDF (cumulative distribution function) {#histogramcdf} - -К каждому виду функции Histogram можно приписать суффикс CDF для построения кумулятивной функции распределения. Конструкции - -```yql -SELECT - Histogram::ToCumulativeDistributionFunction(Histogram::Normalize(<вид_функции>Histogram(numeric_column))) -FROM my_table; -``` - -и - -```yql -SELECT - <вид_функции>HistogramCDF(numeric_column) -FROM my_table; -``` - -полностью эквивалентны. \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/max_min_by.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/max_min_by.md deleted file mode 100644 index 94301df96c82..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/max_min_by.md +++ /dev/null @@ -1,51 +0,0 @@ -## MAX_BY и MIN_BY {#max-min-by} - -### Сигнатура - -```yql -MAX_BY(T1?, T2)->T1? -MAX_BY(T1, T2)->T1? -MAX_BY(T1, T2, limit:Uint64)->List? - -MIN_BY(T1?, T2)->T1? -MIN_BY(T1, T2)->T1? -MIN_BY(T1, T2, limit:Uint64)->List? -``` - -Вернуть значение первого аргумента для строки таблицы, в которой второй аргумент оказался минимальным/максимальным. - -Опционально можно указать третий аргумент N, который влияет на поведение в случае, если в таблице есть несколько строк с одинаковым минимальным или максимальным значением: - -* Если N не указано — будет возвращено значение одной из строк, а остальные отбрасываются. -* Если N указано — будет возвращен список со всеми значениями, но не более N, все значения после достижения указанного числа отбрасываются. - -При выборе значения N рекомендуется не превышать порядка сотен или тысяч, чтобы не возникало проблем с ограниченной доступной памятью на кластерах {{ backend_name }}. - -Если для задачи обязательно нужны все значения, и их количество может измеряться десятками тысяч и больше, то вместо данных агрегационных функций следует использовать `JOIN` исходной таблицы с подзапросом, где по ней же сделан `GROUP BY + MIN/MAX` на интересующих вас колонках. - -{% note warning %} - -Если второй аргумент всегда `NULL`, то результатом агрегации будет `NULL`. - -{% endnote %} - -При использовании [фабрики агрегационной функции](../../basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](../../aggregation.md#aggregateby) передается `Tuple` из значения и ключа. - -### Примеры - -```yql -SELECT - MIN_BY(value, LENGTH(value)), - MAX_BY(value, key, 100) -FROM my_table; -``` - -```yql -$min_by_factory = AggregationFactory("MIN_BY"); -$max_by_factory = AggregationFactory("MAX_BY", 100); - -SELECT - AGGREGATE_BY(AsTuple(value, LENGTH(value)), $min_by_factory), - AGGREGATE_BY(AsTuple(value, key), $max_by_factory) -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/percentile_median.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/percentile_median.md deleted file mode 100644 index ef747e848dd8..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/percentile_median.md +++ /dev/null @@ -1,37 +0,0 @@ -## PERCENTILE и MEDIAN {#percentile-median} - -### Сигнатура - -```yql -PERCENTILE(T, Double)->T -PERCENTILE(T, Tuple)->Tuple -PERCENTILE(T, Struct)->Struct -PERCENTILE(T, List)->List - -MEDIAN(T, [ Double ])->T -MEDIAN(T, [ Tuple ])->Tuple -MEDIAN(T, [ Struct ])->Struct -MEDIAN(T, [ List ])->List -``` - -Подсчет процентилей по амортизированной версии алгоритма [TDigest](https://github.com/tdunning/t-digest). `MEDIAN(x)` без второго аргумента — алиас для `PERCENTILE(x, 0.5)`. -`MEDIAN` с двумя аргументами полностью эквивалентен `PERCENTILE`. - -В качестве первого аргумента `PERCENTILE`/`MEDIAN` принимает выражение типа `T`. В качестве типа `T` на данный момент поддерживаются типы `Interval` и `Double` (а также типы которые допускают неявное приведение к ним - например целочисленные типы). - -В качестве второго аргумента можно использовать либо один `Double` (значение перцентиля), либо сразу несколько значений перцентиля в виде `Tuple`/`Struct`/`List`. - -Значения прецентиля должны лежать в диапазоне от 0.0 до 1.0 включительно. - -### Примеры - -```yql -SELECT - MEDIAN(numeric_column), - PERCENTILE(numeric_column, 0.99), - PERCENTILE(CAST(string_column as Double), (0.01, 0.5, 0.99)), -- подсчет сразу трех перцентилей - PERCENTILE(numeric_column, AsStruct(0.01 as p01, 0.5 as median, 0.99 as p99)), -- используя структуру, значениям перцентиля можно дать удобные имена - PERCENTILE(numeric_column, ListFromRange(0.00, 1.05, 0.05)), -- подсчет множества перцентилей (от 0.0 до 1.0 включительно с шагом 0.05) -FROM my_table; -``` - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/session_start.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/session_start.md deleted file mode 100644 index c8236bd7704b..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/session_start.md +++ /dev/null @@ -1,6 +0,0 @@ -## SessionStart {#session-start} - -Без аргументов. Допускается только при наличии [SessionWindow](../../../syntax/group_by.md#session-window) в -[GROUP BY](../../../syntax/group_by.md) / [PARTITION BY](../../../syntax/window.md#partition). -Возвращает значение ключевой колонки `SessionWindow`. В случае `SessionWindow` с двумя аргументами – минимальное значение первого аргумента внутри группы/раздела. -В случае раширенного варианта `SessionWindoow` – значение второго элемента кортежа, возвращаемого ``, при котором первый элемент кортежа равен `True`. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/simple.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/simple.md deleted file mode 100644 index 2806321fcfbc..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/simple.md +++ /dev/null @@ -1,188 +0,0 @@ -## COUNT {#count} - -### Сигнатура - -```yql -COUNT(*)->Uint64 -COUNT(T)->Uint64 -COUNT(T?)->Uint64 -``` - -Подсчет количества строк в строковой или колоночной таблице (если в качестве аргумента указана `*` или константа) или непустых значений в столбце таблицы (если в качестве аргумента указано имя столбца). - -Как и другие агрегатные функции, может использоваться в сочетании с [GROUP BY](../../../syntax/group_by.md) для получения статистики по частям таблицы, соответствующим значениям в столбцах, по которым идет группировка. {% if select_statement != "SELECT STREAM" %}А модификатор [DISTINCT](../../../syntax/group_by.md#distinct) позволяет посчитать число уникальных значений.{% endif %} - -### Примеры - -```yql -SELECT COUNT(*) FROM my_table; -``` - -```yql -SELECT key, COUNT(value) FROM my_table GROUP BY key; -``` -{% if select_statement != "SELECT STREAM" %} - -```yql -SELECT COUNT(DISTINCT value) FROM my_table; -``` -{% endif %} - -## MIN и MAX {#min-max} - -### Сигнатура - -```yql -MIN(T?)->T? -MIN(T)->T? -MAX(T?)->T? -MAX(T)->T? -``` - -Минимальное или максимальное значение. - -В качестве аргумента допустимо произвольное вычислимое выражение с результатом, допускающим сравнение значений. - -### Примеры - -```yql -SELECT MIN(value), MAX(value) FROM my_table; -``` - -## SUM {#sum} - -### Сигнатура - -```yql -SUM(Unsigned?)->Uint64? -SUM(Signed?)->Int64? -SUM(Interval?)->Interval? -SUM(Decimal(N, M)?)->Decimal(35, M)? -``` - -Сумма чисел. - -В качестве аргумента допустимо произвольное вычислимое выражение с числовым результатом или типом `Interval`. - -Целые числа автоматически расширяются до 64 бит, чтобы уменьшить риск переполнения. - -```yql -SELECT SUM(value) FROM my_table; -``` - -## AVG {#avg} - -### Сигнатура - -```yql -AVG(Double?)->Double? -AVG(Interval?)->Interval? -AVG(Decimal(N, M)?)->Decimal(N, M)? -``` - -Арифметическое среднее. - -В качестве аргумента допустимо произвольное вычислимое выражение с числовым результатом или типом `Interval`. - -Целочисленные значения и интервалы времени автоматически приводятся к Double. - -### Примеры - -```yql -SELECT AVG(value) FROM my_table; -``` - -## COUNT_IF {#count-if} - -### Сигнатура - -```yql -COUNT_IF(Bool?)->Uint64? -``` - -Количество строк, для которых указанное в качестве аргумента выражение истинно (результат вычисления выражения — true). - -Значение `NULL` приравнивается к `false` (в случае, если тип аргумента `Bool?`). - -Функция *не* выполняет неявного приведения типов к булевым для строк и чисел. - -### Примеры - -```yql -SELECT - COUNT_IF(value % 2 == 1) AS odd_count -``` - -{% if select_statement != "SELECT STREAM" %} - -{% note info %} - -Если нужно посчитать число уникальных значений на строках, где выполняется условие, то в отличие от остальных агрегатных функций модификатор [DISTINCT](../../../syntax/group_by.md#distinct) тут не поможет, так как в аргументах нет никаких значений. Для получения данного результата, стоит воспользоваться в подзапросе встроенной функцией [IF](../../../builtins/basic.md#if) с двумя аргументами (чтобы в else получился `NULL`), а снаружи сделать [COUNT(DISTINCT ...)](#count) по её результату. - -{% endnote %} - -{% endif %} - -## SUM_IF и AVG_IF {#sum-if} - -### Сигнатура - -```yql -SUM_IF(Unsigned?, Bool?)->Uint64? -SUM_IF(Signed?, Bool?)->Int64? -SUM_IF(Interval?, Bool?)->Interval? - -AVG_IF(Double?, Bool?)->Double? -``` - -Сумма или арифметическое среднее, но только для строк, удовлетворяющих условию, переданному вторым аргументом. - -Таким образом, `SUM_IF(value, condition)` является чуть более короткой записью для `SUM(IF(condition, value))`, аналогично для `AVG`. Расширение типа данных аргумента работает так же аналогично одноименным функциям без суффикса. - -### Примеры - -```yql -SELECT - SUM_IF(value, value % 2 == 1) AS odd_sum, - AVG_IF(value, value % 2 == 1) AS odd_avg, -FROM my_table; -``` - -При использовании [фабрики агрегационной функции](../../basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](../../aggregation.md#aggregateby) передается `Tuple` из значения и предиката. - -```yql -$sum_if_factory = AggregationFactory("SUM_IF"); -$avg_if_factory = AggregationFactory("AVG_IF"); - -SELECT - AGGREGATE_BY(AsTuple(value, value % 2 == 1), $sum_if_factory) AS odd_sum, - AGGREGATE_BY(AsTuple(value, value % 2 == 1), $avg_if_factory) AS odd_avg -FROM my_table; -``` - -## SOME {#some} - -### Сигнатура - -```yql -SOME(T?)->T? -SOME(T)->T? -``` - -Получить значение указанного в качестве аргумента выражения для одной из строк таблицы. Не дает никаких гарантий о том, какая именно строка будет использована. - -Из-за отсутствия гарантий `SOME` вычислительно дешевле, чем часто использующиеся в подобных ситуациях [MIN и MAX](#min-max). - -### Примеры - -```yql -SELECT - SOME(value) -FROM my_table; -``` - -{% note alert %} - -При вызове агрегатной функции `SOME` несколько раз **не** гарантируется, что все значения результатов будут взяты с одной строки исходной таблицы. Для получения данной гарантии, нужно запаковать значения в какой-либо из контейнеров и передавать в `SOME` уже его. Например, для структуры это можно сделать с помощью [AsStruct](../../../builtins/basic.md#asstruct) - -{% endnote %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/stddev_variance.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/stddev_variance.md deleted file mode 100644 index 1d2fce8b0bf5..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/stddev_variance.md +++ /dev/null @@ -1,37 +0,0 @@ -## STDDEV и VARIANCE {#stddev-variance} - -### Сигнатура - -```yql -STDDEV(Double?)->Double? -STDDEV_POPULATION(Double?)->Double? -POPULATION_STDDEV(Double?)->Double? -STDDEV_SAMPLE(Double?)->Double? -STDDEVSAMP(Double?)->Double? - -VARIANCE(Double?)->Double? -VARIANCE_POPULATION(Double?)->Double? -POPULATION_VARIANCE(Double?)->Double? -VARPOP(Double?)->Double? -VARIANCE_SAMPLE(Double?)->Double? -``` - -Стандартное отклонение и дисперсия по колонке. Используется [однопроходной параллельный алгоритм](https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm), результат которого может отличаться от полученного более распространенными методами, требующими двух проходов по данным. - -По умолчанию вычисляются выборочная дисперсия и стандартное отклонение. Доступны несколько способов записи: - -* с суффиксом/префиксом `POPULATION`, например: `VARIANCE_POPULATION`, `POPULATION_VARIANCE` — вычисляет дисперсию/стандартное отклонение для генеральной совокупности; -* с суффиксом `SAMPLE` или без суффикса, например `VARIANCE_SAMPLE`, `SAMPLE_VARIANCE`, `VARIANCE` — вычисляет выборочную дисперсию и стандартное отклонение. - -Также определено несколько сокращенных алиасов, например `VARPOP` или `STDDEVSAMP`. - -Если все переданные значения — `NULL`, возвращает `NULL`. - -### Примеры - -```yql -SELECT - STDDEV(numeric_column), - VARIANCE(numeric_column) -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/top_bottom.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/top_bottom.md deleted file mode 100644 index 0b56863249c1..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/top_bottom.md +++ /dev/null @@ -1,63 +0,0 @@ -## TOP и BOTTOM {#top-bottom} - -### Сигнатура - -```yql -TOP(T?, limit:Uint32)->List -TOP(T, limit:Uint32)->List -BOTTOM(T?, limit:Uint32)->List -BOTTOM(T, limit:Uint32)->List -``` - -Вернуть список максимальных/минимальных значений выражения. Первый аргумент - выражение, второй - ограничение на количество элементов. - -### Примеры - -```yql -SELECT - TOP(key, 3), - BOTTOM(value, 3) -FROM my_table; -``` - -```yql -$top_factory = AggregationFactory("TOP", 3); -$bottom_factory = AggregationFactory("BOTTOM", 3); - -SELECT - AGGREGATE_BY(key, $top_factory), - AGGREGATE_BY(value, $bottom_factory) -FROM my_table; -``` - -## TOP_BY и BOTTOM_BY {#top-bottom-by} - -### Сигнатура - -```yql -TOP_BY(T1, T2, limit:Uint32)->List -BOTTOM_BY(T1, T2, limit:Uint32)->List -``` - -Вернуть список значений первого аргумента для строк с максимальными/минимальными значениями второго аргумента. Третий аргумент - ограничение на количество элементов в списке. - -При использовании [фабрики агрегационной функции](../../basic.md#aggregationfactory) в качестве первого аргумента [AGGREGATE_BY](../../aggregation.md#aggregateby) передается `Tuple` из значения и ключа. Ограничение на количество элементов в этом случае передаётся вторым аргументом при создании фабрики. - -### Примеры - -```yql -SELECT - TOP_BY(value, LENGTH(value), 3), - BOTTOM_BY(value, key, 3) -FROM my_table; -``` - -```yql -$top_by_factory = AggregationFactory("TOP_BY", 3); -$bottom_by_factory = AggregationFactory("BOTTOM_BY", 3); - -SELECT - AGGREGATE_BY(AsTuple(value, LENGTH(value)), $top_by_factory), - AGGREGATE_BY(AsTuple(value, key), $bottom_by_factory) -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/topfreq_mode.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/topfreq_mode.md deleted file mode 100644 index 45ecc881cc19..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/aggregation/topfreq_mode.md +++ /dev/null @@ -1,29 +0,0 @@ -## TOPFREQ и MODE {#topfreq-mode} - -### Сигнатура - -```yql -TOPFREQ(T [, num:Uint32 [, bufSize:Uint32]])->List> -MODE(T [, num:Uint32 [, bufSize:Uint32]])->List> -``` - -Получение **приближенного** списка самых часто встречающихся значений колонки с оценкой их числа. Возвращают список структур с двумя полями: - -* `Value`— найденное часто встречающееся значение; -* `Frequency` — оценка числа упоминаний в таблице. - -Обязательный аргумент: само значение. - -Опциональные аргументы: - -1. Для `TOPFREQ` — желаемое число элементов в результате. `MODE` является алиасом к `TOPFREQ` с 1 в этом аргументе. У `TOPFREQ` по умолчанию тоже 1. -2. Число элементов в используемом буфере, что позволяет разменивать потребление памяти на точность. По умолчанию 100. - -### Примеры - -```yql -SELECT - MODE(my_column), - TOPFREQ(my_column, 5, 1000) -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/abs.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/abs.md deleted file mode 100644 index decad1dc4986..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/abs.md +++ /dev/null @@ -1,16 +0,0 @@ -## Abs {#abs} - -Абсолютное значение числа. - -### Сигнатура - -```yql -Abs(T)->T -Abs(T?)->T? -``` - -### Примеры - -```yql -SELECT Abs(-123); -- 123 -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/aggr_factory.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/aggr_factory.md deleted file mode 100644 index ce69db24eceb..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/aggr_factory.md +++ /dev/null @@ -1,79 +0,0 @@ -## AggregationFactory {#aggregationfactory} - -Создать фабрику для [агрегационных функций](../../aggregation.md) для того чтобы разделить процесс описания того, как агрегировать данные, и то, к каким данным это применять. - -Аргументы: - -1. Строка в кавычках, являющаяся именем агрегационной функции, например ["MIN"](../../aggregation.md#min). -2. Опциональные параметры агрегационной функции, которые не зависят от данных. Например, значение percentile в [PERCENTILE](../../aggregation.md#percentile). - -Полученную фабрику можно использовать как второй параметр функции [AGGREGATE_BY](../../aggregation.md#aggregateby). -Если агрегационная функция работает на двух колонках вместо одной, как например, [MIN_BY](../../aggregation.md#minby), то в [AGGREGATE_BY](../../aggregation.md#aggregateby) первым аргументом передается `Tuple` из двух значений. Подробнее это указано при описании такой агрегационной функции. - -### Примеры - -```yql -$factory = AggregationFactory("MIN"); -SELECT - AGGREGATE_BY(value, $factory) AS min_value -- применить MIN агрегацию к колонке value -FROM my_table; -``` - -## AggregateTransformInput {#aggregatetransform} - -`AggregateTransformInput()` преобразует фабрику для [агрегационных функций](../../aggregation.md), например, полученную через функцию [AggregationFactory](#aggregationfactory) в другую фабрику, в которой перед началом выполнения агрегации производится указанное преобразование входных элементов. - -Аргументы: - -1. Фабрика для агрегационных функций; -2. Лямбда функция с одним аргументом, преобразующая входной элемент. - -### Примеры - -```yql -$f = AggregationFactory("sum"); -$g = AggregateTransformInput($f, ($x) -> (cast($x as Int32))); -$h = AggregateTransformInput($f, ($x) -> ($x * 2)); -SELECT ListAggregate([1,2,3], $f); -- 6 -SELECT ListAggregate(["1","2","3"], $g); -- 6 -SELECT ListAggregate([1,2,3], $h); -- 12 -``` - -## AggregateTransformOutput {#aggregatetransformoutput} - -`AggregateTransformOutput()` преобразует фабрику для [агрегационных функций](../../aggregation.md), например, полученную через функцию [AggregationFactory](#aggregationfactory) в другую фабрику, в которой после окончания выполнения агрегации производится указанное преобразование результата. - -Аргументы: - -1. Фабрика для агрегационных функций; -2. Лямбда функция с одним аргументом, преобразующая результат. - -### Примеры - -```yql -$f = AggregationFactory("sum"); -$g = AggregateTransformOutput($f, ($x) -> ($x * 2)); -SELECT ListAggregate([1,2,3], $f); -- 6 -SELECT ListAggregate([1,2,3], $g); -- 12 -``` - -## AggregateFlatten {#aggregateflatten} - -Адаптирует фабрику для [агрегационных функций](../../aggregation.md), например, полученную через функцию [AggregationFactory](#aggregationfactory) так, чтобы выполнять агрегацию над входными элементами - списками. Эта операция похожа на [FLATTEN LIST BY](../../../syntax/flatten.md) - производится агрегация каждого элемента списка. - -Аргументы: - -1. Фабрика для агрегационных функций. - -### Примеры - -```yql -$i = AggregationFactory("AGGREGATE_LIST_DISTINCT"); -$j = AggregateFlatten($i); -SELECT AggregateBy(x, $j) from ( - SELECT [1,2] as x - union all - SELECT [2,3] as x -); -- [1, 2, 3] - -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/as_container.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/as_container.md deleted file mode 100644 index e8b5052e6309..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/as_container.md +++ /dev/null @@ -1,37 +0,0 @@ -## AsTuple, AsStruct, AsList, AsDict, AsSet, AsListStrict, AsDictStrict и AsSetStrict {#as-container} - -Создает контейнеры соответствующих типов. Также доступна [операторная запись](../../basic.md#containerliteral) литералов контейнеров. - -Особенности: - -* Элементы контейнеров передаются через аргументы, таким образом число элементов результирующего контейнера равно числу переданных аргументов, кроме случая, когда повторяются ключи словаря. -* В `AsTuple` и `AsStruct` могут быть вызваны без аргументов, а также аргументы могут иметь разные типы. -* Имена полей в `AsStruct` задаются через `AsStruct(field_value AS field_name)`. -* Для создания списка требуется хотя бы один аргумент, если нужно вывести типы элементов. Для создания пустого списка с заданным типом элементов используется функция [ListCreate](../../list.md#listcreate). Можно создать пустой список как вызов `AsList()` без аргументов, в этом случае это выражение будет иметь тип `EmptyList`. -* Для создания словаря требуется хотя бы один аргумент, если нужно вывести типы элементов. Для создания пустого словаря с заданным типом элементов используется функция [DictCreate](../../dict.md#dictcreate). Можно создать пустой словарь как вызов `AsDict()` без аргументов, в этом случае это выражение будет иметь тип `EmptyDict`. -* Для создания множества требуется хотя бы один аргумент, если нужно вывести типы элементов. Для создания пустого множества с заданным типом элементов используется функция [SetCreate](../../dict.md#setcreate). Можно создать пустое множество как вызов `AsSet()` без аргументов, в этом случае это выражение будет иметь тип `EmptyDict`. -* `AsList` выводит общий тип элементов списка. При несовместимых типах генерируется ошибка типизации. -* `AsDict` выводит раздельно общие типы ключей и значений. При несовместимых типах генерируется ошибка типизации. -* `AsSet` выводит общие типы ключей. При несовместимых типах генерируется ошибка типизации. -* `AsListStrict`, `AsDictStrict`, `AsSetStrict` требуют одинакового типа для аргументов. -* В `AsDict` и `AsDictStrict` в качестве аргументов ожидаются `Tuple` из двух элементов: ключ и значение, соответственно. Если ключи повторяются, в словаре останется только значение для первого ключа. -* В `AsSet` и `AsSetStrict` в качестве аргументов ожидаются ключи. - -### Примеры - -```yql -SELECT - AsTuple(1, 2, "3") AS `tuple`, - AsStruct( - 1 AS a, - 2 AS b, - "3" AS c - ) AS `struct`, - AsList(1, 2, 3) AS `list`, - AsDict( - AsTuple("a", 1), - AsTuple("b", 2), - AsTuple("c", 3) - ) AS `dict`, - AsSet(1, 2, 3) AS `set` -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/as_tagged.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/as_tagged.md deleted file mode 100644 index 2923d2ebd33f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/as_tagged.md +++ /dev/null @@ -1,32 +0,0 @@ -## AsTagged, Untag {#as-tagged} - -Оборачивает значение в [Tagged тип данных](../../../types/special.md) с указанной меткой с сохранением физического типа данных. `Untag` — обратная операция. - -### Сигнатура - -```yql -AsTagged(T, tagName:String)->Tagged -AsTagged(T?, tagName:String)->Tagged? - -Untag(Tagged)->T -Untag(Tagged?)->T? -``` - -Обязательные аргументы: - -1. Значение произвольного типа; -2. Имя метки. - -Возвращает копию значения из первого аргумента с указанной меткой в типе данных. - -Примеры сценариев использования: - -* Возвращение на клиент для отображения в веб-интерфейсе медиа-файлов из base64-encoded строк{% if feature_webui %}. Поддержка меток в веб-UI YQL [описана здесь](../../../interfaces/web_tagged.md){% endif %}. - -{% if feature_mapreduce %} - -* Защита на границах вызова UDF от передачи некорректных значений; - -{% endif %} - -* Дополнительные уточнения на уровне типов возвращаемых колонок. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/assume_strict.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/assume_strict.md deleted file mode 100644 index f78435dea7a9..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/assume_strict.md +++ /dev/null @@ -1,24 +0,0 @@ -## AssumeStrict {#assumestrict} - -### Сигнатура - -```yql -AssumeStrict(T)->T -``` - -Функция `AssumeStrict` возвращает свой аргумент. Использование этой функции – способ сказать оптимизатору YQL, что выражение в аргументе является *строгим*, т.е. свободным от ошибок времени выполнения. -Большинство встроенных функций и операторов YQL являются строгими, но есть исключения – например [Unwrap](../../basic.md#optional-ops) и [Ensure](../../basic.md#ensure). -Кроме того, нестрогим выражением считается вызов UDF. - -Если есть уверенность, что при вычислении выражения ошибок времени выполнения на самом деле не возникает, то имеет смысл использовать `AssumeStrict`. - -### Пример - -```yql -SELECT * FROM T1 AS a JOIN T2 AS b USING(key) -WHERE AssumeStrict(Unwrap(CAST(a.key AS Int32))) == 1; -``` - -В данном примере мы считаем что все значения текстовой колонки `a.key` в таблице `T1` являются валидными числами, поэтому Unwrap не приводит к ошибке. -При налиичии `AssumeStrict` оптимизатор сможет выполнить сначала фильтрацию, а потом JOIN. -Без `AssumeStrict` такая оптимизация не выполняется – оптимизатор обязан учитывать ситуацию, при которой в колонке `a.key` есть нечисловые значения, которые отфильтровываются `JOIN`ом. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/bitops.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/bitops.md deleted file mode 100644 index c6883af9f864..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/bitops.md +++ /dev/null @@ -1,34 +0,0 @@ -## ...Bit {#bitops} - -`TestBit()`, `ClearBit()`, `SetBit()` и `FlipBit()` - проверить, сбросить, установить или инвертировать бит в беззнаковом числе по указанному порядковому номеру бита. - -### Сигнатуры - -```yql -TestBit(T, Uint8)->Bool -TestBit(T?, Uint8)->Bool? - -ClearBit(T, Uint8)->T -ClearBit(T?, Uint8)->T? - -SetBit(T, Uint8)->T -SetBit(T?, Uint8)->T? - -FlipBit(T, Uint8)->T -FlipBit(T?, Uint8)->T? -``` - -Аргументы: - -1. Беззнаковое число, над которым выполнять требуемую операцию. TestBit также реализован и для строк. -2. Номер бита. - -TestBit возвращает `true/false`. Остальные функции возвращают копию своего первого аргумента с проведенным соответствующим преобразованием. - -### Примеры - -```yql -SELECT - TestBit(1u, 0), -- true - SetBit(8u, 0); -- 9 -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/byteat.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/byteat.md deleted file mode 100644 index 4eb6bc1b184a..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/byteat.md +++ /dev/null @@ -1,27 +0,0 @@ -## ByteAt {#byteat} - -Получение значение байта в строке по индексу от её начала. В случае некорректного индекса возвращается `NULL`. - -### Сигнатура - -```yql -ByteAt(String, Uint32)->Uint8 -ByteAt(String?, Uint32)->Uint8? - -ByteAt(Utf8, Uint32)->Uint8 -ByteAt(Utf8?, Uint32)->Uint8? -``` - -Аргументы: - -1. Строка: `String` или `Utf8`; -2. Индекс: `Uint32`. - -### Примеры - -```yql -SELECT - ByteAt("foo", 0), -- 102 - ByteAt("foo", 1), -- 111 - ByteAt("foo", 9); -- NULL -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/callable.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/callable.md deleted file mode 100644 index 923916fe9d87..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/callable.md +++ /dev/null @@ -1,29 +0,0 @@ -## Callable {#callable} - -Создать вызываемое значение с заданной сигнатурой из лямбда-функции. Обычно используется для того, чтобы размещать вызываемые значения в контейнерах. - -### Сигнатура - -```yql -Callable(TypeT>>, lambda)->Callable<(...)->T> -``` - -Аргументы: - -1. Тип; -2. Лямбда-функция. - -### Примеры - -```yql -$lambda = ($x) -> { - RETURN CAST($x as String) -}; - -$callables = AsTuple( - Callable(Callable<(Int32)->String>, $lambda), - Callable(Callable<(Bool)->String>, $lambda), -); - -SELECT $callables.0(10), $callables.1(true); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/coalesce.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/coalesce.md deleted file mode 100644 index ea79259d952f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/coalesce.md +++ /dev/null @@ -1,38 +0,0 @@ -## COALESCE {#coalesce} - -Перебирает аргументы слева направо и возвращает первый найденный непустой аргумент. Чтобы результат получился гарантированно непустым (не [optional типа](../../../types/optional.md)), самый правый аргумент должен быть такого типа (зачастую используют литерал). При одном аргументе возвращает его без изменений. - -### Сигнатура - -```yql -COALESCE(T?, ..., T)->T -COALESCE(T?, ..., T?)->T? -``` - -Позволяет передавать потенциально пустые значения в функции, которые не умеют обрабатывать их самостоятельно. - -Доступен краткий формат записи в виде оператора `??`. Можно использовать алиас `NVL`. - -### Примеры - -```yql -SELECT COALESCE( - maybe_empty_column, - "it's empty!" -) FROM my_table; -``` - -```yql -SELECT - maybe_empty_column ?? "it's empty!" -FROM my_table; -``` - -```yql -SELECT NVL( - maybe_empty_column, - "it's empty!" -) FROM my_table; -``` - -Все три примера выше эквивалентны. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/container_literal.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/container_literal.md deleted file mode 100644 index ba35f35f6c7e..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/container_literal.md +++ /dev/null @@ -1,35 +0,0 @@ -## Литералы контейнеров {#containerliteral} - -Для некоторых контейнеров возможна операторная форма записи их литеральных значений: - -* Кортеж — `(value1, value2...)`; -* Структура — `<|name1: value1, name2: value2...|>`; -* Список — `[value1, value2,...]`; -* Словарь — `{key1: value1, key2: value2...}`; -* Множество — `{key1, key2...}`. - -Во всех случаях допускается незначащая хвостовая запятая. Для кортежа с одним элементом эта запятая является обязательной - `(value1,)`. -Для имен полей в литерале структуры допускается использовать выражение, которое можно посчитать в evaluation time, например, строковые литералы, а также идентификаторы (в том числе в backticks). - -Для списка внутри используется функция [AsList](../../basic.md#as-container), словаря - [AsDict](../../basic.md#as-container), множества - [AsSet](../../basic.md#as-container), кортежа - [AsTuple](../../basic.md#as-container), структуры - [AsStruct](../../basic.md#as-container). - -### Примеры - -```yql -$name = "computed " || "member name"; -SELECT - (1, 2, "3") AS `tuple`, - <| - `complex member name`: 2.3, - b: 2, - $name: "3", - "inline " || "computed member name": false - |> AS `struct`, - [1, 2, 3] AS `list`, - { - "a": 1, - "b": 2, - "c": 3, - } AS `dict`, - {1, 2, 3} AS `set` -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/current_tz.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/current_tz.md deleted file mode 100644 index de8054706c22..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/current_tz.md +++ /dev/null @@ -1,78 +0,0 @@ -## CurrentTz... {#current-tz} - -`CurrentTzDate()`, `CurrentTzDatetime()` и `CurrentTzTimestamp()` - получение текущей даты и/или времени в указанной в первом аргументе [IANA временной зоне](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). Тип данных результата указан в конце названия функции. - -### Сигнатуры - -```yql -CurrentTzDate(String, ...)->TzDate -CurrentTzDatetime(String, ...)->TzDatetime -CurrentTzTimestamp(String, ...)->TzTimestamp -``` - -Последующие аргументы опциональны и работают по тому же принципу, что и у [RANDOM](../../basic.md#random). - -### Примеры - -```yql -SELECT CurrentTzDate("Europe/Moscow"); -``` - -```yql -SELECT CurrentTzTimestamp("Europe/Moscow", TableRow()) FROM my_table; -``` - -## AddTimezone - -Добавление информации о временной зоне к дате/времени, заданных в UTC. При выводе в результате `SELECT` или после `CAST` в `String` будут применены правила временной зоны по вычислению смещения времени. - -### Сигнатура - -```yql -AddTimezone(Date, String)->TzDate -AddTimezone(Date?, String)->TzDate? -AddTimezone(Datetime, String)->TzDatetime -AddTimezone(Datetime?, String)->TzDatetime? -AddTimezone(Timestamp, String)->TzTimestamp -AddTimezone(Timestamp?, String)->TzTimestamp? -``` - -Аргументы: - -1. Дата - тип `Date`/`Datetime`/`Timestamp`; -2. [IANA имя временной зоны](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). - -Тип результата - `TzDate`/`TzDatetime`/`TzTimestamp`, в зависимости от типа данных входа. - -### Примеры - -```yql -SELECT AddTimezone(Datetime("2018-02-01T12:00:00Z"), "Europe/Moscow"); -``` - -## RemoveTimezone - -Удаление информации о временной зоне и перевод в дату/время, заданные в UTC. - -### Сигнатура - -```yql -RemoveTimezone(TzDate)->Date -RemoveTimezone(TzDate?)->Date? -RemoveTimezone(TzDatetime)->Datetime -RemoveTimezone(TzDatetime?)->Datetime? -RemoveTimezone(TzTimestamp)->Timestamp -RemoveTimezone(TzTimestamp?)->Timestamp? -``` - -Аргументы: - -1. Дата - тип `TzDate`/`TzDatetime`/`TzTimestamp`. - -Тип результата - `Date`/`Datetime`/`Timestamp`, в зависимости от типа данных входа. - -### Примеры - -```yql -SELECT RemoveTimezone(TzDatetime("2018-02-01T12:00:00,Europe/Moscow")); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/current_utc.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/current_utc.md deleted file mode 100644 index ddb1050b448c..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/current_utc.md +++ /dev/null @@ -1,23 +0,0 @@ -## CurrentUtc... {#current-utc} - -`CurrentUtcDate()`, `CurrentUtcDatetime()` и `CurrentUtcTimestamp()` - получение текущей даты и/или времени в UTC. Тип данных результата указан в конце названия функции. - -### Сигнатуры - -```yql -CurrentUtcDate(...)->Date -CurrentUtcDatetime(...)->Datetime -CurrentUtcTimestamp(...)->Timestamp -``` - -Аргументы опциональны и работают по тому же принципу, что и у [RANDOM](../../basic.md#random). - -### Примеры - -```yql -SELECT CurrentUtcDate(); -``` - -```yql -SELECT CurrentUtcTimestamp(TableRow()) FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/data-type-literals.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/data-type-literals.md deleted file mode 100644 index bcf9523b7698..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/data-type-literals.md +++ /dev/null @@ -1,50 +0,0 @@ -## Литералы простых типов {#data-type-literals} - -Для простых типов могут быть созданы литералы на основании строковых литералов. - -### Синтаксис - -`<Простой тип>( <строка>[, <дополнительные атрибуты>] )` - -В отличие от `CAST("myString" AS MyType)`: - -* Проверка на приводимость литерала к требуемому типу происходит на этапе валидации; -* Результат не является optional. - -Для типов данных `Date`, `Datetime`, `Timestamp` и `Interval` поддерживаются литералы только в формате, соответствующем [ISO 8601](https://ru.wikipedia.org/wiki/ISO_8601). У `Interval` есть следующие отличия от стандарта: - -* поддерживается отрицательный знак для сдвигов в прошлое; -* микросекунды могут быть записаны как дробная часть секунд; -* единицы измерения больше недель не доступны; -* не поддерживаются варианты с началом/концом интервала, а также повторами. - -Для типов данных `TzDate`, `TzDatetime`, `TzTimestamp` литералы также задаются в формате, соответствующем [ISO 8601](https://ru.wikipedia.org/wiki/ISO_8601), но вместо опционального суффикса Z через запятую указывается [IANA имя временной зоны](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones), например, GMT или Europe/Moscow. - -{% include [decimal args](../../../_includes/decimal_args.md) %} - -### Примеры - -```yql -SELECT - Bool("true"), - Uint8("0"), - Int32("-1"), - Uint32("2"), - Int64("-3"), - Uint64("4"), - Float("-5"), - Double("6"), - Decimal("1.23", 5, 2), -- до 5 десятичных знаков, из которых 2 после запятой - String("foo"), - Utf8("привет"), - Yson("[3;%false]"), - Json(@@{"a":1,"b":null}@@), - Date("2017-11-27"), - Datetime("2017-11-27T13:24:00Z"), - Timestamp("2017-11-27T13:24:00.123456Z"), - Interval("P1DT2H3M4.567890S"), - TzDate("2017-11-27,Europe/Moscow"), - TzDatetime("2017-11-27T13:24:00,America/Los_Angeles"), - TzTimestamp("2017-11-27T13:24:00.123456,GMT"), - Uuid("f9d5cc3f-f1dc-4d9c-b97e-766e57ca4ccb"); -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/ensure.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/ensure.md deleted file mode 100644 index 9b415d80df7c..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/ensure.md +++ /dev/null @@ -1,55 +0,0 @@ -## Ensure... {#ensure} - -Проверка пользовательских условий: - -* `Ensure()` — проверка верности предиката во время выполнения запроса. -* `EnsureType()` — проверка точного соответствия типа выражения указанному. -* `EnsureConvertibleTo()` — мягкая проверка соответствия типа выражения, работающая по тем же правилам, что и неявное приведение типов. - -Если проверка не прошла успешно, то весь запрос завершается с ошибкой. - -### Сигнатуры - -```yql -Ensure(T, Bool, String)->T -EnsureType(T, Type, String)->T -EnsureConvertibleTo(T, Type, String)->T -``` - -Аргументы: - -1. Выражение, которое станет результатом вызова функции в случае успеха проверки. Оно же подвергается проверке на тип данных в соответствующих функциях. -2. В Ensure — булевый предикат, который проверяется на `true`. В остальных функциях — тип данных, который может быть получен через [предназначенные для этого функции](../../types.md), либо строковый литерал с [текстовым описанием типа](../../../types/type_string.md). -3. Опциональная строка с комментарием к ошибке, которая попадет в общее сообщение об ошибке при завершении запроса. Для проверок типов не может использовать сами данные, так как они выполняются на этапе валидации запроса, а для Ensure — может быть произвольным выражением. - -{% if backend_name != "YDB" %} - -Для проверки условий по финальному результату вычисления Ensure удобно использовать в сочетании с [DISCARD SELECT](../../../syntax/discard.md). - -{% endif %} - -### Примеры - -```yql -SELECT Ensure( - value, - value < 100, - "value out or range" -) AS value FROM my_table; -``` - -```yql -SELECT EnsureType( - value, - TypeOf(other_value), - "expected value and other_value to be of same type" -) AS value FROM my_table; -``` - -```yql -SELECT EnsureConvertibleTo( - value, - Double?, - "expected value to be numeric" -) AS value FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/enum.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/enum.md deleted file mode 100644 index 17d6037ec6cd..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/enum.md +++ /dev/null @@ -1,44 +0,0 @@ -## Enum {#enum} - -`Enum()` cоздает значение перечисления. - -### Сигнатура - -```yql -Enum(String, Type>)->Enum<...> -``` - -Аргументы: - -* Строка с именем поля -* Тип перечисления - -### Пример - -```yql -$enum_type = Enum; -SELECT - Enum("Foo", $enum_type) as Enum1Value, - Enum("Bar", $enum_type) as Enum2Value; -``` - -## AsEnum {#asenum} - -`AsEnum()` создает значение [перечисления](../../../types/containers.md) с одним элементом. Это значение может быть неявно преобразовано к любому перечислению, содержащему такое имя. - -### Сигнатура - -```yql -AsEnum(String)->Enum<'tag'> -``` - -Аргументы: - -* Строка с именем элемента перечисления - -### Пример - -```yql -SELECT - AsEnum("Foo"); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/evaluate_expr_atom.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/evaluate_expr_atom.md deleted file mode 100644 index d9990bda4166..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/evaluate_expr_atom.md +++ /dev/null @@ -1,31 +0,0 @@ -## EvaluateExpr, EvaluateAtom {#evaluate_expr_atom} - -Возможность выполнить выражение до начала основного расчета и подставить его результат в запрос как литерал (константу). Во многих контекстах, где в стандартном SQL ожидалась бы только константа (например, в именах таблиц, количестве строк в [LIMIT](../../../syntax/select/limit_offset.md) и т.п.) этот функционал активируется неявным образом автоматически. - -EvaluateExpr может использоваться в тех местах, где грамматикой уже ожидается выражение. Например, с его помощью можно: - -* округлить текущее время до дней, недель или месяцев и подставить в запрос, что затем позволит корректно работать [кешированию запросов](../../../syntax/pragma.md#yt.querycachemode), хотя обычно использование [функций для получения текущего времени](../../basic.md#current-utc) его полностью отключает; -* сделать тяжелое вычисление с небольшим результатом один раз на запрос вместо одного раза на каждую джобу. - -{% if backend_name == "YT" %} - -EvaluateAtom позволяет динамически создать [атом](../../../types/special.md), но т.к. ими в основном оперирует более низкий уровень [s-expressions](/docs/s_expressions/functions), то использовать эту функцию напрямую как правило не рекомендуется. - -{% endif %} - -Единственный аргумент у обоих функций — само выражение для вычисления и подстановки. - -Ограничения: - -* выражение не должно приводить к запуску MapReduce операций; -* данный функционал полностью заблокирован в YQL over YDB. - -### Примеры - -```yql -$now = CurrentUtcDate(); -SELECT EvaluateExpr( - DateTime::MakeDate(DateTime::StartOfWeek($now) - ) -); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/files.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/files.md deleted file mode 100644 index df490cc09c0a..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/files.md +++ /dev/null @@ -1,83 +0,0 @@ -## FileContent и FilePath {#file-content-path} - -{% if oss != true %} - -Как [консольный](../../../interfaces/cli.md), так и [веб](../../../interfaces/web.md)-интерфейсы позволяют «прикладывать» к запросу произвольные именованные файлы. С помощью этих функций можно по имени приложенного файла получить его содержимое или путь в «песочнице» и в дальнейшем использовать в запросе произвольным образом. - -{% endif %} - -### Сигнатуры - -```yql -FilePath(String)->String -FileContent(String)->String -``` - -Аргумент `FileContent` и `FilePath` — строка с алиасом. - -### Примеры - -```yql -SELECT "Content of " - || FilePath("my_file.txt") - || ":\n" - || FileContent("my_file.txt"); -``` -## FolderPath {#folderpath} - -Получение пути до корня директории с несколькими «приложенными» файлами с указанным общим префиксом. - -### Сигнатура - -```yql -FolderPath(String)->String -``` - -Аргумент — строка с префиксом среди алиасов. - -Также см. [PRAGMA File](../../../syntax/pragma.md#file) и [PRAGMA Folder](../../../syntax/pragma.md#folder). - -### Примеры - -```yql -PRAGMA File("foo/1.txt", "http://url/to/somewhere"); -PRAGMA File("foo/2.txt", "http://url/to/somewhere/else"); -PRAGMA File("bar/3.txt", "http://url/to/some/other/place"); - -SELECT FolderPath("foo"); -- в директории по возвращённому пути будут - -- находиться файлы 1.txt и 2.txt, скачанные по указанным выше ссылкам -``` - -## ParseFile - -Получить из приложенного текстового файла список значений. Может использоваться в сочетании с [IN](../../../syntax/expressions.md#in) и прикладыванием файла по URL{% if oss != true %} (инструкции по прикладыванию файлов для {% if feature_webui %}[веб-интерфейса](../../../interfaces/web.md#attach) и {% endif %} [клиента](../../../interfaces/cli.md#attach)){% endif %}. - -Поддерживается только один формат файла — по одному значению на строку.{% if feature_udf_noncpp and oss != true %} Для чего-то более сложного прямо сейчас придется написать небольшую UDF на [Python](../../../udf/python.md) или [JavaScript](../../../udf/javascript.md).{% endif %} - -### Сигнатура - -```yql -ParseFile(String, String)->List -``` - -Два обязательных аргумента: - -1. Тип ячейки списка: поддерживаются только строки и числовые типы; -2. Имя приложенного файла. - -{% note info %} - -Возвращаемое значение - ленивый список. Для многократного использования его нужно обернуть в функцию [ListCollect](../../list.md#listcollect) - -{% endnote %} - -### Примеры - -```yql -SELECT ListLength(ParseFile("String", "my_file.txt")); -``` - -```yql -SELECT * FROM my_table -WHERE int_column IN ParseFile("Int64", "my_file.txt"); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/find.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/find.md deleted file mode 100644 index 2b41d529ec22..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/find.md +++ /dev/null @@ -1,75 +0,0 @@ -## FIND {#find} - -Поиск позиции подстроки в строке. - -### Сигнатура - -```yql -Find(String, String[, Uint32?])->Uint32? -Find(String?, String[, Uint32?])->Uint32? -Find(Utf8, Utf8[, Uint32?])->Uint32? -Find(Utf8?, Utf8[, Uint32?])->Uint32? -``` - -Обязательные аргументы: - -* Исходная строка; -* Искомая подстрока. - -Опциональные аргументы: - -* Позиция — в байтах, с которой начинать поиск (целое число, или `NULL` по умолчанию, означающий «от начала исходной строки»). - -Возвращает первую найденную позицию подстроки или `NULL`, означающий что искомая подстрока с указанной позиции не найдена. - -### Примеры - -```yql -SELECT FIND("abcdefg_abcdefg", "abc"); -- 0 -``` - -```yql -SELECT FIND("abcdefg_abcdefg", "abc", 1); -- 8 -``` - -```yql -SELECT FIND("abcdefg_abcdefg", "abc", 9); -- null -``` - -## RFIND {#rfind} - -Обратный поиск позиции подстроки в строке, от конца к началу. - -### Сигнатура - -```yql -RFind(String, String[, Uint32?])->Uint32? -RFind(String?, String[, Uint32?])->Uint32? -RFind(Utf8, Utf8[, Uint32?])->Uint32? -RFind(Utf8?, Utf8[, Uint32?])->Uint32? -``` - -Обязательные аргументы: - -* Исходная строка; -* Искомая подстрока. - -Опциональные аргументы: - -* Позиция — в байтах, с которой начинать поиск (целое число, или `NULL` по умолчанию, означающий «от конца исходной строки»). - -Возвращает первую найденную позицию подстроки или `NULL`, означающий, что искомая подстрока с указанной позиции не найдена. - -### Примеры - -```yql -SELECT RFIND("abcdefg_abcdefg", "bcd"); -- 9 -``` - -```yql -SELECT RFIND("abcdefg_abcdefg", "bcd", 8); -- 1 -``` - -```yql -SELECT RFIND("abcdefg_abcdefg", "bcd", 0); -- null -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/if.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/if.md deleted file mode 100644 index 238569e2f4d2..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/if.md +++ /dev/null @@ -1,23 +0,0 @@ -## IF {#if} - -Проверяет условие `IF(condition_expression, then_expression, else_expression)`. - -Является упрощенной альтернативой для [CASE WHEN ... THEN ... ELSE ... END](../../../syntax/expressions.md#case). - -### Сигнатура - -```yql -IF(Bool, T, T)->T -IF(Bool, T)->T? -``` - -Аргумент `else_expression` можно не указывать. В этом случае, если условие ложно (`condition_expression` вернул `false`), будет возвращено пустое значение с типом, соответствующим `then_expression` и допускающим значение `NULL`. Таким образом, у результата получится [optional тип данных](../../../types/optional.md). - -### Примеры - -```yql -SELECT - IF(foo > 0, bar, baz) AS bar_or_baz, - IF(foo > 0, foo) AS only_positive_foo -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/intro.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/intro.md deleted file mode 100644 index 8a55343d145c..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/intro.md +++ /dev/null @@ -1,3 +0,0 @@ -# Базовые встроенные функции - -Ниже описаны функции общего назначения, а для специализированных функций есть отдельные статьи: [агрегатные](../../aggregation.md){% if feature_window_functions %}, [оконные](../../window.md){% endif %}, а также для работы со [списками](../../list.md), [словарями](../../dict.md), [структурами](../../struct.md), [типами данных](../../types.md){% if feature_codegen %} и [генерацией кода](../../codegen.md){% endif %}. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/length.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/length.md deleted file mode 100644 index 3c34e551db62..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/length.md +++ /dev/null @@ -1,26 +0,0 @@ -## LENGTH {#length} - -Возвращает длину строки в байтах. Также эта функция доступна под именем `LEN`. - -### Сигнатура - -```yql -LENGTH(T)->Uint32 -LENGTH(T?)->Uint32? -``` - -### Примеры - -```yql -SELECT LENGTH("foo"); -``` - -```yql -SELECT LEN("bar"); -``` - -{% note info %} - -Для вычисления длины строки в unicode символах можно воспользоваться функцией [Unicode::GetLength](../../../udf/list/unicode.md).

Для получения числа элементов в списке нужно использовать функцию [ListLength](../../list.md#listlength). - -{% endnote %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/likely.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/likely.md deleted file mode 100644 index baa6e49d4b53..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/likely.md +++ /dev/null @@ -1,20 +0,0 @@ -## Likely {#likely} - -### Сигнатура - -```yql -Likely(Bool)->Bool -Likely(Bool?)->Bool? -``` - -Функция `Likely` возвращает свой аргумент. Функция является подсказкой оптимизатору и говорит о том, что в большинстве случаев ее аргумент будет иметь значение `True`. -Например, наличие такой функции в `WHERE` означает что фильтр является слабоселективным. - -### Пример - -```yql -SELECT * FROM T1 AS a JOIN T2 AS b USING(key) -WHERE Likely(a.amount > 0) -- почти всегда верно -``` - -При наличии `Likely` оптимизатор не будет стараться выполнить фильтрацию перед `JOIN`. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/max_min.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/max_min.md deleted file mode 100644 index c53781ed8444..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/max_min.md +++ /dev/null @@ -1,20 +0,0 @@ -## MAX_OF, MIN_OF, GREATEST и LEAST {#max-min} - -Возвращает минимальный или максимальный среди N аргументов. Эти функции позволяют не использовать стандартную для SQL конструкцию `CASE WHEN a < b THEN a ELSE b END`, которая была бы особенно громоздкой для N больше двух. - -### Сигнатуры - -```yql -MIN_OF(T[,T,...})->T -MAX_OF(T[,T,...})->T -``` - -Типы аргументов должны быть приводимы друг к другу и могут допускать значение `NULL`. - -`GREATEST` является синонимом к `MAX_OF`, а `LEAST` — к `MIN_OF`. - -### Примеры - -```yql -SELECT MIN_OF(1, 2, 3); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/metadata.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/metadata.md deleted file mode 100644 index f8c174110fcd..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/metadata.md +++ /dev/null @@ -1,28 +0,0 @@ -## Доступ к метаданным текущей операции {#metadata} - -При запуске YQL операций через веб-интерфейс или HTTP API, предоставляется доступ к следующей информации: - -* `CurrentOperationId()` — приватный идентификатор операции; -* `CurrentOperationSharedId()` — публичный идентификатор операции; -* `CurrentAuthenticatedUser()` — логин текущего пользователя. - -### Сигнатуры - -```yql -CurrentOperationId()->String -CurrentOperationSharedId()->String -CurrentAuthenticatedUser()->String -``` - -Аргументов нет. - -При отсутствии данной информации, например, при запуске в embedded режиме, возвращают пустую строку. - -### Примеры - -```yql -SELECT - CurrentOperationId(), - CurrentOperationSharedId(), - CurrentAuthenticatedUser(); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/nanvl.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/nanvl.md deleted file mode 100644 index b21206d5c1e0..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/nanvl.md +++ /dev/null @@ -1,25 +0,0 @@ -## NANVL {#nanvl} - -Заменяет значения `NaN` (not a number) в выражениях типа `Float`, `Double` или [Optional](../../../types/optional.md). - -### Сигнатура - -```yql -NANVL(Float, Float)->Float -NANVL(Double, Double)->Double -``` - -Аргументы: - -1. Выражение, в котором нужно произвести замену. -2. Значение, на которое нужно заменить `NaN`. - -Если один из агрументов `Double`, то в выдаче `Double`, иначе `Float`. Если один из агрументов `Optional`, то и в выдаче `Optional`. - -### Примеры - -```yql -SELECT - NANVL(double_column, 0.0) -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/optional_ops.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/optional_ops.md deleted file mode 100644 index b1a64a91633e..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/optional_ops.md +++ /dev/null @@ -1,64 +0,0 @@ -## Just {#optional-ops} - -`Just()` - Изменить тип данных значения на [optional](../../../types/optional.md) от текущего типа данных (то есть `T` превращается в `T?`). - -### Сигнатура - -```yql -Just(T)->T? -``` - -### Примеры - -```yql -SELECT - Just("my_string"); -- String? -``` - -## Unwrap {#unwrap} - -`Unwrap()` - Преобразование значения [optional](../../../types/optional.md) типа данных в соответствующий не-optional тип с ошибкой времени выполнений, если в данных оказался `NULL`. Таким образом, `T?` превращается в `T`. - -Если значение не является [optional](../../../types/optional.md), то функция возвращает свой первый аргумент без изменений. - -### Сигнатура - -```yql -Unwrap(T?)->T -Unwrap(T?, Utf8)->T -Unwrap(T?, String)->T -``` - -Аргументы: - -1. Значение для преобразования; -2. Опциональная строка с комментарием для текста ошибки. - -Обратная операция — [Just](#optional-ops). - -### Примеры - -```yql -$value = Just("value"); - -SELECT Unwrap($value, "Unexpected NULL for $value"); -``` - -## Nothing {#nothing} - -`Nothing()` - Создать пустое значение указанного [Optional](../../../types/optional.md) типа данных. - -### Сигнатура - -```yql -Nothing(Type)->T? -``` - -### Примеры - -```yql -SELECT - Nothing(String?); -- пустое значение (NULL) с типом String? -``` - -[Подробнее о ParseType и других функциях для работы с типами данных](../../types.md). diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/pickle.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/pickle.md deleted file mode 100644 index 815e4f114a09..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/pickle.md +++ /dev/null @@ -1,26 +0,0 @@ -## Pickle, Unpickle {#pickle} - -`Pickle()` и `StablePickle()` сериализуют произвольный объект в последовательность байт, если это возможно. Типовыми несериализуемыми объектами являются Callable и Resource. Формат сериализации не версионируется, допускается использовать в пределах одного запроса. Для типа Dict функция StablePickle предварительно сортирует ключи, а для Pickle порядок элементов словаря в сериализованном представлении не определен. - -`Unpickle()` — обратная операция (десериализация), где первым аргументом передается тип данных результата, а вторым — строка с результатом `Pickle()` или `StablePickle()`. - -### Сигнатуры - -```yql -Pickle(T)->String -StablePickle(T)->String -Unpickle(Type, String)->T -``` - -### Примеры - -```yql -SELECT * -FROM my_table -WHERE Digest::MurMurHash32( - Pickle(TableRow()) - ) % 10 == 0; -- в реальности лучше использовать TABLESAMPLE - -$buf = Pickle(123); -SELECT Unpickle(Int32, $buf); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/random.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/random.md deleted file mode 100644 index 3115137eef9e..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/random.md +++ /dev/null @@ -1,72 +0,0 @@ -## Random... {#random} - -Генерирует псевдослучайное число: - -* `Random()` — число с плавающей точкой (Double) от 0 до 1; -* `RandomNumber()` — целое число из всего диапазона Uint64; -* `RandomUuid()` — [Uuid version 4](https://tools.ietf.org/html/rfc4122#section-4.4). - -### Сигнатуры - -```yql -Random(T1[, T2, ...])->Double -RandomNumber(T1[, T2, ...])->Uint64 -RandomUuid(T1[, T2, ...])->Uuid -``` - -При генерации случайных чисел аргументы не используются и нужны исключительно для управления моментом вызова. В каждый момент вызова возвращается новое случайное число. Поэтому: - -{% if ydb_non_deterministic_functions %} - -* Повторный вызов Random в рамках **одного запроса** при идентичном наборе аргументов не гарантирует получения одинаковых наборов случайных чисел. Значения будут равны, если вызовы Random попадут в одну фазу исполнения. - -{% else %} - -* Повторный вызов Random в рамках **одного запроса** при идентичном наборе аргументов возвращает тот же самый набор случайных чисел. Важно понимать, что речь именно про сами аргументы (текст между круглыми скобками), а не их значения. - -{% endif %} -* Вызовы Random с одним и тем же набором аргументов в **разных запросах** вернут разные наборы случайных чисел. - -{% note warning %} - -Если Random используется в [именованных выражениях](../../../syntax/expressions.md#named-nodes), то его однократное вычисление не гарантируется. В зависимости от оптимизаторов и среды исполнения он может посчитаться как один раз, так и многократно. Для гарантированного однократного подсчета необходимо в этом случае материализовать именованное выражение в таблицу. - -{% endnote %} - -Сценарии использования: - -* `SELECT RANDOM(1);` — получить одно случайное значение на весь запрос и несколько раз его использовать (чтобы получить несколько, можно передать разные константы любого типа); -* `SELECT RANDOM(1) FROM table;` — одно и то же случайное число на каждую строку таблицы; -* `SELECT RANDOM(1), RANDOM(2) FROM table;` — по два случайных числа на каждую строку таблицы, все числа в каждой из колонок одинаковые; -* `SELECT RANDOM(some_column) FROM table;` — разные случайные числа на каждую строку таблицы; -* `SELECT RANDOM(some_column), RANDOM(some_column) FROM table;` — разные случайные числа на каждую строку таблицы, но в рамках одной строки — два одинаковых числа; -* `SELECT RANDOM(some_column), RANDOM(some_column + 1) FROM table;` или `SELECT RANDOM(some_column), RANDOM(other_column) FROM table;` — две колонки, и все с разными числами. - -### Примеры - -```yql -SELECT - Random(key) -- [0, 1) -FROM my_table; -``` - -```yql -SELECT - RandomNumber(key) -- [0, Max) -FROM my_table; -``` - -```yql -SELECT - RandomUuid(key) -- Uuid version 4 -FROM my_table; -``` - -```yql -SELECT - RANDOM(column) AS rand1, - RANDOM(column) AS rand2, -- same as rand1 - RANDOM(column, 1) AS randAnd1, -- different from rand1/2 - RANDOM(column, 2) AS randAnd2 -- different from randAnd1 -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/s_expressions.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/s_expressions.md deleted file mode 100644 index 5c80ef837bf8..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/s_expressions.md +++ /dev/null @@ -1,5 +0,0 @@ -## YQL::, s-expressions {#s-expressions} - -Полный список внутренних функций YQL находится в [документации к s-expressions](/docs/s_expressions/functions), альтернативному низкоуровневому синтаксису YQL. Любую из перечисленных там функций можно вызвать и из SQL синтаксиса, добавив к её имени префикс `YQL::`, но это не рекомендуется делать, т.к. данный механизм предназначен в первую очередь для временного обхода возможных проблем, а также для нужд внутреннего тестирования. - -Если функция доступна в SQL синтаксисе без префикса `YQL::`, то её поведение имеет право отличаться от одноименной функции из документации по s-expressions, если таковая существует. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/starts_ends_with.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/starts_ends_with.md deleted file mode 100644 index 96a0530f2c07..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/starts_ends_with.md +++ /dev/null @@ -1,41 +0,0 @@ -## StartsWith, EndsWith {#starts_ends_with} - -Проверка наличия префикса или суффикса в строке. - -### Сигнатуры - -```yql -StartsWith(T str, U prefix)->Bool[?] - -EndsWith(T str, U suffix)->Bool[?] -``` - -Обязательные аргументы: - -* Исходная строка; -* Искомая подстрока. - -Аргументы должны иметь тип `String`/`Utf8` (или опциональный `String`/`Utf8`) либо строковый PostgreSQL тип (`PgText`/`PgBytea`/`PgVarchar`). -Результатом функции является опциональный Bool, за исключением случая, когда оба аргумента неопциональные – в этом случае возвращается Bool. - -### Примеры - -```yql -SELECT StartsWith("abc_efg", "abc") AND EndsWith("abc_efg", "efg"); -- true -``` - -```yql -SELECT StartsWith("abc_efg", "efg") OR EndsWith("abc_efg", "abc"); -- false -``` - -```yql -SELECT StartsWith("abcd", NULL); -- null -``` - -```yql -SELECT EndsWith(NULL, Utf8("")); -- null -``` - -```yql -SELECT StartsWith("abc_efg"u, "abc"p) AND EndsWith("abc_efg", "efg"pv); -- true -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/staticfold.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/staticfold.md deleted file mode 100644 index 0df756108437..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/staticfold.md +++ /dev/null @@ -1,30 +0,0 @@ -## StaticFold, StaticFold1 {#staticfold} - -```yql -StaticFold(obj:Struct/Tuple, initVal, updateLambda) -StaticFold1(obj:Struct/Tuple, initLambda, updateLambda) -``` - -Статическая левоассоциативная свертка структуры или кортежа. -Для кортежей свертка производится в порядке от меньшего индекса к большему, для структур порядок не гарантируется. - -- `obj` - объект, элементы которого нужно свернуть -- `initVal` - _(для StaticFold)_ исходное состояние свертки -- `initLambda` - _(для StaticFold1)_ функция для получения исходного состояния по первому элементу -- `updateLambda` - функция обновления состояния (принимает в аргументах следующий элемент объекта и предыдущее состояние) - -`StaticFold(<|key_1:$el_1, key_2:$el_2, ..., key_n:$el_n|>, $init, $f)` преобразуется в свертку: - -```yql -$f($el_n, ...$f($el_2, $f($init, el_1))...) -``` - -`StaticFold1(<|key_1:$el_1, key_2:$el_2, ..., key_n:$el_n|>, $f0, $f)`: - -```yql -$f($el_n, ...$f($el_2, $f($f0($init), el_1))...) -``` - -`StaticFold1(<||>, $f0, $f)` вернет `NULL`. - -Аналогично работает и с кортежами. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/staticmap.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/staticmap.md deleted file mode 100644 index ec7e9fa248b0..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/staticmap.md +++ /dev/null @@ -1,31 +0,0 @@ -## StaticMap - -Преобразует структуру или кортеж, применяя лямбду к каждому элементу. - -### Сигнатура - -```yql -StaticMap(Struct<...>, lambda)->Struct<...> -StaticMap(Tuple<...>, lambda)->Tuple<...> -``` - -Аргументы: - -* Структура или кортеж; -* Лямбда для обработки элементов. - -Результат: структура или кортеж с аналогичным первому аргументу количеством и именованием элементов, а типы данных элементов определяются результатами лямбды. - -### Примеры - -```yql -SELECT * -FROM ( - SELECT - StaticMap(TableRow(), ($item) -> { - return CAST($item AS String); - }) - FROM my_table -) FLATTEN COLUMNS; -- преобразование всех колонок в строки -``` - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/staticzip.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/staticzip.md deleted file mode 100644 index d7c03f0aaa37..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/staticzip.md +++ /dev/null @@ -1,22 +0,0 @@ -## StaticZip - -Поэлементно "склеивает" структуры или кортежи. Все аргументы (один и более) должны быть либо структурами с одинаковым набором полей, либо кортежами одинаковой длины. -Результататом будет соответственно структура или кортеж. -Каждый элемент результата – кортеж с соответствующими элементами из аргументов. - -### Сигнатура - -```yql -StaticZip(Struct, Struct)->Struct -StaticZip(Tuple, Tuple)->Tuple -``` - -### Примеры - -```yql -$one = <|k1:1, k2:2.0|>; -$two = <|k1:3.0, k2:4|>; - --- поэлементное сложение двух структур -SELECT StaticMap(StaticZip($one, $two), ($tuple)->($tuple.0 + $tuple.1)) AS sum; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/substring.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/substring.md deleted file mode 100644 index 1788a7b2f48f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/substring.md +++ /dev/null @@ -1,36 +0,0 @@ -## SUBSTRING {#substring} - -Возвращает подстроку. - -### Сигнатура - -```yql -Substring(String[, Uint32? [, Uint32?]])->String -Substring(String?[, Uint32? [, Uint32?]])->String? -``` - -Обязательные аргументы: - -* Исходная строка; -* Позиция — отступ от начала строки в байтах (целое число) или `NULL`, означающий «от начала». - -Опциональные аргументы: - -* Длина подстроки — количество байт, начиная с указанной позиции (целое число, или `NULL` по умолчанию, означающий «до конца исходной строки»). - -Индексация с нуля. Если указанные позиция и длина выходят за пределы строки, возвращает пустую строку. -Если входная строка является опциональной, то таким же является и результат. - -### Примеры - -```yql -SELECT SUBSTRING("abcdefg", 3, 1); -- d -``` - -```yql -SELECT SUBSTRING("abcdefg", 3); -- defg -``` - -```yql -SELECT SUBSTRING("abcdefg", NULL, 3); -- abc -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/table_path_name_recindex.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/table_path_name_recindex.md deleted file mode 100644 index 4eabb5a4791d..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/table_path_name_recindex.md +++ /dev/null @@ -1,76 +0,0 @@ -## TablePath {#tablepath} - -Доступ к текущему имени таблицы, что бывает востребовано при использовании [CONCAT](../../../syntax/select/concat.md), [RANGE](../../../syntax/select/concat.md) и других подобных механизмов. - -### Сигнатура - -```yql -TablePath()->String -``` - -Аргументов нет. Возвращает строку с полным путём, либо пустую строку и warning при использовании в неподдерживаемом контексте (например, при работе с подзапросом или диапазоном из 1000+ таблиц). - -{% note info %} - -Функции [TablePath](#tablepath), [TableName](#tablename) и [TableRecordIndex](#tablerecordindex) не работают для временных и анонимных таблиц (возвращают пустую строку или 0 для [TableRecordIndex](#tablerecordindex)). -Данные функции вычисляются в момент [выполнения](../../../syntax/select/index.md#selectexec) проекции в `SELECT`, и к этому моменту текущая таблица уже может быть временной. -Чтобы избежать такой ситуации, следует поместить вычисление этих функций в подзапрос, как это сделано во втором примере ниже. - -{% endnote %} - -### Примеры - -```yql -SELECT TablePath() FROM CONCAT(table_a, table_b); -``` - -```yql -SELECT key, tpath_ AS path FROM (SELECT a.*, TablePath() AS tpath_ FROM RANGE(`my_folder`) AS a) -WHERE key IN $subquery; -``` - -## TableName {#tablename} - -Получить имя таблицы из пути к таблице. Путь можно получить через функцию [TablePath](#tablepath), или в виде колонки `Path` при использовании табличной функции {% if feature_mapreduce %}[FOLDER](../../../syntax/select/index.md#folder){% else %} `FOLDER`{% endif %}. - -### Сигнатура - -```yql -TableName()->String -TableName(String)->String -TableName(String, String)->String -``` - -Необязательные аргументы: - -* путь к таблице, по умолчанию используется `TablePath()` (также см. его ограничения); -* указание системы ("yt"), по правилам которой выделяется имя таблицы. Указание системы нужно только в том случае, если с помощью {% if feature_mapreduce %}[USE](../../../syntax/use.md){% else %}`USE`{% endif %} не указан текущий кластер. - -### Примеры - -```yql -USE hahn; -SELECT TableName() FROM CONCAT(table_a, table_b); -``` - -```yql -SELECT TableName(Path, "yt") FROM hahn.FOLDER(folder_name); -``` - -## TableRecordIndex {#tablerecordindex} - -Доступ к текущему порядковому номеру строки в исходной физической таблице, **начиная с 1** (зависит от реализации хранения). - -### Сигнатура - -```yql -TableRecordIndex()->Uint64 -``` - -Аргументов нет. При использовании в сочетании с [CONCAT](../../../syntax/select/concat.md), [RANGE](../../../syntax/select/concat.md) и другими подобными механизмами нумерация начинается заново для каждой таблицы на входе. В случае использования в некорректном контексте возвращает 0. - -### Пример - -```yql -SELECT TableRecordIndex() FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/table_row.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/table_row.md deleted file mode 100644 index af5b72ade488..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/table_row.md +++ /dev/null @@ -1,15 +0,0 @@ -## TableRow{% if feature_join %}, JoinTableRow{% endif %} {#tablerow} - -Получение всей строки таблицы целиком в виде структуры. Аргументов нет{% if feature_join %}. `JoinTableRow` в случае `JOIN`-ов всегда возвращает структуру с префиксами таблиц{% endif %}. - -### Сигнатура - -```yql -TableRow()->Struct -``` - -### Пример - -```yql -SELECT TableRow() FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/to_from_bytes.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/to_from_bytes.md deleted file mode 100644 index 73126fcc0af9..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/to_from_bytes.md +++ /dev/null @@ -1,24 +0,0 @@ -## ToBytes и FromBytes {#to-from-bytes} - -Конвертация [простых типов данных](../../../types/primitive.md) в строку со своим бинарным представлением и обратно. Числа представляются в [little endian](https://en.wikipedia.org/wiki/Endianness#Little-endian). - -### Сигнатуры - -```yql -ToBytes(T)->String -ToBytes(T?)->String? - -FromBytes(String, Type)->T? -FromBytes(String?, Type)->T? -``` - -### Примеры - -```yql -SELECT - ToBytes(123), -- "\u0001\u0000\u0000\u0000" - FromBytes( - "\xd2\x02\x96\x49\x00\x00\x00\x00", - Uint64 - ); -- 1234567890ul -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/udf.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/udf.md deleted file mode 100644 index 421d5d791003..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/udf.md +++ /dev/null @@ -1,35 +0,0 @@ -## Udf {#udf} - -Строит `Callable` по заданному названию функции и опциональным `external user types`, `RunConfig` и `TypeConfig`. - -* `Udf(Foo::Bar)` — Функция `Foo::Bar` без дополнительных параметров. -* `Udf(Foo::Bar)(1, 2, 'abc')` — Вызов udf `Foo::Bar`. -* `Udf(Foo::Bar, Int32, @@{"device":"AHCI"}@@ as TypeConfig")(1, 2, 'abc')` — Вызов udf `Foo::Bar` с дополнительным типом `Int32` и указанным `TypeConfig`. -* `Udf(Foo::Bar, "1e9+7" as RunConfig")(1, 'extended' As Precision)` — Вызов udf `Foo::Bar` с указанным `RunConfig` и именоваными параметрами. - -### Сигнатуры - -```yql -Udf(Callable[, T1, T2, ..., T_N][, V1 as TypeConfig][,V2 as RunConfig]])->Callable -``` - -Где `T1`, `T2`, и т. д. -- дополнительные (`external`) пользовательские типы. - -### Примеры - -```yql -$IsoParser = Udf(DateTime2::ParseIso8601); -SELECT $IsoParser("2022-01-01"); -``` - -```yql -SELECT Udf(Unicode::IsUtf)("2022-01-01") -``` - -```yql -$config = @@{ - "name":"MessageFoo", - "meta": "..." -}@@; -SELECT Udf(Protobuf::TryParse, $config As TypeConfig)("") -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/variant.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/variant.md deleted file mode 100644 index 2b28faed2307..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/variant.md +++ /dev/null @@ -1,132 +0,0 @@ -## Variant {#variant} - -`Variant()` создает значение варианта над кортежем или структурой. - -### Сигнатура - -```yql -Variant(T, String, Type>)->Variant<...> -``` - -Аргументы: - -* Значение -* Строка с именем поля или индексом кортежа -* Тип варианта - -### Пример - -```yql -$var_type = Variant; - -SELECT - Variant(6, "foo", $var_type) as Variant1Value, - Variant(false, "bar", $var_type) as Variant2Value; -``` - -## AsVariant {#asvariant} - -`AsVariant()` создает значение [варианта над структурой](../../../types/containers.md) с одним полем. Это значение может быть неявно преобразовано к любому варианту над структурой, в которой совпадает для этого имени поля тип данных и могут быть дополнительные поля с другими именами. - -### Сигнатура - -```yql -AsVariant(T, String)->Variant -``` - -Аргументы: - -* Значение -* Строка с именем поля - -### Пример - -```yql -SELECT - AsVariant(6, "foo") as VariantValue -``` - -## Visit, VisitOrDefault {#visit} - -Обрабатывает возможные значения варианта, представленного структурой или кортежем, с использованием предоставленных функций-обработчиков для каждого из его полей/элементов. - -### Сигнатура - -```yql -Visit(Variant, K1->R AS key1, K2->R AS key2, ...)->R -Visit(Variant, K1->R, K2->R, ...)->R - -VisitOrDefault(Variant{Flags:AutoMap}, R, [K1->R, [K2->R, ...]])->R -VisitOrDefault(Variant{Flags:AutoMap}, R, [K1->R AS key1, [K2->R AS key2, ...]])->R -``` - -### Аргументы - -* Для варианта над структурой функция принимает сам вариант в качестве позиционного аргумента и по одному именованному аргументу-обработчику для каждого поля этой структуры. -* Для варианта над кортежем функция принимает сам вариант и по одному обработчику на каждый элемент кортежа в качестве позиционных аргументов. -* Модификация `VisitOrDefault` принимает дополнительный позиционный аргумент (на втором месте), представляющий значение по умолчанию, и позволяет не указывать некоторые обработчики. - -### Пример - -```yql -$vartype = Variant; -$handle_num = ($x) -> { return 2 * $x; }; -$handle_flag = ($x) -> { return If($x, 200, 10); }; -$handle_str = ($x) -> { return Unwrap(CAST(LENGTH($x) AS Int32)); }; - -$visitor = ($var) -> { return Visit($var, $handle_num AS num, $handle_flag AS flag, $handle_str AS str); }; -SELECT - $visitor(Variant(5, "num", $vartype)), -- 10 - $visitor(Just(Variant(True, "flag", $vartype))), -- Just(200) - $visitor(Just(Variant("somestr", "str", $vartype))), -- Just(7) - $visitor(Nothing(OptionalType($vartype))), -- Nothing(Optional) - $visitor(NULL) -- NULL -; -``` - -## VariantItem {#variantitem} - -Возвращает значение гомогенного варианта (т.е. содержащего поля/элементы одного типа). - -### Сигнатура - -```yql -VariantItem(Variant{Flags:AutoMap})->K -VariantItem(Variant{Flags:AutoMap})->K -``` - -### Пример - -```yql -$vartype1 = Variant; -SELECT - VariantItem(Variant(7, "num2", $vartype1)), -- 7 - VariantItem(Just(Variant(5, "num1", $vartype1))), -- Just(5) - VariantItem(Nothing(OptionalType($vartype1))), -- Nothing(Optional) - VariantItem(NULL) -- NULL -; -``` - -## Way {#way} - -Возвращает активное поле (активный индекс) варианта поверх структуры (кортежа). - -### Сигнатура - -```yql -Way(Variant{Flags:AutoMap})->Utf8 -Way(Variant{Flags:AutoMap})->Uint32 -``` - -### Пример - -```yql -$vr = Variant(1, "0", Variant); -$vrs = Variant(1, "a", Variant); - - -SELECT Way($vr); -- 0 -SELECT Way($vrs); -- "a" - -``` - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/version.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/version.md deleted file mode 100644 index 9f11ee142274..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/version.md +++ /dev/null @@ -1,9 +0,0 @@ -# Version {#version} - -`Version()` возвращает строку, описывающую текущую версию узла, обрабатывающего запрос. В некоторых случаях, например, во время постепенного обновлений кластера, она может возвращать разные строки в зависимости от того, какой узел обрабатывает запрос. Функция не принимает никаких аргументов. - -## Примеры - -```yql -SELECT Version(); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/weakfield.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/weakfield.md deleted file mode 100644 index 831c662ae1e5..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/basic/weakfield.md +++ /dev/null @@ -1,16 +0,0 @@ -## WeakField {#weakfield} - -Вытаскивает колонку таблицы из строгой схемы, если оно там есть, либо из полей `_other` и `_rest`. В случае отсутствия значения возвращается `NULL`. - -Синтаксис: `WeakField([
.], [, ])`. - -Значение по умолчанию используется только в случае отсутствия колонки в схеме данных. Чтобы подставить значение по умолчанию в любом случае можно воспользоваться [COALESCE](#coalesce). - -### Примеры - -```yql -SELECT - WeakField(my_column, String, "no value"), - WeakField(my_table.other_column, Int64) -FROM my_table; -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/index.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/index.md deleted file mode 100644 index 6582d7d04476..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/index.md +++ /dev/null @@ -1,24 +0,0 @@ -# Встроенные функции YQL - -- [Базовые](../basic.md) -- [Агрегатные](../aggregation.md) - -{% if feature_window_functions %} - -- [Оконные](../window.md) - -{% endif %} - -- [Для работы со списками](../list.md) -- [Для работы со словарями](../dict.md) -- [Для работы со структурами](../struct.md) -- [Для работы с типами](../types.md) - -{% if feature_codegen %} - -- [Для работы с генерацией кода](../codegen.md) - -{% endif %} - -- [Для работы с JSON](../json.md) -- [Библиотеки C++](../../udf/list/index.md) diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/aggregate.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/aggregate.md deleted file mode 100644 index 1bc660684e52..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/aggregate.md +++ /dev/null @@ -1,16 +0,0 @@ -## Агрегатные функции {#aggregate-functions} - -Все [агрегатные функции](../../aggregation.md) также могут использоваться в роли оконных. -В этом случае на каждой строке оказывается результат агрегации, полученный на множестве строк из [рамки окна](../../../syntax/window.md#frame). - -### Примеры - -```yql -SELECT - SUM(int_column) OVER w1 AS running_total, - SUM(int_column) OVER w2 AS total, -FROM my_table -WINDOW - w1 AS (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW), - w2 AS (); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/cume_dist.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/cume_dist.md deleted file mode 100644 index cd6a6b5b9f1a..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/cume_dist.md +++ /dev/null @@ -1,19 +0,0 @@ -## CUME_DIST - -Возвращает относительную позицию (> 0 и <= 1) строки в рамках [раздела](../../../syntax/window.md#partition). Без аргументов. - -### Сигнатура - -```yql -CUME_DIST()->Double -``` - -### Примеры - -```yql -SELECT - CUME_DIST() OVER w AS dist -FROM my_table -WINDOW w AS (ORDER BY key); -``` - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/first_last_value.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/first_last_value.md deleted file mode 100644 index 265cabeb54ac..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/first_last_value.md +++ /dev/null @@ -1,28 +0,0 @@ -## FIRST_VALUE / LAST_VALUE - -Доступ к значениям из первой и последней (в порядке `ORDER BY` на окне) строк [рамки окна](../../../syntax/window.md#frame). Единственный аргумент - выражение, к которому необходим доступ. - -Опционально перед `OVER` может указываться дополнительный модификатор `IGNORE NULLS`, который меняет поведение функций на первое или последнее **не пустое** (то есть не `NULL`) значение среди строк рамки окна. Антоним этого модификатора — `RESPECT NULLS` является поведением по умолчанию и может не указываться. - -### Сигнатура - -```yql -FIRST_VALUE(T)->T? -LAST_VALUE(T)->T? -``` - -### Примеры - -```yql -SELECT - FIRST_VALUE(my_column) OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` - -```yql -SELECT - LAST_VALUE(my_column) IGNORE NULLS OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/intro.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/intro.md deleted file mode 100644 index 8da5abdff41d..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/intro.md +++ /dev/null @@ -1,3 +0,0 @@ -# Список оконных функций в YQL - -Синтаксис вызова оконных функций подробно описан в [отдельной статье](../../../syntax/window.md). diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/lag_lead.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/lag_lead.md deleted file mode 100644 index 4fac50af0737..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/lag_lead.md +++ /dev/null @@ -1,44 +0,0 @@ -## LAG / LEAD {#lag-lead} - -Доступ к значению из строки [раздела](../../../syntax/window.md#partition), отстающей (`LAG`) или опережающей (`LEAD`) текущую на фиксированное число. В первом аргументе указывается выражение, к которому необходим доступ, а во втором — отступ в строках. Отступ можно не указывать, по умолчанию используется соседняя строка — предыдущая или следующая, соответственно, то есть подразумевается 1. В строках, для которых нет соседей с заданным расстоянием (например `LAG(expr, 3)` в первой и второй строках раздела), возвращается `NULL`. - -### Сигнатура - -```yql -LEAD(T[,Int32])->T? -LAG(T[,Int32])->T? -``` - -### Примеры - -```yql -SELECT - int_value - LAG(int_value) OVER w AS int_value_diff -FROM my_table -WINDOW w AS (ORDER BY key); -``` - -```yql -SELECT item, odd, LAG(item, 1) OVER w as lag1 FROM ( - SELECT item, item % 2 as odd FROM ( - SELECT AsList(1, 2, 3, 4, 5, 6, 7) as item - ) - FLATTEN BY item -) -WINDOW w As ( - PARTITION BY odd - ORDER BY item -); - -/* Output: -item odd lag1 --------------------- -2 0 NULL -4 0 2 -6 0 4 -1 1 NULL -3 1 1 -5 1 3 -7 1 5 -*/ -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/nth_value.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/nth_value.md deleted file mode 100644 index ceaee264baa6..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/nth_value.md +++ /dev/null @@ -1,27 +0,0 @@ -## NTH_VALUE - -Доступ к значения из заданной строки (в порядке `ORDER BY` на окне) [рамки окна](../../../syntax/window.md#frame). Аргументы - выражение, к которому необходим доступ и номер строки, начиная с 1. - -Опционально перед `OVER` может указываться дополнительный модификатор `IGNORE NULLS`, который приводит к пропуску строк с NULL в значении первого аргумента. Антоним этого модификатора — `RESPECT NULLS` является поведением по умолчанию и может не указываться. - -### Сигнатура - -```yql -NTH_VALUE(T,N)->T? -``` - -### Примеры - -```yql -SELECT - NTH_VALUE(my_column, 2) OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` - -```yql -SELECT - NTH_VALUE(my_column, 3) IGNORE NULLS OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/ntile.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/ntile.md deleted file mode 100644 index ee252618ace5..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/ntile.md +++ /dev/null @@ -1,18 +0,0 @@ -## NTILE - -Распределяет строки упорядоченного [раздела](../../../syntax/window.md#partition) в заданное количество групп. Группы нумеруются, начиная с единицы. Для каждой строки функция NTILE возвращает номер группы,которой принадлежит строка. - -### Сигнатура - -```yql -NTILE(Uint64)->Uint64 -``` - -### Примеры - -```yql -SELECT - NTILE(10) OVER w AS group_num -FROM my_table -WINDOW w AS (ORDER BY key); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/rank_dense.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/rank_dense.md deleted file mode 100644 index b42ef08c074b..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/rank_dense.md +++ /dev/null @@ -1,43 +0,0 @@ -## RANK / DENSE_RANK / PERCENT_RANK {#rank} - -Пронумеровать группы соседних строк [раздела](../../../syntax/window.md#partition) с одинаковым значением выражения в аргументе. `DENSE_RANK` нумерует группы подряд, а `RANK` — пропускает `(N - 1)` значений, где `N` — число строк в предыдущей группе. `PERCENT_RANK` выдает относительный ранг текущей строки: `(RANK - 1)/(число строк в разделе - 1)`. - -При отсутствии аргумента использует порядок, указанный в секции `ORDER BY` определения окна. -Если аргумент отсутствует и `ORDER BY` не указан, то все строки считаются равными друг другу. - -{% note info %} - -Возможность передавать аргумент в `RANK`/`DENSE_RANK`/`PERCENT_RANK` является нестандартным расширением YQL. - -{% endnote %} - -### Сигнатура - -```yql -RANK([T])->Uint64 -DENSE_RANK([T])->Uint64 -PERCENT_RANK([T])->Double -``` - -### Примеры - -```yql -SELECT - RANK(my_column) OVER w -FROM my_table -WINDOW w AS (ORDER BY key); -``` - -```yql -SELECT - DENSE_RANK() OVER w -FROM my_table -WINDOW w AS (ORDER BY my_column); -``` - -```yql -SELECT - PERCENT_RANK() OVER w -FROM my_table -WINDOW w AS (ORDER BY my_column); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/row_number.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/row_number.md deleted file mode 100644 index dff41b82b4b0..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/row_number.md +++ /dev/null @@ -1,18 +0,0 @@ -## ROW_NUMBER {#row_number} - -Номер строки в рамках [раздела](../../../syntax/window.md#partition). Без аргументов. - -### Сигнатура - -```yql -ROW_NUMBER()->Uint64 -``` - -### Примеры - -```yql -SELECT - ROW_NUMBER() OVER w AS row_num -FROM my_table -WINDOW w AS (ORDER BY key); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/session_state.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/session_state.md deleted file mode 100644 index 9857f7a1941c..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/_includes/window/session_state.md +++ /dev/null @@ -1,5 +0,0 @@ -## SessionState() {#session-state} - -Нестандартная оконная функция `SessionState()` (без аргументов) позволяет получить состояние расчета сессий из [SessionWindow](../../../syntax/group_by.md#session-window) для текущей строки. - -Допускается только при наличии `SessionWindow()` в секции `PARTITION BY` определения окна. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/aggregation.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/aggregation.md deleted file mode 100644 index 6ed01e757c33..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/aggregation.md +++ /dev/null @@ -1,31 +0,0 @@ -# Агрегатные функции - -{% include [simple.md](_includes/aggregation/simple.md) %} - -{% include [count_distinct_estimate.md](_includes/aggregation/count_distinct_estimate.md) %} - -{% include [agg_list.md](_includes/aggregation/agg_list.md) %} - -{% include [max_min_by.md](_includes/aggregation/max_min_by.md) %} - -{% include [top_bottom.md](_includes/aggregation/top_bottom.md) %} - -{% include [topfreq_mode.md](_includes/aggregation/topfreq_mode.md) %} - -{% include [stddev_variance.md](_includes/aggregation/stddev_variance.md) %} - -{% include [corr_covar.md](_includes/aggregation/corr_covar.md) %} - -{% include [percentile_median.md](_includes/aggregation/percentile_median.md) %} - -{% include [histogram.md](_includes/aggregation/histogram.md) %} - -{% include [bool_bit.md](_includes/aggregation/bool_bit.md) %} - -{% if feature_window_functions %} - - {% include [session_start.md](_includes/aggregation/session_start.md) %} - -{% endif %} - -{% include [aggregate_by.md](_includes/aggregation/aggregate_by.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/basic.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/basic.md deleted file mode 100644 index 000082e89249..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/basic.md +++ /dev/null @@ -1,102 +0,0 @@ - -{% include [x](_includes/basic/intro.md) %} - -{% include [x](_includes/basic/coalesce.md) %} - -{% include [x](_includes/basic/length.md) %} - -{% include [x](_includes/basic/substring.md) %} - -{% include [x](_includes/basic/find.md) %} - -{% include [x](_includes/basic/starts_ends_with.md) %} - -{% include [x](_includes/basic/if.md) %} - -{% include [x](_includes/basic/nanvl.md) %} - -{% include [x](_includes/basic/random.md) %} - -{% include [x](_includes/basic/udf.md) %} - -{% include [x](_includes/basic/current_utc.md) %} - -{% include [x](_includes/basic/current_tz.md) %} - -{% include [x](_includes/basic/version.md) %} - -{% include [x](_includes/basic/max_min.md) %} - -{% include [x](_includes/basic/as_container.md) %} - -{% include [x](_includes/basic/container_literal.md) %} - -{% include [x](_includes/basic/variant.md) %} - -{% include [x](_includes/basic/enum.md) %} - -{% include [x](_includes/basic/as_tagged.md) %} - -{% if feature_bulk_tables %} - - {% include [x](_includes/basic/table_path_name_recindex.md) %} - -{% endif %} - -{% include [x](_includes/basic/table_row.md) %} - -{% if feature_mapreduce %} - - {% include [x](_includes/basic/files.md) %} - - {% include [x](_includes/basic/weakfield.md) %} - -{% endif %} - -{% include [x](_includes/basic/ensure.md) %} - -{% include [x](_includes/basic/assume_strict.md) %} - -{% include [x](_includes/basic/likely.md) %} - -{% if feature_codegen %} - - {% include [x](_includes/basic/evaluate_expr_atom.md) %} - -{% endif %} - -{% include [x](_includes/basic/data-type-literals.md) %} - -{% if feature_webui %} - - {% include [x](_includes/basic/metadata.md) %} - -{% endif %} - -{% include [x](_includes/basic/to_from_bytes.md) %} - -{% include [x](_includes/basic/byteat.md) %} - -{% include [x](_includes/basic/bitops.md) %} - -{% include [x](_includes/basic/abs.md) %} - -{% include [x](_includes/basic/optional_ops.md) %} - -{% include [x](_includes/basic/callable.md) %} - -{% include [x](_includes/basic/pickle.md) %} - -{% include [x](_includes/basic/staticmap.md) %} - -{% include [x](_includes/basic/staticzip.md) %} - -{% include [x](_includes/basic/staticfold.md) %} - -{% include [x](_includes/basic/aggr_factory.md) %} - -{% if tech %} - - {% include [x](_includes/basic/s_expressions.md) %} - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/codegen.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/codegen.md deleted file mode 100644 index bc3bca2b116d..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/codegen.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [codegen.md](_includes/codegen.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/dict.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/dict.md deleted file mode 100644 index 24267d59a418..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/dict.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [dict.md](_includes/dict.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/index.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/index.md deleted file mode 100644 index b3cf50bcae96..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/index.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [index.md](_includes/index.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/json.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/json.md deleted file mode 100644 index 4b454b1b6349..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/json.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [json.md](_includes/json.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/list.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/list.md deleted file mode 100644 index 44351e21def7..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/list.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/list.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/struct.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/struct.md deleted file mode 100644 index 418289d25303..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/struct.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/struct.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/types.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/types.md deleted file mode 100644 index 962e7b5fe24f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/types.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/types.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/builtins/window.md b/ydb/docs/ru/core/yql/reference/yql-core/builtins/window.md deleted file mode 100644 index c8b573e257be..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/builtins/window.md +++ /dev/null @@ -1,20 +0,0 @@ - -{% include [x](_includes/window/intro.md) %} - -{% include [x](_includes/window/aggregate.md) %} - -{% include [x](_includes/window/row_number.md) %} - -{% include [x](_includes/window/lag_lead.md) %} - -{% include [x](_includes/window/first_last_value.md) %} - -{% include [x](_includes/window/nth_value.md) %} - -{% include [x](_includes/window/rank_dense.md) %} - -{% include [x](_includes/window/ntile.md) %} - -{% include [x](_includes/window/cume_dist.md) %} - -{% include [x](_includes/window/session_state.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/Readme.txt b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/Readme.txt deleted file mode 100644 index 1abfe7c04f69..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/Readme.txt +++ /dev/null @@ -1 +0,0 @@ -Files inside this folder represent YQL base blocks, and may NOT contain product-conditional or corporate content. \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/action/begin.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/action/begin.md deleted file mode 100644 index 783ef38c184a..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/action/begin.md +++ /dev/null @@ -1,20 +0,0 @@ -## BEGIN .. END DO {#begin} - -Выполнение действия без его объявления (анонимное действие). - -### Синтаксис - -1. `BEGIN`; -1. Список выражений верхнего уровня; -1. `END DO`. - -Анонимное действие не может содержать параметров. - -### Пример - -```yql -DO BEGIN - SELECT 1; - SELECT 2 -- здесь и в предыдущем примере ';' перед END можно не ставить -END DO -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/action/define_do.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/action/define_do.md deleted file mode 100644 index 1fc79a0e8b59..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/action/define_do.md +++ /dev/null @@ -1,51 +0,0 @@ -## DEFINE ACTION {#define-action} - -Задает именованное действие, которое представляют собой параметризуемый блок из нескольких выражений верхнего уровня. - -### Синтаксис - -1. `DEFINE ACTION` — объявление действия. -1. [Имя действия](../../expressions.md#named-nodes), по которому объявляемое действие доступно далее для вызова. -1. В круглых скобках — список имен параметров. -1. Ключевое слово `AS`. -1. Список выражений верхнего уровня. -1. `END DEFINE` — маркер последнего выражения внутри действия. - -Один или более последних параметров могут быть помечены знаком вопроса `?` как необязательные. Если они не будут указаны при вызове, то им будет присвоено значение `NULL`. - -## DO {#do} - -Выполняет `ACTION` с указанными параметрами. - -### Синтаксис - -1. `DO` — выполнение действия. -1. Именованное выражение, по которому объявлено действие. -1. В круглых скобках — список значений для использования в роли параметров. - -`EMPTY_ACTION` — действие, которое ничего не выполняет. - -{% if feature_mapreduce %} - -{% note info %} - -В больших запросах объявление действий можно выносить в отдельные файлы и подключать их в основной запрос с помощью [EXPORT](../../export_import.md#export) + [IMPORT](../../export_import.md#import), чтобы вместо одного длинного текста получилось несколько логических частей, в которых проще ориентироваться. Важный нюанс: директива `USE my_cluster;` в импортирующем запросе не влияет на поведение объявленных в других файлах действий. - -{% endnote %} - -{% endif %} - -### Пример - -```yql -DEFINE ACTION $hello_world($name, $suffix?) AS - $name = $name ?? ($suffix ?? "world"); - SELECT "Hello, " || $name || "!"; -END DEFINE; - -DO EMPTY_ACTION(); -DO $hello_world(NULL); -DO $hello_world("John"); -DO $hello_world(NULL, "Earth"); -``` - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/action/evaluate.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/action/evaluate.md deleted file mode 100644 index f19a932b003f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/action/evaluate.md +++ /dev/null @@ -1,75 +0,0 @@ -## EVALUATE IF {#evaluate-if} - -`EVALUATE IF` — выполнение действия (action) в зависимости от выполнения условия. Далее указывается: - -1. Условие; -2. [DO](#do) с именем и параметрами действия или анонимным действием; -3. Опционально `ELSE` и следом второе `DO` для ситуации, когда условие не выполнено. - -## EVALUATE FOR {#evaluate-for} - -`EVALUATE FOR` — выполнение действия (action) для каждого элемента в списке. Далее указывается: - -1. [Именованное выражение](../../expressions.md#named-nodes), в которое будет подставляться каждый очередной элемент списка; -2. Ключевое слово `IN`; -3. Объявленное выше именованное выражение со списком, по которому будет выполняться действие. -4. [DO](#do) с именем и параметрами действия или анонимным действием, в параметрах можно использовать как текущий элемент из первого пункта, так и любые объявленные выше именованные выражения, в том числе сам список. -5. Опционально `ELSE` и следом второе `DO` для ситуации, когда список пуст. - -### Примеры - -```yql -DEFINE ACTION $hello() AS - SELECT "Hello!"; -END DEFINE; - -DEFINE ACTION $bye() AS - SELECT "Bye!"; -END DEFINE; - -EVALUATE IF RANDOM(0) > 0.5 - DO $hello() -ELSE - DO $bye(); - -EVALUATE IF RANDOM(0) > 0.1 DO BEGIN - SELECT "Hello!"; -END DO; - -EVALUATE FOR $i IN AsList(1, 2, 3) DO BEGIN - SELECT $i; -END DO; -``` - -```yql --- скопировать таблицу $input в $count новых таблиц -$count = 3; -$input = "my_input"; -$inputs = ListReplicate($input, $count); -$outputs = ListMap( - ListFromRange(0, $count), - ($i) -> { - RETURN "tmp/out_" || CAST($i as String) - } -); -$pairs = ListZip($inputs, $outputs); - -DEFINE ACTION $copy_table($pair) as - $input = $pair.0; - $output = $pair.1; - INSERT INTO $output WITH TRUNCATE - SELECT * FROM $input; -END DEFINE; - -EVALUATE FOR $pair IN $pairs - DO $copy_table($pair) -ELSE - DO EMPTY_ACTION(); -- такой ELSE можно было не указывать, - -- ничего не делать подразумевается по умолчанию -``` - -{% note info %} - -Стоит учитывать, что `EVALUATE` выполняется до начала работы основного запроса. Также в рамках вычисления предиката в `EVALUATE IF` или списка в `EVALUATE FOR` невозможно использование {% if feature_temp_table %}[анонимных таблиц](../../select/temporary_table.md){% else %} анонимных таблиц{% endif %}. - -{% endnote %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md deleted file mode 100644 index 8b4e00316ddd..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/create_table.md +++ /dev/null @@ -1,307 +0,0 @@ -# CREATE TABLE - -{% if feature_olap_tables %} - -{{ ydb-short-name }} поддерживает два типа таблиц: - -* [строковые](../../../../concepts/datamodel/table.md); -* [колоночные](../../../../concepts/datamodel/table.md#column-tables). - -Тип таблицы при создании задается параметром `STORE`, где `ROW` означает [строковую таблицу](#row), а `COLUMN` — [колоночную](#olap-tables). По умолчанию, если параметр `STORE` не указан, создается строковая таблица. - -{%endif%} - -{% if feature_olap_tables %} - -## Строковые таблицы {#row} - -{%endif%} - -{% if feature_bulk_tables %} - -Таблица создается автоматически при первом [INSERT INTO](insert_into.md){% if feature_mapreduce %}, в заданной оператором [USE](../use.md) базе данных{% endif %}. Схема при этом определяется автоматически. - -{% else %} - -Вызов `CREATE TABLE` создает {% if concept_table %}[таблицу]({{ concept_table }}){% else %}таблицу{% endif %} с указанной схемой данных{% if feature_map_tables %} и ключевыми колонками (`PRIMARY KEY`){% endif %}. {% if feature_secondary_index == true %}Позволяет определить вторичные индексы на создаваемой таблице.{% endif %} - - CREATE [TEMP | TEMPORARY] TABLE table_name ( - column1 type1, -{% if feature_not_null == true %} column2 type2 NOT NULL,{% else %} column2 type2,{% endif %} - ... - columnN typeN, -{% if feature_secondary_index == true %} - INDEX index1_name GLOBAL ON ( column ), - INDEX index2_name GLOBAL ON ( column1, column2, ... ), -{% endif %} -{% if feature_map_tables %} - PRIMARY KEY ( column, ... ), - FAMILY column_family ( family_options, ... ) -{% else %} - ... -{% endif %} - ) -{% if feature_map_tables %} - WITH ( key = value, ... ) -{% endif %} - -{% if feature_olap_tables %}#{%endif%}## Колонки {#row-columns} - -{% if feature_column_container_type == true %} - -Для неключевых колонок допускаются любые типы данных, для ключевых - только [примитивные](../../types/primitive.md). При указании сложных типов (например, `List`) тип заключается в двойные кавычки. - -{% else %} - -Для ключевых и неключевых колонок допускаются только [примитивные](../../types/primitive.md) типы данных. - -{% endif %} - -{% if feature_not_null == true %} - -Без дополнительных модификаторов колонка приобретает [опциональный тип](../../types/optional.md) тип, и допускает запись `NULL` в качестве значений. Для получения неопционального типа необходимо использовать `NOT NULL`. - -{% else %} - -{% if feature_not_null_for_pk %} - -По умолчанию все колонки [опциональные](../../types/optional.md) и могут иметь значение NULL. Ограничение `NOT NULL` можно указать только для колонок, входящих в первичный ключ. - -{% else %} - -Все колонки допускают запись `NULL` в качестве значений, то есть являются [опциональными](../../types/optional.md). - -{% endif %} - -{% endif %} - -{% if feature_map_tables %} - -Обязательно указание `PRIMARY KEY` с непустым списком колонок. Эти колонки становятся частью ключа в порядке перечисления. - -{% endif %} - -### Пример - - CREATE TABLE my_table ( -{% if feature_not_null_for_pk %} a Uint64 NOT NULL,{% else %} a Uint64,{% endif %} - b Bool, -{% if feature_not_null %} c Float NOT NULL,{% else %} c Float,{% endif %} -{% if feature_column_container_type %} d "List>"{% endif %} -{% if feature_map_tables %} - PRIMARY KEY (b, a) -{% endif %} - ) - -{% if feature_secondary_index %} - -{% if feature_olap_tables %}#{%endif%}## Вторичные индексы {#secondary_index} - -Конструкция INDEX используется для определения {% if concept_secondary_index %}[вторичного индекса]({{ concept_secondary_index }}){% else %}вторичного индекса{% endif %} на таблице: - -```yql -CREATE TABLE table_name ( - ... - INDEX GLOBAL [UNIQUE] [SYNC|ASYNC] ON ( ) COVER ( ) - ... -) -``` - -где: - -* **index_name** — уникальное имя индекса, по которому будет возможно обращение к данным. -* **SYNC/ASYNC** — синхронная или асинхронная запись в индекс, если не указано — синхронная. -* **UNIQUE** — создаёт индекс с гарантией уникальности для вставляемых значений. -* **index_columns** — имена колонок создаваемой таблицы через запятую, по которым возможен поиск в индексе. -* **cover_columns** — имена колонок создаваемой таблицы через запятую, которые будет сохранены в индексе дополнительно к колонкам поиска, давая возможность получить дополнительные данные без обращения за ними в таблицу. - -### Пример - -```yql -CREATE TABLE my_table ( - a Uint64, - b Bool, - c Utf8, - d Date, - INDEX idx_d GLOBAL ON (d), - INDEX idx_ba GLOBAL ASYNC ON (b, a) COVER (c), - INDEX idx_bc GLOBAL UNIQUE SYNC ON (b, c), - PRIMARY KEY (a) -) -``` - -{% endif %} - -{% if feature_temp_tables %} - -{% if feature_olap_tables %}#{%endif%}## Создание временных таблиц {#temporary_tables} - -```yql -CREATE TEMPORARY TABLE table_name ( - ... -); -``` - -{% include [temp-table-description.md](../../../../_includes/temp-table-description.md) %} - -{% endif %} - -{% if feature_map_tables and concept_table %} - -{% if feature_olap_tables %}#{%endif%}## Дополнительные параметры {#row-additional} - -Для таблицы может быть указан ряд специфичных для {{ backend_name }} параметров. При создании таблицы такие параметры перечисляются в блоке `WITH`: - -```yql -CREATE TABLE table_name (...) -WITH ( - key1 = value1, - key2 = value2, - ... -) -``` - -Здесь key — это название параметра, а value — его значение. - -Перечень допустимых имен параметров и их значений приведен на странице [описания таблицы {{ backend_name }}]({{ concept_table }}). - -Например, такой код создаст таблицу с включенным автоматическим партиционированием по размеру партиции и предпочитаемым размером каждой партиции 512 мегабайт: - -```yql -CREATE TABLE my_table ( - id Uint64, - title Utf8, - PRIMARY KEY (id) -) -WITH ( - AUTO_PARTITIONING_BY_SIZE = ENABLED, - AUTO_PARTITIONING_PARTITION_SIZE_MB = 512 -); -``` - -{% if feature_olap_tables %}#{%endif%}## Группы колонок {#column-family} - -Колонки одной таблицы можно объединять в группы, для того чтобы задать следующие параметры: - -* `DATA` — тип устройства хранения для данных колонок этой группы. Допустимые значения: `"ssd"`, `"rot"`. -* `COMPRESSION` — кодек сжатия данных. Допустимые значения: `"off"`, `"lz4"`. - -По умолчанию все колонки находятся в одной группе с именем `default`. При желании, параметры этой группы тоже можно переопределить. - -В примере ниже для создаваемой таблицы добавляется группа колонок `family_large` и устанавливается для колонки `series_info`, а также переопределяются параметры для группы `default`, которая по умолчанию установлена для всех остальных колонок. - -```yql -CREATE TABLE series_with_families ( - series_id Uint64, - title Utf8, - series_info Utf8 FAMILY family_large, - release_date Uint64, - PRIMARY KEY (series_id), - FAMILY default ( - DATA = "ssd", - COMPRESSION = "off" - ), - FAMILY family_large ( - DATA = "rot", - COMPRESSION = "lz4" - ) -); -``` - -{% note info %} - -Доступные типы устройств хранения зависят от конфигурации кластера {{ ydb-short-name }}. - -{% endnote %} - -{% endif %} - -{% endif %} - -{% if feature_olap_tables %} - -## Колоночные таблицы {#olap-tables} - -{% note warning %} - -Колоночные таблицы {{ ydb-short-name }} доступны в режиме Preview. - -{% endnote %} - -Вызов `CREATE TABLE` создает [колоночную таблицу](../../../../concepts/datamodel/table.md#column-tables) с указанной схемой данных и ключевыми колонками (`PRIMARY KEY`). - -```yql -CREATE TABLE table_name ( - column1 type1, - column2 type2 NOT NULL, - column2 type2, - ... - columnN typeN, - PRIMARY KEY ( column, ... ), - ... -) -PARTITION BY HASH(column1, column2, ...) -WITH ( - STORE = COLUMN, - key = value, - ... -) -``` - -### Колонки {#olap-columns} - -Поддерживаемые типы данных в колоночных таблицах и ограничение на использование типов в первичных ключах или колонках данных описаны в разделе [колоночные таблицы](../../../../concepts/datamodel/table.md#column-tables). - -Обязательно указание `PRIMARY KEY` и `PARTITION BY` с непустым списком колонок. - -Без дополнительных модификаторов колонка приобретает [опциональный](../../types/optional.md) тип и допускает запись `NULL` в качестве значений. Для получения неопционального типа необходимо использовать `NOT NULL`. - -#### Пример - -```yql -CREATE TABLE my_table ( - a Uint64 NOT NULL, - b String, - c Float, - PRIMARY KEY (b, a) -) -PARTITION BY HASH(b) -WITH ( -STORE = COLUMN -) -``` - -### Дополнительные параметры {#olap-additional} - -Для таблицы может быть указан ряд специфичных для {{ backend_name }} параметров. При создании таблицы такие параметры перечисляются в блоке `WITH`: - -```yql -CREATE TABLE table_name (...) -WITH ( - key1 = value1, - key2 = value2, - ... -) -``` - -Здесь `key` — это название параметра, а `value` — его значение. - -Поддерживаемые параметры колоночных таблиц: - -* `AUTO_PARTITIONING_MIN_PARTITIONS_COUNT` — определяет минимальное физическое количество партиций для хранения данных (см. [{#T}](../../../../concepts/datamodel/table.md#olap-tables-partitioning)). - -Например, следующий код создает колоночную таблицу с 10-ю партициями: - -```yql -CREATE TABLE my_table ( - id Uint64, - title Utf8, - PRIMARY KEY (id) -) -PARTITION BY HASH(id) -WITH ( - AUTO_PARTITIONING_MIN_PARTITIONS_COUNT = 10 -); -``` - -{%endif%} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/discard.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/discard.md deleted file mode 100644 index 754456b7606c..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/discard.md +++ /dev/null @@ -1,31 +0,0 @@ -# DISCARD - -Вычисляет {% if select_command == "SELECT STREAM" %}[`SELECT STREAM`](../select_stream.md){% else %}[`SELECT`](../select/index.md){% endif %}{% if feature_mapreduce %}{% if reduce_command %}, [`{{ reduce_command }}`](../reduce.md){% endif %} или [`{{ process_command }}`](../process.md){% endif %}, но не возвращает результат ни в клиент, ни в таблицу. {% if feature_mapreduce %}Не может быть задано одновременно с [INTO RESULT](../into_result.md).{% endif %} - -Полезно использовать в сочетании с [`Ensure`](../../builtins/basic.md#ensure) для проверки выполнения пользовательских условий на финальный результат вычислений. - -{% if select_command != true or select_command == "SELECT" %} - -### Примеры - -```yql -DISCARD SELECT 1; -``` - -```yql -INSERT INTO result_table WITH TRUNCATE -SELECT * FROM -my_table -WHERE value % 2 == 0; - -COMMIT; - -DISCARD SELECT Ensure( - 0, -- will discard result anyway - COUNT(*) > 1000, - "Too small result table, got only " || CAST(COUNT(*) AS String) || " rows" -) FROM result_table; - -``` - -{% endif %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/as.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/as.md deleted file mode 100644 index f0f369b09268..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/as.md +++ /dev/null @@ -1,42 +0,0 @@ -## AS {#as} - -Может использоваться в следующих сценариях: - -* Присвоение короткого имени (алиаса) столбцам или таблицам в рамках запроса. -* Указание именованных аргументов при вызове функций. -* При явном приведении типов данных для указания целевого типа, см. [CAST](../../../syntax/expressions.md#cast). - -### Примеры - -{% if select_command != "SELECT STREAM" %} - -```yql -SELECT key AS k FROM my_table; -``` - -```yql -SELECT t.key FROM my_table AS t; -``` - -```yql -SELECT - MyFunction(key, 123 AS my_optional_arg) -FROM my_table; -``` -{% else %} - -```yql -SELECT STREAM key AS k FROM my_stream; -``` - -```yql -SELECT STREAM s.key FROM my_stream AS s; -``` - -```yql -SELECT STREAM - MyFunction(key, 123 AS my_optional_arg) -FROM my_stream; -``` - -{% endif %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/between.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/between.md deleted file mode 100644 index d4fd86294b66..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/between.md +++ /dev/null @@ -1,20 +0,0 @@ -## BETWEEN {#between} - -Проверка на вхождение значения в диапазон. Cинтаксис: `expr [NOT] BETWEEN [ASYMMETRIC | SYMMETRIC] expr AND expr`. - -* `BETWEEN` и `BETWEEN ASYMMETRIC` эквивалентны, `x BETWEEN a AND b` эквивалентно `a <= x AND x <= b`. -* `BETWEEN SYMMETRIC` автоматически переставляет аргументы местами так чтобы диапазон получился непустым, -`x BETWEEN SYMMETRIC a AND b` эквивалентно `(x BETWEEN a AND b) OR (x BETWEEN b AND a)`. -* `NOT` инвертирует результат проверки. - -### Примеры - -```yql -SELECT * FROM my_table -WHERE key BETWEEN 10 AND 20; -``` - -```yql -SELECT * FROM my_table -WHERE key NOT BETWEEN SYMMETRIC 20 AND 10; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/bitcast.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/bitcast.md deleted file mode 100644 index 183a33586162..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/bitcast.md +++ /dev/null @@ -1,14 +0,0 @@ -## BITCAST {#bitcast} - -Выполняет побитное преобразование целочисленного значения к указанному целочисленному типу. Преобразование всегда успешно, но может потерять точность или старшие биты. - -### Примеры - -```yql -SELECT - BITCAST(100000ul AS Uint32), -- 100000 - BITCAST(100000ul AS Int16), -- -31072 - BITCAST(100000ul AS Uint16), -- 34464 - BITCAST(-1 AS Int16), -- -1 - BITCAST(-1 AS Uint16); -- 65535 -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/case.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/case.md deleted file mode 100644 index 3ff9da9ee282..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/case.md +++ /dev/null @@ -1,32 +0,0 @@ -## CASE {#case} - -Условные выражения и ветвление. Аналог `if`, `switch` и тернарных операторов в императивных языках программирования. -Если результатом выражения `WHEN` оказывается `true`, значением выражения `CASE` становится результат, -следующий за условием, а остальная часть выражения `CASE` не вычисляется. Если же условие не выполняется, -за ним таким же образом проверяются все последующие предложения `WHEN`. Если не выполняется -ни одно из условий `WHEN`, значением `CASE` становится результат, записанный в предложении `ELSE`. -Ветка `ELSE` является обязательной в выражении `CASE`. Выражения в `WHEN` проверяются последовательно, сверху вниз. - -Так как синтаксис достаточно громоздкий, зачастую удобнее пользоваться встроенной функцией [IF](../../../builtins/basic.md#if). - -### Примеры - -```yql -SELECT - CASE - WHEN value > 0 - THEN "positive" - ELSE "negative" - END -FROM my_table; -``` - -```yql -SELECT - CASE value - WHEN 0 THEN "zero" - WHEN 1 THEN "one" - ELSE "not zero or one" - END -FROM my_table; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/cast.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/cast.md deleted file mode 100644 index 28e3e184de43..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/cast.md +++ /dev/null @@ -1,17 +0,0 @@ -## CAST {#cast} - -Пробует привести значение к указанному типу. Попытка может оказаться неуспешной и вернуть `NULL`. Для чисел может потерять точность или старшие биты. - -{% if feature_column_container_type %} - -Для списков и словарей может либо удалить, либо заменить на `NULL` элементы, преобразование которых неудачно. -Для структур и кортежей удаляет элементы, которых нет в целевом типе. -Подробнее правила преобразований описаны [здесь](../../../types/cast.md). - -{% endif %} - -{% include [decimal_args](../../../_includes/decimal_args.md) %} - -### Примеры - -{% include [cast_examples](../../../_includes/cast_examples.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/check-match.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/check-match.md deleted file mode 100644 index 1cc3b68c39f3..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/check-match.md +++ /dev/null @@ -1,47 +0,0 @@ -## Проверка строки на соответствие шаблону {#check-match} - -`REGEXP` и `RLIKE` являются алиасами и представляют собой короткий способ записи для вызова [Re2::Grep](../../../udf/list/re2.md#match). `MATCH` — аналогично для [Re2::Match](../../../udf/list/re2.md#match). - -`LIKE` работает по следующим принципам: - -* В шаблонах используется два спецсимвола: - - * `%` — ноль и более любых символов; - * `_` — ровно один любой символ. - - Все остальные символы выступают как литералы, то есть обозначают сами себя. - -* В отличие от `REGEXP`, с шаблоном `LIKE` строка должна совпасть полностью. Например, для поиска подстроки в середине нужно добавить `%` в начале и в конце шаблона. -* `ILIKE` является не чувствительной к регистру версией `LIKE`. -* Если `LIKE` применяется к ключевой колонке сортированной таблицы и шаблон начинается не со спецсимвола, то фильтрация по префиксу опускается прямо до кластера, что в некоторых случаях позволяет не сканировать всю таблицу целиком. Для `ILIKE` данная оптимизация отключена. -* Чтобы заэкранировать спецсимволы, необходимо после шаблона указать символ для экранирования с помощью ключевого слова `ESCAPE '?'`. Вместо `?` можно использовать любой символ, кроме `%`, `_` и `\`. Например, если в качестве экранирующего символа используется знак вопроса, то выражения `?%`, `?_` и `??` в шаблоне совпадут со своим вторым символом: процент, подчеркивание и знак вопроса, соответственно. По умолчанию экранирующий символ не определен. - -Наиболее популярный способ использования ключевых слов `LIKE` и `REGEXP` — фильтрация таблицы в выражениях с `WHERE`. Однако ограничения на использование шаблонов именно в этом контексте нет, и их можно использовать в большинстве контекстов при работе со строками, наравне, например, с конкатенацией с помощью `||`. - -### Примеры - -```yql -SELECT * FROM my_table -WHERE string_column REGEXP '\\d+'; --- второй слеш нужен, так как все --- стандартные строковые литералы в SQL --- могут принимать С-escaped строки -``` - -```yql -SELECT - string_column LIKE '___!_!_!_!!!!!!' ESCAPE '!' - -- ищет строку из ровно 9 символов: - -- 3 произвольных, - -- затем 3 подчеркивания - -- и 3 восклицательных знака -FROM my_table; -``` - -```yql -SELECT * FROM my_table -WHERE key LIKE 'foo%bar'; --- при наличии сортировки таблицы по key просканирует только ключи, --- начинающиеся на foo, и затем среди них --- оставит только заканчивающиеся на bar -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/concatenation.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/concatenation.md deleted file mode 100644 index 3d1525a75ec8..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/concatenation.md +++ /dev/null @@ -1,13 +0,0 @@ -## Конкатенация строк {#concatenation} - -Выполняется через бинарный оператор `||`. - -Как и у других бинарных операторов, если в данных с одной из сторон оказался `NULL`, то и результат будет `NULL`. - -Не следует путать этот оператор с логическим «или», в SQL оно обозначается ключевым словом `OR`. Также не стоит пытаться делать конкатенацию через `+`. - -### Примеры - -```yql -SELECT "fo" || "o"; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/in.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/in.md deleted file mode 100644 index e8c7eb862eaf..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/in.md +++ /dev/null @@ -1,47 +0,0 @@ -## IN {#in} - -Проверка вхождения одного значения в набор значений. Логически эквивалентно цепочке сравнений на равенство через `OR`, но реализовано более эффективно. - -{% note warning %} - -В отличие от аналогичного ключевого слова в Python, в YQL `IN` **НЕ** является поиском подстроки в строке. Для поиска подстроки можно использовать функцию [String::Contains](../../../udf/list/string.md) или описанные выше [LIKE / REGEXP](../../../syntax/expressions.md#like). - -{% endnote %} - -Сразу после `IN` можно указать [хинт](../../lexer.md#sql-hints) `COMPACT`. -Если `COMPACT` не указан, то `IN` с подзапросом по возможности выполняется как соответствующий `JOIN` (`LEFT SEMI` для `IN` и `LEFT ONLY` для `NOT IN`). -Наличие `COMPACT` форсирует in-memory стратегию выполнения: из содержимого правой части `IN` в памяти сразу строится хеш-таблица, по которой затем фильтруется левая часть. - -Хинтом `COMPACT` следует пользоваться с осторожностью. Поскольку хеш-таблица строится в памяти, то запрос может завершиться с ошибкой, если правая часть `IN` содержит много больших и/или различных элементов. - -{% if feature_mapreduce %} - -Так как в YQL есть лимит на размер запроса в байтах (порядка 1Мб), для больших списков значений нужно прикладывать их к запросу через URL и использовать функцию [ParseFile](../../../builtins/basic.md#parsefile). - -{% endif %} - -### Примеры - -```yql -SELECT column IN (1, 2, 3) -FROM my_table; -``` - -```yql -SELECT * FROM my_table -WHERE string_column IN ("a", "b", "c"); -``` - -```yql -$foo = AsList(1, 2, 3); -SELECT 1 IN $foo; -``` - -```yql -$values = (SELECT column + 1 FROM table); -SELECT * FROM my_table WHERE - -- фильтрация по in-memory хеш-таблице на основе table - column1 IN /*+ COMPACT() */ $values AND - -- с последующим LEFT ONLY JOIN с other_table - column2 NOT IN (SELECT other_column FROM other_table); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/is-distinct-from.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/is-distinct-from.md deleted file mode 100644 index cd5bc2452a00..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/is-distinct-from.md +++ /dev/null @@ -1,13 +0,0 @@ -## IS \[NOT\] DISTINCT FROM {#is-distinct-from} - -Сравнение двух значений. В отличие от обычных [операторов сравнения](../../../syntax/expressions.md#comparison-operators), нуллы считаются равными друг другу. - -Сравнение осуществляется по следующим правилам: - -1. операторы `IS DISTINCT FROM`/`IS NOT DISTINCT FROM` определены для тех и только для тех аргументов, для которых определены операторы `!=` и `=`; -2. результат `IS NOT DISTINCT FROM` равен логическому отрицанию результата `IS DISTINCT FROM` для данных аргументов; -3. если результат оператора `==` не равен нуллу для некоторых аргументов, то он совпадает с результатом оператора `IS NOT DISTINCT FROM` для тех же аргументов; -4. если оба аргумента являются незаполненными `Optional`ми или `NULL`ами, то значение `IS NOT DISTINCT FROM` равно `True` -5. результат `IS NOT DISTINCT FROM` от незаполненного `Optional` или `NULL` и заполненного `Optional` или не-`Optional` значения равен `False`. - -Для значений композитных типов эти правила применяются рекурсивно. \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/is-null.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/is-null.md deleted file mode 100644 index 22219be51b72..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/is-null.md +++ /dev/null @@ -1,10 +0,0 @@ -## IS \[NOT\] NULL {#is-null} - -Проверка на пустое значение (`NULL`). Так как `NULL` является особым значением, которое [ничему не равно](../../../types/optional.md#null_expr), то обычные [операторы сравнения](../../../syntax/expressions.md#comparison-operators) для этой задачи не подходят. - -### Примеры - -```yql -SELECT key FROM my_table -WHERE value IS NOT NULL; -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/items-access.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/items-access.md deleted file mode 100644 index 3a72ac6949bd..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/items-access.md +++ /dev/null @@ -1,26 +0,0 @@ -## Обращение к контейнерам {#items-access} - -Для адресации к значениям внутри контейнеров: - -* `Struct<>`, `Tuple<>` и `Variant<>` — используется **точка**. Набор ключей (для кортежа и соответствующего варианта — индексов) известен в момент компиляции запроса. Валидность ключа **проверяется** до начала выполнения запроса. -* `List<>` и `Dict<>` — используются **квадратные скобки**. Набор ключей (для списка — индексов) известен только во время выполнения запроса. Валидность ключа **не проверяется** до начала выполнения запроса. Если значение не найдено — будет возвращено пустое значение (NULL) - -[Описание и список доступных контейнеров](../../../types/containers.md). - -При использовании этого синтаксиса для обращения к контейнерам в столбцах таблиц обязательно нужно указывать полное имя столбца, включая имя или алиас таблицы через точку (см. первый пример ниже). - -### Примеры - -```yql -SELECT - t.struct.member, - t.tuple.7, - t.dict["key"], - t.list[7] -FROM my_table AS t; -``` - -```yql -SELECT - Sample::ReturnsStruct().member; -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/lambda.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/lambda.md deleted file mode 100644 index 063f3356e400..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/lambda.md +++ /dev/null @@ -1,32 +0,0 @@ -## Lambda функции {#lambda} - -Позволяют комбинировать несколько выражений в одно вызываемое значение. - -В круглых скобках перечисляются аргументы, далее после стрелки указывается тело lambda. Тело lambda состоит либо из выражения в круглых скобках, либо из фигурных скобок вокруг необязательной цепочки выражений с присвоением [именованных выражений](../../../syntax/expressions.md#named-nodes) и результата вызова после ключевого слова `RETURN` в последнем выражении. - -Область видимости для тела lambda — сначала локальные именованные выражения, затем аргументы, затем именованные выражения, определенные выше lambda на верхнем уровне запроса. - -В теле lambda можно использовать только чистые выражения — в том числе другие lambda, возможно, переданные через аргументы. Но нельзя использовать [SELECT](../../select/index.md), [INSERT INTO](../../insert_into.md) и прочие выражения верхнего уровня. - -Один или более последних параметров lambda могут быть помечены вопросиком как необязательные — если они не были указаны при вызове lambda, то им будет присвоено значение `NULL`. - -### Примеры - -```yql -$f = ($y) -> { - $prefix = "x"; - RETURN $prefix || $y; -}; - -$g = ($y) -> ("x" || $y); - -$h = ($x, $y?) -> ($x + ($y ?? 0)); - -SELECT $f("y"), $g("z"), $h(1), $h(2, 3); -- "xy", "xz", 1, 5 -``` - -```yql --- если результат лямбды вычисляется единственным выражением, то можно использовать более компактный вариант синтаксиса: -$f = ($x, $_) -> ($x || "suffix"); -- второй аргумент не используется -SELECT $f("prefix_", "whatever"); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/named-nodes.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/named-nodes.md deleted file mode 100644 index 660cdd35158a..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/named-nodes.md +++ /dev/null @@ -1,90 +0,0 @@ -## Именованные выражения {#named-nodes} - -Сложные запросы могут выглядеть громоздко и содержать много уровней вложенности и/или повторяющихся частей. В YQL имеется возможность использовать именованные выражения – способ назначить имя произвольному выражению или подзапросу. На это именованное выражение можно ссылаться в других выражениях или подзапросах. При этом фактически происходит подстановка исходного выражения/подзапроса по месту использования. - -Именованное выражение определяется следующим образом: - -```antlr - = | ; -``` - -Здесь `` состоит из символа $ и произвольного непустого идентификатора (например `$foo`). - -Если выражение в правой части представляет собой кортеж, то его можно автоматически распаковать, указав в левой части несколько именованных выражений через запятую: - -```antlr -, , ... = ; -``` - -В этом случае число выражений должно совпадать с размером кортежа. - -У каждого именованного выражения есть область видимости. Она начинается сразу после определения именованного выражения и заканчивается в конце ближайшего охватывающего scope имен (например в конце запроса либо в конце тела [лямбда-функции](../../../syntax/expressions.md#lambda), [ACTION](../../action.md#define-action){% if feature_subquery %}, [SUBQUERY](../../subquery.md#define-subquery){% endif %}{% if feature_mapreduce %} или цикла [EVALUATE FOR](../../action.md#evaluate-for){% endif %}). -Повторное определение именованного выражения с тем же именем приводит к сокрытию предыдущего выражения из текущей области видимости. - -Если именованное выражение ни разу не использовалось, то генерируется предупреждение. Для того, чтобы избавиться от такого предупреждения, достаточно использовать символ подчеркивания в качестве первого символа идентификатора (например `$_foo`). -Именованное выражение `$_` называется анонимным именованным выражением и обрабатывается специальным образом: оно работает, как если бы `$_` автоматически заменялось на `$_`. -Анонимными именованными выражениями удобно пользоваться в тех случаях, когда мы не интересуемся его значением. Например, для извлечения второго элемента из кортежа из трех элементов можно написать: - -```yql -$_, $second, $_ = AsTuple(1, 2, 3); -select $second; -``` - -Попытка сослаться на анонимное именованное выражение приводит к ошибке: - -```yql -$_ = 1; -select $_; --- ошибка: Unable to reference anonymous name $_ -export $_; --- ошибка: Can not export anonymous name $_ -``` - -{% if feature_mapreduce %} - -Кроме того, нельзя импортировать именованное выражение под анонимным алиасом: - -```yql -import utils symbols $sqrt as $_; --- ошибка: Can not import anonymous name $_ -``` - -{% endif %} - -Анонимные имена аргументов поддерживаются также для [лямбда-функций](../../../syntax/expressions.md#lambda), [ACTION](../../action.md#define-action){% if feature_subquery %}, [SUBQUERY](../../subquery.md#define-subquery){% endif %}{% if feature_mapreduce %} и в [EVALUATE FOR](../../action.md#evaluate-for){% endif %}. - -{% note info %} - -Если в результате подстановки именованных выражений в графе выполнения запроса получились полностью одинаковые подграфы, они объединяются, чтобы такой подграф выполнялся только один раз. - -{% endnote %} - -### Примеры - -```yql -$multiplier = 712; -SELECT - a * $multiplier, -- $multiplier is 712 - b * $multiplier, - (a + b) * $multiplier -FROM abc_table; -``` - -```yql -$intermediate = ( - SELECT - value * value AS square, - value - FROM my_table -); -SELECT a.square * b.value -FROM $intermediate AS a -INNER JOIN $intermediate AS b -ON a.value == b.square; -``` - -```yql -$a, $_, $c = AsTuple(1, 5u, "test"); -- распаковка кортежа -SELECT $a, $c; -``` - -```yql -$x, $y = AsTuple($y, $x); -- swap значений выражений -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/operators.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/operators.md deleted file mode 100644 index fce531eaac80..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/operators.md +++ /dev/null @@ -1,87 +0,0 @@ -## Операторы - -### Арифметические операторы {#math-operators} - -Операторы `+`, `-`, `*`, `/`, `%` определены для [примитивных типов данных](../../../types/primitive.md), являющихся разновидностями чисел. - -Для типа данных Decimal используется банковское округление (до ближайшего четного). - -#### Примеры - -```yql -SELECT 2 + 2; -``` - -```yql -SELECT 0.0 / 0.0; -``` - -### Операторы сравнения {#comparison-operators} - -Операторы `=`, `==`, `!=`, `<>`, `>`, `<` определены для: - -* Примитивных типов данных за исключением Yson и Json. -* Кортежей и структур с одинаковым набором полей. Для структур не определен порядок, но можно проверять на (не-)равенство, а кортежи сравниваются поэлементно слева направо. - -#### Примеры - -```yql -SELECT 2 > 1; -``` - -### Логические операторы {#logic-operators} - -С помощью операторов `AND`, `OR`, `XOR` осуществляются логические операции над булевыми значениями (`Bool`). - -#### Примеры - -```yql -SELECT 3 > 0 AND false; -``` - -### Битовые операторы {#bit-operators} - -Битовые операции над числами: - -* `&`, `|`, `^` — AND, OR и XOR соответственно. Не следует путать битовые операции с аналогичными ключевыми словами. Ключевые слова `AND`, `OR` и `XOR` используются *только для булевых значений*, но не для чисел; -* ` ~ ` — отрицание; -* `<<`, `>>` — сдвиги влево-вправо; -* `|<<`, `>>|` — кольцевые сдвиги влево-вправо. - -#### Примеры - -```yql -SELECT - key << 10 AS key, - ~value AS value -FROM my_table; -``` - -### Приоритет и ассоциативность операторов {#operator-priority} - -Приоритет оператора определяет порядок вычисления выражения содержащего разные операторы. -Например, выражение `1 + 2 * 3` вычисляется как `1 + (2 * 3)`, -поскольку приоритет оператора умножения больше приоритета оператора сложения. - -Ассоциативность определяет порядок вычисления в выражениях содержащих операторы одного типа. -Например, выражение `1 + 2 + 3` вычисляется как `(1 + 2) + 3`, поскольку оператор сложения является лево-ассоциативным. -С другой стороны, выражение `a ?? b ?? c` вычисляется как `a ?? (b ?? c)` из-за право-ассоциативности оператора `??` - -В таблице ниже указаны приоритет и ассоциативность операторов языка YQL. -Операторы в таблице перечислены в порядке убывания приоритета. - -| Приоритет | Оператор | Описание | Ассоциативность | -| --- | --- | --- | --- | -| 1 | `a[], a.foo, a()` | Обращение к элементу контейнера, вызов функции | Левая | -| 2 | `+a, -a, ~a, NOT a` | Унарные операторы: плюс, минус, битовое и логическое отрицание | Правая | -| 3 | `a\|\|b` | [Конкатенация строк](../../../syntax/expressions.md#concatenation) | Левая | -| 4 | `a*b, a/b, a%b` | Умножение,деление, остаток от деления | Левая | -| 5 | `a+b, a-b` | Сложение / вычитание | Левая | -| 6 | `a ?? b` | Операторная форма записи [NVL/COALESCE](../../../builtins/basic.md#coalesce) | Правая | -| 7 | `a<>b, a\|<>\|b,` `a\|b, a^b, a&b` | Сдвиговые и логические битовые операторы | Левая | -| 8 | `a=b, a>b` | Сравнение | Левая | -| 9 | `a IN b` | Вхождение элемента в множество | Левая | -| 9 | `a==b, a=b, a!=b, a<>b,` `a is (not) distinct from b` | Сравнение на (не)равенство | Левая | -| 10 | `a XOR b` | Логическое XOR | Левая | -| 11 | `a AND b` | Логическое AND | Левая | -| 12 | `a OR b` | Логическое OR | Левая | diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/tables.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/tables.md deleted file mode 100644 index feb33308656d..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/expressions/tables.md +++ /dev/null @@ -1,80 +0,0 @@ -## Табличные выражения {#table-contexts} - -Табличное выражения – это выражение, которое возвращает таблицу. Табличными выражениями в YQL являются: - -* подзапросы: `(SELECT key, subkey FROM T)` -* [именованные подзапросы](../../../syntax/expressions.md#named-nodes): `$foo = SELECT * FROM T;` (использование именованного подзапроса `$foo` является табличным выражением) - -{% if feature_subquery %} - -* [шаблоны подзапросов](../../subquery.md#define-subquery): `DEFINE SUBQUERY $foo($name) AS ... END DEFINE;` (вызов `$foo("InputTable")` является табличным выражением). - -{% endif %} - -Семантика табличного выражения зависит от контекста в котором оно используется. В YQL табличные выражения могут применяться в следующих контекстах: - -* табличный контекст - после [FROM](../../select/from.md). - - Здесь табличные выражения работают как ожидается – например `$input = SELECT a, b, c FROM T; SELECT * FROM $input` вернет таблицу с тремя колонками. - - Табличный контекст также возникает после [UNION ALL](../../select/index.md#unionall){% if feature_join %}, [JOIN](../../join.md#join){% endif %}{% if feature_mapreduce and process_command == "PROCESS" %}, [PROCESS](../../process.md#process), [REDUCE](../../reduce.md#reduce){% endif %}; - -* векторный контекст - после [IN](../../../syntax/expressions.md#in). В этом контексте табличное выражение обязано содержать ровно одну колонку (имя этой колонки никак не влияет на результат выражения). - - Табличное выражение в векторном контексте типизируется как список (тип элемента списка при этом совпадает с типом колонки). Пример: `SELECT * FROM T WHERE key IN (SELECT k FROM T1)`; - -* скалярный контекст возникает *во всех остальных случаях*. Как и в векторном контексте, табличное выражение должно содержать ровно одну колонку, но значением табличного выражения будет скаляр – произвольно выбранное значение этой колонки (если получилось ноль строк, то результатом будет `NULL`). Пример: `$count = SELECT COUNT(*) FROM T; SELECT * FROM T ORDER BY key LIMIT $count / 2`. - -Порядок строк в табличном контексте, порядок элементов в векторном контексте и правило выбора значения в скалярном контексте (в случае если значений несколько) не определены. На этот порядок также нельзя повлиять с помощью `ORDER BY`: `ORDER BY` без `LIMIT` в табличных выражениях будет игнорироваться с выдачей предупреждения, а использование `ORDER BY` с `LIMIT` определяет множество элементов, но не порядок внутри этого множества. - -{% if feature_mapreduce and process_command == "PROCESS" %} - -Из этого правила есть исключение. Именованное выражение с [PROCESS](../../process.md#process), будучи использованным в скалярном контексте, ведет себя как в табличном: - -```yql -$input = SELECT 1 AS key, 2 AS value; -$process = PROCESS $input; - -SELECT FormatType(TypeOf($process)); -- $process используется в скалярном контексте, - -- но результат SELECT при этом - List> - -SELECT $process[0].key; -- вернет 1 - -SELECT FormatType(TypeOf($input)); -- ошибка: $input в скалярном контексте должен содержать одну колонку -``` - -{% note warning "Внимание" %} - -Часто встречающейся ошибкой является использование выражения в скалярном контексте вместо табличного или векторного. Например: - -```yql -$dict = SELECT key, value FROM T1; - -DEFINE SUBQUERY $merge_dict($table, $dict) AS -SELECT * FROM $table LEFT JOIN $dict USING(key); -END DEFINE; - -SELECT * FROM $merge_dict("Input", $dict); -- $dict здесь используется в скалярном контексте. - -- ошибка - в скалярном контексте ожидается ровно одна колонка - -``` - -Правильное решение в данном случае выглядит так: - -```yql -DEFINE SUBQUERY $dict() AS -SELECT key, value FROM T1; -END DEFINE; - -DEFINE SUBQUERY $merge_dict($table, $dict) AS -SELECT * FROM $table LEFT JOIN $dict() USING(key); -- использование табличного выражения $dict() - -- (вызов шаблона подзапроса) в табличном контексте -END DEFINE; - -SELECT * FROM $merge_dict("Input", $dict); -- $dict - шаблон позапроса (не табличное выражение) - -- передаваемый в качестве аргумента табличного выражения -``` - -{% endnote %} - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_columns.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_columns.md deleted file mode 100644 index 79bc25bf622c..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_columns.md +++ /dev/null @@ -1,19 +0,0 @@ -## FLATTEN COLUMNS {#flatten-columns} - -Преобразует таблицу, в которой все столбцы должны являться структурами, в таблицу со столбцами, соответствующими каждому элементу каждой структуры из исходных столбцов. - -Имена исходных столбцов-структур не используются и не возвращаются в результате. Имена элементов структур не должны повторяться в исходных столбцах. - -### Пример - -```yql -SELECT x, y, z -FROM ( - SELECT - AsStruct( - 1 AS x, - "foo" AS y), - AsStruct( - false AS z) -) FLATTEN COLUMNS; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_other_db.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_other_db.md deleted file mode 100644 index 104d7e51a4f2..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_other_db.md +++ /dev/null @@ -1,9 +0,0 @@ -### Аналоги FLATTEN BY для других СУБД {#flatten-other-dmb} - -* PostgreSQL: `unnest`; -* Hive: `LATERAL VIEW`; -* MongoDB: `unwind`; -* Google BigQuery: `FLATTEN`; -* ClickHouse: `ARRAY JOIN / arrayJoin`; - - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_type_by.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_type_by.md deleted file mode 100644 index 788a88df1779..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/flatten/flatten_type_by.md +++ /dev/null @@ -1,41 +0,0 @@ -### Уточнение типа контейнера {#flatten-by-specific-type} - -Чтобы уточнить тип контейнера, по которому необходимо произвести преобразование, можно использовать: - -* `FLATTEN LIST BY` - - Для `Optional>` операция `FLATTEN LIST BY` будет разворачивать список, интерпретируя `NULL`-значение как пустой список. -* `FLATTEN DICT BY` - - Для `Optional>` операция `FLATTEN DICT BY` будет разворачивать словарь, интерпретируя `NULL`-значение как пустой словарь. -* `FLATTEN OPTIONAL BY` - - Чтобы фильтровать `NULL`-значения без размножения, необходимо уточнить операцию до `FLATTEN OPTIONAL BY`. - -#### Примеры - -```yql -SELECT - t.item.0 AS key, - t.item.1 AS value, - t.dict_column AS original_dict, - t.other_column AS other -FROM my_table AS t -FLATTEN DICT BY dict_column AS item; -``` - -```yql -SELECT * FROM ( - SELECT - AsList(1, 2, 3) AS a, - AsList("x", "y", "z") AS b -) FLATTEN LIST BY (a, b); -``` - -```yql -SELECT * FROM ( - SELECT - "1;2;3" AS a, - AsList("x", "y", "z") AS b -) FLATTEN LIST BY (String::SplitToList(a, ";") as a, b); -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/compact.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/compact.md deleted file mode 100644 index a01f59afb10e..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/compact.md +++ /dev/null @@ -1,17 +0,0 @@ -## COMPACT - -Наличие [SQL хинта](../../lexer.md#sql-hints) `COMPACT` непосредственно после ключевого слова `GROUP` позволяет более эффективно выполнять агрегацию в тех случаях, когда автору запроса заранее известно, что ни по одному из ключей агрегации не встречаются большие объемы данных (больше примерно гигабайт или миллионов строк). Если это предположение на практике окажется неверным, то операция может завершиться ошибкой из-за превышения потребления оперативной памяти или работать значительно медленнее не-COMPACT версии. - -В отличие от обычного GROUP BY, отключается стадия Map-side combiner и дополнительные Reduce для каждого поля с [DISTINCT](../../group_by.md#distinct) агрегацией. - -### Пример - -```yql -SELECT - key, - COUNT(DISTINCT value) AS count -- топ-3 ключей по количеству уникальных значений -FROM my_table -GROUP /*+ COMPACT() */ BY key -ORDER BY count DESC -LIMIT 3; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/distinct.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/distinct.md deleted file mode 100644 index 6bf72ec94137..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/distinct.md +++ /dev/null @@ -1,24 +0,0 @@ -## DISTINCT {#distinct} - -Применение [агрегатных функций](../../../builtins/aggregation.md) только к уникальным значениям столбца. - -{% note info %} - -Применение `DISTINCT` к вычислимым значениям на данный момент не реализовано. С этой целью можно использовать [подзапрос](../../select/from.md) или выражение `GROUP BY ... AS ...`. - -{% endnote %} - -### Пример - -```yql -SELECT - key, - COUNT(DISTINCT value) AS count -- топ-3 ключей по количеству уникальных значений -FROM my_table -GROUP BY key -ORDER BY count DESC -LIMIT 3; -``` - -Также ключевое слово `DISTINCT` может использоваться для выборки уникальных строк через [`SELECT DISTINCT`](../../select/distinct.md). - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/general.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/general.md deleted file mode 100644 index 3ad6399f7dea..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/general.md +++ /dev/null @@ -1,68 +0,0 @@ -## GROUP BY - -Группирует результаты `SELECT` по значениям указанных столбцов или выражений. Вместе с `GROUP BY` часто применяются [агрегатные функции](../../../builtins/aggregation.md) (`COUNT`, `MAX`, `MIN`, `SUM`, `AVG`) для выполнения вычислений в каждой группе. - -### Синтаксис - -```yql -SELECT -- В SELECT можно использовать: - column1, -- ключевые колонки, заданные в GROUP BY - key_n, -- именованные выражения, заданные в GROUP BY - column1 + key_n, -- произвольные неагрегатные функции от них - Aggr_Func1( column2 ), -- агрегатные функции, содержащие в аргументах любые колонки, - Aggr_Func2( key_n + column2 ), -- включая именованные выражения, заданные в GROUP BY - ... -FROM table -GROUP BY - column1, column2, ..., - AS key_n -- При группировке по выражению ему может быть задано имя через AS, - -- которое может быть использовано в SELECT -``` - -Запрос вида `SELECT * FROM table GROUP BY k1, k2, ...` вернет все колонки, перечисленные в GROUP BY, то есть экивалентент запросу `SELECT DISTINCT k1, k2, ... FROM table`. - -Звездочка может также применяться в качестве аргумента агрегатной функции `COUNT`. `COUNT(*)` означает "число строк в группе". - - -{% note info %} - -Агрегатные функции не учитывают `NULL` в своих аргументах, за исключением функции `COUNT`. - -{% endnote %} - -Также в YQL доступен механизм фабрик агрегатных функций, реализованный с помощью функций [`AGGREGATION_FACTORY`](../../../builtins/basic.md#aggregationfactory) и [`AGGREGATE_BY`](../../../builtins/aggregation.md#aggregateby). - -### Примеры - -```yql -SELECT key, COUNT(*) FROM my_table -GROUP BY key; -``` - -```yql -SELECT double_key, COUNT(*) FROM my_table -GROUP BY key + key AS double_key; -``` - -```yql -SELECT - double_key, -- ОК: ключевая колонка - COUNT(*) AS group_size, -- OK: COUNT(*) - SUM(key + subkey) AS sum1, -- ОК: агрегатная функция - CAST(SUM(1 + 2) AS String) AS sum2, -- ОК: агрегатная функция с константным аргументом - SUM(SUM(1) + key) AS sum3, -- ОШИБКА: вложенные агрегации не допускаются - key AS k1, -- ОШИБКА: использование неключевой колонки key без агрегации - key * 2 AS dk1, -- ОШИБКА в YQL: использование неключевой колонки key без агрегации -FROM my_table -GROUP BY - key * 2 AS double_key, - subkey as sk, - -``` - - -{% note warning %} - -Возможность указывать имя для колонки или выражения в `GROUP BY .. AS foo` является расширением YQL. Такое имя становится видимым в `WHERE` несмотря на то, что фильтрация по `WHERE` выполняется [раньше](../../select/index.md#selectexec) группировки. В частности, если в таблице `T` есть две колонки `foo` и `bar`, то в запросе `SELECT foo FROM T WHERE foo > 0 GROUP BY bar AS foo` фильтрация фактически произойдет по колонке `bar` из исходной таблицы. - -{% endnote %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/general_stream.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/general_stream.md deleted file mode 100644 index 57cdea496083..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/general_stream.md +++ /dev/null @@ -1,56 +0,0 @@ -## GROUP BY ... HOP - -Сгруппировать таблицу по значениям указанных столбцов или выражений, а также окну времени. - -Если GROUP BY присутствует в запросе, то при выборке столбцов (между `SELECT STREAM ... FROM`) допустимы **только** следующие конструкции: - -1. Столбцы, по которым производится группировка (присутствующие в аргументе `GROUP BY`). -2. Агрегатные функции (см. следующий раздел). Столбцы, по которым **не** идет группировка, можно включать только в качестве аргументов агрегатной функции. -3. Функции, выдающие начальное и конечное время текущего окна (`HOP_START` и `HOP_END`) -4. Произвольные вычисления, комбинирующие пункты 1-3. - -Имеется возможность выполнять группировку по результату вычисления произвольного выражения от исходных столбцов. В этом случае для получения доступа к результату этого выражения рекомендуется присваивать ему имя с помощью `AS`, см. второй пример. - -Агрегатные функции автоматически пропускают `NULL` в своих аргументах. - -Среди столбцов, по которым производится группировка, должна присутствовать конструкция `HOP`, определяющая характеристики окна времени для группировки. -```yql -HOP(time_extractor, hop, interval, delay) -``` -Реализованный вариант окна времени называется **hopping window**. Это окно, продвигающееся вперёд дискретными интервалами (параметр `hop`). Общая длительность окна задаётся параметром `interval`. Для определения времени каждого входного события используется параметр `time_extractor`. Это выражение, зависящее только от входных значений столбцов стрима, должно иметь тип `Timestamp`. Оно указывает, откуда именно во входных событиях доставать значение времени. - -В каждом потоке, определяемом значениями всех столбцов группировки, окно продвигается независимо от других потоков. Продвижение окна полностью зависит от самого позднего события потока. Поскольку записи в потоках слегка перемешиваются во времени, добавлен параметр `delay`, позволяющий отложить закрытие окна на указанную величину. События, приходящие до текущего окна, игнорируются. - -Параметры `interval` и `delay` следует задавать кратными параметру `hop`. Некратные интервалы будут округлены в меньшую сторону. - -Для задания `hop`, `interval` и `delay` используется строковое выражение, соответствующее стандарту [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). Это формат, который используется для конструирования встроенного типа `Interval` [из строки](../../../builtins/basic.md#data-type-literals). - -Функции без параметров `HOP_START` и `HOP_END` возвращают значение типа `Timestamp` и соответствуют началу и концу текущего окна. - -Известное в других системах **tumbling window** является частным случаем **hopping window**, когда `interval` == `hop`. - -### Примеры - -```yql -SELECT STREAM - key, - COUNT(*) -FROM my_stream -GROUP BY - HOP(CAST(subkey AS Timestamp), "PT10S", "PT1M", "PT30S"), - key; --- hop = 10 секунд --- interval = 1 минута --- delay = 30 секунд -``` - -```yql -SELECT STREAM - double_key, - HOP_END() as time, - COUNT(*) as count -FROM my_stream -GROUP BY - key + key AS double_key, - HOP(ts, "PT1М", "PT1M", "PT1M"); -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/having.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/having.md deleted file mode 100644 index 8e0b167940d3..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/having.md +++ /dev/null @@ -1,13 +0,0 @@ -## HAVING {#having} - -Фильтрация выборки `SELECT` по результатам вычисления [агрегатных функций](../../../builtins/aggregation.md). Синтаксис аналогичен конструкции [`WHERE`](../../select/where.md). - -### Пример - -```yql -SELECT - key -FROM my_table -GROUP BY key -HAVING COUNT(value) > 100; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/having_stream.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/having_stream.md deleted file mode 100644 index 0bb9ff598935..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/having_stream.md +++ /dev/null @@ -1,13 +0,0 @@ -## HAVING {#having} - -Фильтрация выборки `SELECT STREAM` по результатам вычисления [агрегатных функций](../../../builtins/aggregation.md). Синтаксис аналогичен [WHERE](../../select_stream.md#where). - -### Примеры - -```yql -SELECT STREAM - key -FROM my_table -GROUP BY key, HOP(ts, "PT1M", "PT1M", "PT1M") -HAVING COUNT(value) > 100; -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/rollup_cube_sets.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/rollup_cube_sets.md deleted file mode 100644 index 79689d135e7f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/rollup_cube_sets.md +++ /dev/null @@ -1,73 +0,0 @@ -## ROLLUP, CUBE и GROUPING SETS {#rollup} - -Результаты вычисления агрегатной функции в виде промежуточных итогов для групп и общих итогов для отдельных столбцов или всей таблицы. - -### Синтаксис - -```yql -SELECT - c1, c2, -- столбцы, по которым производится группировка - -AGGREGATE_FUNCTION(c3) AS outcome_c -- агрегатная функция (SUM, AVG, MIN, MAX, COUNT) - -FROM table_name - -GROUP BY - GROUP_BY_EXTENSION(c1, c2) -- расширение GROUP BY: ROLLUP, CUBE или GROUPING SETS -``` - -* `ROLLUP` — группирует значения столбцов в порядке их перечисления в аргументах (строго слева направо), формирует промежуточные итоги для каждой группы и общий итог. -* `CUBE` — группирует значения для всех возможных комбинаций столбцов, формирует промежуточные итоги для каждой группы и общий итог. -* `GROUPING SETS` — задает группы для промежуточных итогов. - -`ROLLUP`, `CUBE` и `GROUPING SETS` можно комбинировать через запятую. - -### GROUPING {#grouping} - -В промежуточном итоге значения столбцов, которые не участвуют в вычислениях, заменяются на `NULL`. В общем итоге на `NULL` заменяются значения всех столбцов. `GROUPING` — функция, которая позволяет отличить исходные значения `NULL` от `NULL`, которые были добавлены при формировании общих и промежуточных итогов. - -`GROUPING` возвращает битовую маску: - -* `0` — `NULL` для исходного пустого значения. -* `1` — `NULL`, добавленный для промежуточного или общего итога. - -### Пример - -```yql -SELECT - column1, - column2, - column3, - - CASE GROUPING( - column1, - column2, - column3, - ) - WHEN 1 THEN "Subtotal: column1 and column2" - WHEN 3 THEN "Subtotal: column1" - WHEN 4 THEN "Subtotal: column2 and column3" - WHEN 6 THEN "Subtotal: column3" - WHEN 7 THEN "Grand total" - ELSE "Individual group" - END AS subtotal, - - COUNT(*) AS rows_count - -FROM my_table - -GROUP BY - ROLLUP( - column1, - column2, - column3 - ), - GROUPING SETS( - (column2, column3), - (column3) - -- если добавить сюда ещё (column2), то в сумме - -- эти ROLLUP и GROUPING SETS дали бы результат, - -- аналогичный CUBE - ) -; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/session_window.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/session_window.md deleted file mode 100644 index ebefa82d9737..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/group_by/session_window.md +++ /dev/null @@ -1,62 +0,0 @@ -## GROUP BY ... SessionWindow() {#session-window} - -В YQL поддерживаются группировки по сессиям. К обычным выражениям в `GROUP BY` можно добавить специальную функцию `SessionWindow`: - -```yql -SELECT - user, - session_start, - SessionStart() AS same_session_start, -- то же что и session_start - COUNT(*) AS session_size, - SUM(value) AS sum_over_session, -FROM my_table -GROUP BY user, SessionWindow(, ) AS session_start -``` - -При этом происходит следующее: - -1. Входная таблица партиционируется по ключам группировки, указанным в `GROUP BY`, без учета SessionWindow (в данном случае по `user`). Если кроме SessionWindow в `GROUP BY` ничего нет, то входная таблица попадает в одну партицию -2. Каждая партиция делится на непересекающие подмножества строк (сессии). Для этого партиция сортируется по возрастанию значения выражения `time_expr`. Границы сессий проводятся между соседними элементами партиции, разница значений `time_expr` для которых превышает `timeout_expr` -3. Полученные таким образом сессии и являются финальными партициями, на которых вычисляются агрегатные функции. - -Ключевая колонка SessionWindow() (в примере `session_start`) имеет значение "минимальный `time_expr` в сессии". -Кроме того, при наличии SessionWindow() в `GROUP BY` может использоваться специальная агрегатная функция -[SessionStart](../../../builtins/aggregation.md#session-start). - -Поддерживается также расширенный вариант SessionWindow с четырьмя аргументами: - -`SessionWindow(, , , )` - -Здесь: - -* `` – выражение по которому сортируется исходная партиция -* `` – лямбда-функция для инициализации состояния расчета сессий. Имеет сигнатуру `(TableRow())->State`. Вызывается один раз на первом (по порядку сортировки) элементе исходной партиции -* `` – лямбда-функция для обновления состояния расчета сессий и определения границ сессий. Имеет сигнатуру `(TableRow(), State)->Tuple`. Вызывается на каждом элементе исходной партиции, кроме первого. Новое значения состояния вычисляется на основе текущей строки таблицы и предыдущего состояния. Если первый элемент возвращенного кортежа имеет значение `True`, то с _текущей_ строки начнется новая сессия. Ключ новой сессии получается путем применения `` ко второму элементу кортежа. -* `` – лямбда-функция для вычисления ключа сессии ("значения" SessionWindow(), которое также доступно через SessionStart()). Функция имеет сигнатуру `(TableRow(), State)->SessionKey`. Вызывается на первом элемента партиции (после ``) и на тех элементах, для которых `` вернула `True` в качестве первого элемента кортежа. Стоит отметить, что для начала новой сессии необходимо, чтобы `` вернула значение, которое отличается от предыдущего ключа сессии. При этом сессии с одинаковыми ключами не объединяются. Например, если `` последовательно возвращает `0, 1, 0, 1`, то это будут четыре различные сессии. - -С помощью расширенного варианта SessionWindow можно решить, например, такую задачу: разделить партицию на сессии как в варианте SessionWindow с двумя аргументами, но с ограничением максимальной длины сессии некоторой константой: - -### Пример - -```yql -$max_len = 1000; -- максимальная длина сессии -$timeout = 100; -- таймаут (timeout_expr в упрощенном варианте SessionWindow) - -$init = ($row) -> (AsTuple($row.ts, $row.ts)); -- состояние сессии - тапл из 1) значения временной колонки ts на первой строчке сессии и 2) на текущей строчке -$update = ($row, $state) -> { - $is_end_session = $row.ts - $state.0 > $max_len OR $row.ts - $state.1 > $timeout; - $new_state = AsTuple(IF($is_end_session, $row.ts, $state.0), $row.ts); - return AsTuple($is_end_session, $new_state); -}; -$calculate = ($row, $state) -> ($row.ts); -SELECT - user, - session_start, - SessionStart() AS same_session_start, -- то же что и session_start - COUNT(*) AS session_size, - SUM(value) AS sum_over_session, -FROM my_table -GROUP BY user, SessionWindow(ts, $init, $update, $calculate) AS session_start -``` - -`SessionWindow` может использоваться в `GROUP BY` только один раз. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/insert_hints.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/insert_hints.md deleted file mode 100644 index bd0c1ab6c45f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/insert_hints.md +++ /dev/null @@ -1,16 +0,0 @@ -{% if feature_insert_with_truncate %} - -Запись может выполняться с одним или несколькими модификаторами. Модификатор указывается после ключевого слова `WITH` после имени таблицы: `INSERT INTO ... WITH SOME_HINT`. -Если у модификатора есть значение, то оно указывается после знака `=`: `INSERT INTO ... WITH SOME_HINT=value`. -Если необходимо указать несколько модификаторов, то они заключаются в круглые скобки: `INSERT INTO ... WITH (SOME_HINT1=value, SOME_HINT2, SOME_HINT3=value)`. - -Чтобы перед записью очистить таблицу от имевшихся данных, достаточно добавить модификатор: `INSERT INTO ... WITH TRUNCATE`. - -## Примеры - -```yql -INSERT INTO my_table WITH TRUNCATE -SELECT key FROM my_table_source; -``` - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/insert_into.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/insert_into.md deleted file mode 100644 index 0afc6d79da52..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/insert_into.md +++ /dev/null @@ -1,63 +0,0 @@ -# INSERT INTO - -{% if oss == true and backend_name == "YDB" %} - -{% note warning %} - -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} - -{% include [ways_add_data_to_olap](../../../../_includes/ways_add_data_to_olap.md) %} - -{% endnote %} - -{% endif %} - -{% if select_command != "SELECT STREAM" %} -Добавляет строки в {% if oss == true and backend_name == "YDB" %}строковую{% endif %} таблицу. {% if feature_bulk_tables %} Если целевая таблица уже существует и не является сортированной, операция `INSERT INTO` дописывает строки в конец таблицы. В случае сортированной таблицы, YQL пытается сохранить сортированность путем запуска сортированного слияния. {% endif %}{% if feature_map_tables %} При попытке вставить в таблицу строку с уже существующим значением первичного ключа операция завершится ошибкой с кодом `PRECONDITION_FAILED` и текстом `Operation aborted due to constraint violation: insert_pk`.{% endif %} - -{% if feature_mapreduce %}Таблица по имени ищется в базе данных, заданной оператором [USE](../use.md).{% endif %} - -`INSERT INTO` позволяет выполнять следующие операции: - -* Добавление константных значений с помощью [`VALUES`](../values.md). - - ```yql - INSERT INTO my_table (Key1, Key2, Value1, Value2) - VALUES (345987,'ydb', 'Яблочный край', 1414); - COMMIT; - ``` - - ```yql - INSERT INTO my_table (key, value) - VALUES ("foo", 1), ("bar", 2); - ``` - -* Сохранение результата выборки `SELECT`. - - ```yql - INSERT INTO my_table - SELECT Key AS Key1, "Empty" AS Key2, Value AS Value1 - FROM my_table1; - ``` - -{% else %} - -Направить результат вычисления [SELECT STREAM](../select_stream.md) в указанный стрим на кластере, заданном оператором [USE](../use.md). Стрим должен существовать и иметь схему, подходящую результату запроса. - -## Примеры - -```yql -INSERT INTO my_stream_dst -SELECT STREAM key FROM my_stream_src; -``` - -Существует возможность указать в качестве цели таблицу на кластере ydb. Таблица должна существовать на момент создания операции. Схема таблицы должна быть совместима с типом результата запроса. - -## Примеры - -```yql -INSERT INTO ydb_cluster.`my_table_dst` -SELECT STREAM * FROM rtmr_cluster.`my_stream_source`; -``` - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/insert_with.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/insert_with.md deleted file mode 100644 index 9ee492e016e8..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/insert_with.md +++ /dev/null @@ -1,24 +0,0 @@ -{% if feature_federated_queries %} - -При работе с [внешними файловыми источниками данных](../../../../concepts/datamodel/external_data_source.md) можно дополнительно указывать ряд параметров: - -{% include [s3_with](select/s3_with.md) %} - -## Пример - -```yql -INSERT INTO `connection`.`test/` -WITH -( - FORMAT = "csv_with_names" -) -SELECT - "value" AS value, "name" AS name -``` - -Где: - -* `connection` — название соединения с S3 ({{ objstorage-full-name }}). -* `test/`— путь внутри бакета, куда будут записаны данные. При записи создаются файлы со случайными именами. - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/into_result.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/into_result.md deleted file mode 100644 index 68dc72537456..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/into_result.md +++ /dev/null @@ -1,16 +0,0 @@ -# INTO RESULT - -Позволяет задать пользовательскую метку для [SELECT](../select/index.md){% if feature_mapreduce and process_command == "PROCESS" %}, [PROCESS](../process.md) или [REDUCE](../reduce.md){% endif %}.{% if backend_name != "YDB" and oss == true %} Не может быть задано одновременно с [DISCARD](../discard.md).{% endif %} - -## Примеры - -```yql -SELECT 1 INTO RESULT foo; -``` - -```yql -SELECT * FROM -my_table -WHERE value % 2 == 0 -INTO RESULT `Название результата`; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/debug.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/debug.md deleted file mode 100644 index 154720586bca..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/debug.md +++ /dev/null @@ -1,40 +0,0 @@ -{% if tech %} - -## Отладочные и служебные {#debug} - -{% if feature_webui %} - -### `DirectRead` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Служебная настройка для работы preview таблиц в [HTTP API](../../../interfaces/http.md) (для веб-интерфейса и консольного клиента). -{% endif %} - -### `config.flags("ValidateUdf", "Lazy")` - -| Тип значения | По умолчанию | -| --- | --- | -| Строка: None / Lazy / Greedy | None | - -Валидация результатов UDF на соответствие объявленной сигнатуре. Greedy режим форсирует материализацию «ленивых» контейнеров, а Lazy — нет. - -### `{{ backend_name_lower }}.DefaultCluster` - -| Тип значения | По умолчанию | -| --- | --- | -| Строка с именем кластера | hahn | - -Выбор кластера для выполнения вычислений, не использующих таблицы. - -### `config.flags("Diagnostics")` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Получение диагностической информации от YQL в виде дополнительного результата запроса. - -{% endif %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/definition.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/definition.md deleted file mode 100644 index 0b4c1ad5ac55..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/definition.md +++ /dev/null @@ -1,39 +0,0 @@ -## Определение - -Переопределение настроек. - -### Синтаксис - -`PRAGMA x.y = "z";` или `PRAGMA x.y("z", "z2", "z3");`: - -* `x` — (опционально) категория настройки. -* `y` — название настройки. -* `z` — (опционально для флагов) значение настройки. Допустимо использование следующих суффиксов: - - * `Kb`, `Mb`, `Gb` — для объема информации. - * `sec`, `min`, `h`, `d` — для временных значений. - -### Примеры - -```yql -PRAGMA AutoCommit; -``` - -```yql -PRAGMA TablePathPrefix = "home/yql"; -``` - -```yql -PRAGMA Warning("disable", "1101"); -``` - -За некоторым исключением, значение настроек можно вернуть в состояние по умолчанию с помощью `PRAGMA my_pragma = default;`. - -Полный список доступных настроек [см. в таблице ниже](../../pragma.md#pragmas). - -### Область действия {#pragmascope} - -Если не указано иное, прагма влияет на все идущие следом выражения вплоть до конца модуля, в котором она встречается. -При необходимости и логической возможности допустимо менять значение настройки несколько раз в одном запросе, чтобы оно было разным на разных этапах выполнения. -Существуют также специальные scoped прагмы, область действия которых определяется по тем же правилам, что и область видимости [именованных выражений](../../expressions.md#named-nodes). -В отличие от scoped прагм, обычные прагмы могут использоваться только в глобальной области видимости (не внутри лямбда-функций, ACTION{% if feature_subquery %}, SUBQUERY{% endif %} и т.п.). \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/file_options.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/file_options.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/files.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/files.md deleted file mode 100644 index 6df4bd5fa0f2..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/files.md +++ /dev/null @@ -1,123 +0,0 @@ - -{% if feature_mapreduce %} - -## Работа с файлами - -### File - -| Тип значения | По умолчанию | Статическая /
динамическая | -| --- | --- | --- | -| Два или три строковых аргумента — алиас, URL и опциональное имя токена | — | Статическая | - -Приложить файл к запросу по URL. Использовать приложенные файлы можно с помощью встроенных функций [FilePath и FileContent](../../../builtins/basic.md#filecontent).{% if oss != true %} Данная `PRAGMA` является универсальной альтернативой прикладыванию файлов с использованием встроенных механизмов [веб-](../../../interfaces/web.md#attach) или [консольного](../../../interfaces/cli.md#attach) клиентов.{% endif %} - -Сервис YQL оставляет за собой право кешировать находящиеся за URL файлы на неопределенный срок, по-этому при значимом изменении находящегося за ней содержимого настоятельно рекомендуется модифицировать URL за счет добавления/изменения незначащих параметров. - -При указании имени токена, его значение будет использоваться для обращения к целевой системе. - -### FileOption - -| Тип значения | По умолчанию | Статическая /
динамическая | -|-------------------------------------------------|--------------|--------------------------------| -| Три строковых аргумента — алиас, ключ, значение | — | Статическая | - -Установить у указанного файла опцию по заданному ключу в заданное значение. Файл с этим алиасом уже должен быть объявлен -через [PRAGMA File](#file) или приложен к запросу. - -{% include [x](file_options.md) %} - -### Folder - -| Тип значения | По умолчанию | Статическая /
динамическая | -| --- | --- | --- | -| Два или три строковых аргумента — префикс, URL и опциональное имя токена | — | Статическая | - -Приложить набор файлов к запросу по URL. Работает аналогично добавлению множества файлов через [PRAGMA File](#file) по прямым ссылкам на файлы с алиасами, полученными объединением префикса с именем файла через `/`. - -При указании имени токена, его значение будет использоваться для обращения к целевой системе. - -### Library - -| Тип значения | По умолчанию | Статическая /
динамическая | -| --- | --- | --- | -| Один или два аргумента - имя файла и опциональный URL | — | Статическая | - -Интерпретировать указанный приложенный файл как библиотеку, из которой можно делать [IMPORT](../../export_import.md). Тип синтаксиса библиотеки определяется по расширению файла: -* `.sql` для YQL диалекта SQL (рекомендуется); -* `.yql` для [s-expressions](/docs/s_expressions). - -Пример с приложенным файлом к запросу: - -```yql -PRAGMA library("a.sql"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -В случае указания URL библиотека скачивается с него, а не с предварительного приложенного файла, как в следующем примере: - -```yql -PRAGMA library("a.sql","{{ corporate-paste }}/5618566/text"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -При этом можно использовать подстановку текстовых параметров в URL: - -```yql -DECLARE $_ver AS STRING; -- "5618566" -PRAGMA library("a.sql","{{ corporate-paste }}/{$_ver}/text"); -IMPORT a SYMBOLS $x; -SELECT $x; -``` - -### Package - -| Тип значения | По умолчанию | Статическая /
динамическая | -| --- | --- | --- | -| Два или три аргумента - имя пакета, URL и опциональный токен | — | Статическая | - -Приложить иерархический набор файлов к запросу по URL, интерпретируя их в качестве пакета с указанным именем - взаимосвязанного набора библиотек. - -Имя пакета ожидается в формате ``project_name.package_name``; из библиотек пакета в дальнейшнем можно делать [IMPORT](../../export_import.md) с именем модуля вида ``pkg.project_name.package_name.maybe.nested.module.name``. - -Пример для пакета с плоской иерархией, состоящего из двух библиотек - foo.sql и bar.sql: - -```yql -PRAGMA package("project.package", "{{ corporate-yt }}/{{ corporate-yt-cluster }}/path/to/package"); -IMPORT pkg.project.package.foo SYMBOLS $foo; -IMPORT pkg.project.package.bar SYMBOLS $bar; -SELECT $foo, $bar; -``` - -При этом можно использовать подстановку текстовых параметров в URL: - -```yql -DECLARE $_path AS STRING; -- "path" -PRAGMA package("project.package","{{ corporate-yt }}/{{ corporate-yt-cluster }}/{$_path}/to/package"); -IMPORT pkg.project.package.foo SYMBOLS $foo; -IMPORT pkg.project.package.bar SYMBOLS $bar; -SELECT $foo, $bar; -``` - -### OverrideLibrary - -| Тип значения | По умолчанию | Статическая /
динамическая | -| --- | --- | --- | -| Один аргумент - имя файла | — | Статическая | - -Интерпретировать указанный приложенный файл как библиотеку и перекрыть ей одну из библиотек пакета. - -Имя файла ожидается в формате ``project_name/package_name/maybe/nested/module/name.EXTENSION``, поддерживаются аналогичные [PRAGMA Library](#library) расширения. - -Пример: - -```yql -PRAGMA package("project.package", "{{ corporate-yt }}/{{ corporate-yt-cluster }}/path/to/package"); -PRAGMA override_library("project/package/maybe/nested/module/name.sql"); - -IMPORT pkg.project.package.foo SYMBOLS $foo; -SELECT $foo; -``` - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/global.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/global.md deleted file mode 100644 index 550eab51d3ff..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/global.md +++ /dev/null @@ -1,277 +0,0 @@ -## Глобальные {#pragmas} - -### AutoCommit {#autocommit} - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Автоматически выполнять [COMMIT](../../select/index.md#commit) после каждого выражения. - -### TablePathPrefix {#table-path-prefix} - -| Тип значения | По умолчанию | -| --- | --- | -| Строка | — | - -Добавить указанный префикс к путям таблиц внутри кластеров. Работает по принципу объединения путей в файловой системе: поддерживает ссылки на родительский каталог `..` и не требует добавления слеша справа. Например, - -```yql -PRAGMA TablePathPrefix = "home/yql"; -SELECT * FROM test; -``` - -Префикс не добавляется, если имя таблицы указано как абсолютный путь (начинается с /). - -### UDF {#udf} - -| Тип значения | По умолчанию | Статическая /
динамическая | -| --- | --- | --- | -| Строка | — | Статическая | -| Строка - имя префикса, добавляемого ко всем модулям | "" | Статическая | - -Импорт всех UDF из указанной приложенной к запросу скомпилированной под Linux x64 разделяемой библиотеки (.so). -При указании префикса, он добавляется перед названием всех загруженных модулей, например, CustomPrefixIp::IsIPv4 вместо Ip::IsIPv4. -Указание префикса позволяет подгрузить одну и ту же UDF разных версий. - -### UseTablePrefixForEach {#use-table-prefix-for-each} - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -`EACH` использует [TablePathPrefix](#table-path-prefix) для каждого элемента списка. - -### Warning {#warning} - -| Тип значения | По умолчанию | -| --- | --- | -| 1. Действие
2. Код предупреждения либо символ "*"| — | - -Действие: - -* `disable` — отключить; -* `error` — приравнять к ошибке; -* `default` — вернуть поведение по умолчанию. - -Код предупреждения возвращается вместе с самим текстом (в веб-интерфейсе отображается справа). - -Примеры: - -`PRAGMA Warning("error", "*");` -`PRAGMA Warning("disable", "1101");` -`PRAGMA Warning("default", "4503");` - -В данном случае все предупреждения будут считаться ошибками, за исключением предупреждение с кодом `1101`, которое будет отключено, и `4503`, которое будет обрабатываться по умолчанию (то есть останется предупреждением). Поскольку предупреждения могут добавляться в новых релизах YQL, следует с осторожностью пользоваться конструкцией `PRAGMA Warning("error", "*");` (как минимум покрывать такие запросы автотестами). - -{% include [issue_protos.md](issue_protos.md) %} - -### Greetings {#greetings} - -| Тип значения | По умолчанию | -| --- | --- | -| Текст | — | - -Выдать указанный текст в качестве Info сообщения запроса. - -Пример: -`PRAGMA Greetings("It's a good day!");` - -### WarningMsg {#warningmsg} - -| Тип значения | По умолчанию | -| --- | --- | -| Текст | — | - -Выдать указанный текст в качестве Warning сообщения запроса. - -Пример: -`PRAGMA WarningMsg("Attention!");` - -{% if feature_mapreduce %} - -### DqEngine {#dqengine} - -| Тип значения | По умолчанию | -| --- | --- | -| Строка disable/auto/force | "auto" | - -При значении "auto" включает новый движок вычислений. Вычисления по возможности делаются без создания map/reduce операций. При значении "force" вычисление идет в новый движок безусловно. -{% endif %} - -{% if feature_join %} - -### SimpleColumns {#simplecolumns} - -`SimpleColumns` / `DisableSimpleColumns` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | true | - -При использовании `SELECT foo.* FROM ... AS foo` убрать префикс `foo.` у имен результирующих колонок. - -Работает в том числе и для [JOIN](../../join.md), но в этом случае имеет право упасть в случае конфликта имен (который можно разрешить с помощью [WITHOUT](../../select/without.md) и переименования колонок). Для JOIN в режиме SimpleColumns производится неявный Coalesce для ключевых колонок: запрос `SELECT * FROM T1 AS a JOIN T2 AS b USING(key)` в режиме SimpleColumns работает как `SELECT a.key ?? b.key AS key, ... FROM T1 AS a JOIN T2 AS b USING(key)` - -### CoalesceJoinKeysOnQualifiedAll - -`CoalesceJoinKeysOnQualifiedAll` / `DisableCoalesceJoinKeysOnQualifiedAll` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | true | - -Управляет неявным Coalesce для ключевых колонок `JOIN` в режиме SimpleColumns. Если флаг установлен, то Coalesce ключевых колонок происходит при наличии хотя бы одного выражения вида `foo.*` или `*` в SELECT - например `SELECT a.* FROM T1 AS a JOIN T2 AS b USING(key)`. Если флаг сброшен, то Coalesce ключей JOIN происходит только при наличии '*' после `SELECT` - -### StrictJoinKeyTypes - -`StrictJoinKeyTypes` / `DisableStrictJoinKeyTypes` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Если флаг установлен, то [JOIN](../../join.md) будет требовать строгого совпадения типов ключей. -По умолчанию JOIN предварительно конвертирует ключи к общему типу, что может быть нежелательно с точки зрения производительности. -StrictJoinKeyTypes является [scoped](../../pragma.md#pragmascope) настройкой. - -{% endif %} - -### AnsiInForEmptyOrNullableItemsCollections - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Наличие этой прагмы приводит поведение оператора `IN` в соответствие со стандартом в случае наличия `NULL` в левой или правой части оператора `IN`. Также изменено поведение `IN` в случае, когда справа был Tuple с элементами разных типов. Примеры: - -`1 IN (2, 3, NULL) = NULL (было Just(False))` -`NULL IN () = Just(False) (было NULL)` -`(1, null) IN ((2, 2), (3, 3)) = Just(False) (было NULL)` - -Подробнее про поведение `IN` при наличии `NULL`ов в операндах можно почитать [здесь](../../expressions.md#in). Явным образом выбрать старое поведение можно указав прагму `DisableAnsiInForEmptyOrNullableItemsCollections`. Если никакой прагмы не задано, то выдается предупреждение и работает старый вариант. - -### AnsiRankForNullableKeys - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Приводит поведение RANK/DENSE_RANK в соответствие со стандартом при наличии опциональных типов в ключах сортировки окна или в аргументе этих оконных функций. А именно: - -* типом результата всегда является Uint64, а не Uint64?; -* null-ы в ключах считаются равными друг другу (текущая реализация возвращает NULL). - -Явным образом выбрать старое поведению можно указав прагму `DisableAnsiRankForNullableKeys`. Если никакой прагмы не задано, то выдается предупреждение и работает старый вариант. - -### AnsiCurrentRow - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Приводит неявное задание рамки окна при наличии ORDER BY в соответствие со стандартом. -Если AnsiCurrentRow не установлен, то окно `(ORDER BY key)` эквивалентно `(ORDER BY key ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. -Стандарт же требует, чтобы такое окно вело себя как `(ORDER BY key RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`. -Разница состоит в трактовке `CURRENT ROW`. В режиме `ROWS` `CURRENT ROW` трактуется буквально – текущая строка в партиции. -А в режиме `RANGE` конец рамки `CURRENT ROW` означает "последняя строка в партиции с ключом сортировки, равным текущей строке". - -### OrderedColumns {#orderedcolumns} - -`OrderedColumns` / `DisableOrderedColumns` - -Выводить [порядок колонок](../../select/index.md#orderedcolumns) в SELECT/JOIN/UNION ALL и сохранять его при записи результатов. По умолчанию порядок колонок не определен. - -### PositionalUnionAll {#positionalunionall} - -Включить соответствующий стандарту поколоночный режим выполнения [UNION ALL](../../select/index.md#unionall). При этом автоматически включается -[упорядоченность колонок](#orderedcolumns). - -### RegexUseRe2 - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Использовать Re2 UDF вместо Pcre для выполнения SQL операторов `REGEX`,`MATCH`,`RLIKE`. Re2 UDF поддерживает корректную обработку Unicode-символов в отличие от используемой по умолчанию Pcre UDF. - -### ClassicDivision - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | true | - -В классическом варианте результат целочисленного деления остаётся целочисленным (по умолчанию). -Если отключить — результат всегда становится Double. -ClassicDivision является [scoped](../../pragma.md#pragmascope) настройкой. - -### CheckedOps - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -При включенном режиме если в результате выполнения агрегационных функций SUM/SUM_IF, бинарных операций `+`,`-`,`*`,`/`,`%` или унарной операции `-` над целыми числами происходит выход за границы целевого типа аргументов или результата, то возвращается `NULL`. -Если отключить - переполнение не проверяется. -Не влияет на операции с числами с плавающей точкой или `Decimal`. -CheckedOps является [scoped](../../pragma.md#pragmascope) настройкой. - -### UnicodeLiterals - -`UnicodeLiterals`/`DisableUnicodeLiterals` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -При включенном режиме строковые литералы без суффиксов вида "foo"/'bar'/@@multiline@@ будут иметь тип `Utf8`, при выключенном - `String`. -UnicodeLiterals является [scoped](../../pragma.md#pragmascope) настройкой. - -### WarnUntypedStringLiterals - -`WarnUntypedStringLiterals`/`DisableWarnUntypedStringLiterals` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -При включенном режиме для строковых литералов без суффиксов вида "foo"/'bar'/@@multiline@@ будет генерироваться предупреждение. Его можно подавить, если явно выбрать суффикс `s` для типа `String`, либо `u` для типа `Utf8`. -WarnUntypedStringLiterals является [scoped](../../pragma.md#pragmascope) настройкой. - -### AllowDotInAlias - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Разрешить использовать точку в именах результирующих колонок. По умолчанию отключено, т.к. дальнейшее использование таких колонок в JOIN полностью не реализовано. - -### WarnUnnamedColumns - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Генерировать предупреждение если для безымянного выражения в `SELECT` было автоматически сгенерировано имя колонки (вида `column[0-9]+`). - -### GroupByLimit - -| Тип значения | По умолчанию | -| --- | --- | -| Положительное число | 32 | - -Увеличение лимита на число группировок в [GROUP BY](../../group_by.md). - -{% if feature_group_by_rollup_cube %} - -### GroupByCubeLimit - -| Тип значения | По умолчанию | -| --- | --- | -| Положительное число | 5 | - -Увеличение лимита на число размерностей [GROUP BY](../../group_by.md#rollup-cube-group-sets). - -Использовать нужно аккуратно, так как вычислительная сложность запроса растет экспоненциально по отношению к числу размерностей. - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/issue_protos.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/issue_protos.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/ydb.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/ydb.md deleted file mode 100644 index 551575f8d77d..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/ydb.md +++ /dev/null @@ -1,23 +0,0 @@ -## YDB - -### `ydb.CostBasedOptimizationLevel` {#costbasedoptimizationlevel} - -| Уровень | Поведение оптимизатора | -| ------- | ---------------------- | -| 0 | Cтоимостный оптимизатор выключен | -| 1 | Cтоимостный оптимизатор выключен, считаются предсказания оптимизатора | -| 2 | Cтоимостный оптимизатор включается только для запросов, где участвуют {% if backend_name == "YDB" and oss == true %}[колоночные таблицы](../../../../../concepts/glossary.md#column-oriented-table){% else %}колоночные таблицы{% endif %} | -| 3 | Cтоимостный оптимизатор включается для всех запросов, но для строковых таблиц предпочитается алгоритм джоина LookupJoin | -| 4 | Cтоимостный оптимизатор включен для всех запросов | - -{% if tech %} - -### `kikimr.IsolationLevel` - -| Тип значения | По умолчанию | -| --- | --- | -| Serializable, ReadCommitted, ReadUncommitted или ReadStale. | Serializable | - -Экспериментальная pragma, позволяет ослабить уровень изоляции текущей транзакции в YDB. - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/yson.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/yson.md deleted file mode 100644 index 02871997d276..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/pragma/yson.md +++ /dev/null @@ -1,27 +0,0 @@ -## Yson - -Управление поведением Yson UDF по умолчанию, подробнее см. в [документации по ней](../../../udf/list/yson.md) и в частности [Yson::Options](../../../udf/list/yson.md#ysonoptions). - -### `yson.AutoConvert` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Автоматическое конвертация значений в требуемый тип данных во всех вызовах Yson UDF, в том числе и неявных. - -### `yson.Strict` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | true | - -Управление строгим режимом во всех вызовах Yson UDF, в том числе и неявных. Без значения или при значении `"true"` - включает строгий режим. Со значением `"false"` - отключает. - -### `yson.DisableStrict` - -| Тип значения | По умолчанию | -| --- | --- | -| Флаг | false | - -Инвертированная версия `yson.Strict`. Без значения или при значении `"true"` - отключает строгий режим. Со значением `"false"` - включает. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/replace_into.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/replace_into.md deleted file mode 100644 index cb5042bb9aa0..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/replace_into.md +++ /dev/null @@ -1,35 +0,0 @@ -# REPLACE INTO - -{% if oss == true and backend_name == "YDB" %} - -{% note warning %} - -{% include [OLAP_not_allow_text](../../../../_includes/not_allow_for_olap_text.md) %} - -{% include [ways_add_data_to_olap](../../../../_includes/ways_add_data_to_olap.md) %} - -{% endnote %} - -{% endif %} - -В отличие от [`INSERT INTO`](../insert_into.md) и [`UPDATE`](../update.md), запросы [`UPSERT INTO`](../upsert_into.md) и `REPLACE INTO` не требуют предварительного чтения данных, поэтому выполняются быстрее. `REPLACE INTO` сохраняет данные в {% if backend_name == "YDB" and oss == true %}строковую таблицу{% else %}таблицу{% endif %} с перезаписью строк по первичному ключу.{% if feature_mapreduce %} Таблица по имени ищется в базе данных, заданной оператором [USE](../use.md).{% endif %} Если заданный первичный ключ отсутствует, в таблицу будет добавлена новая строка. Если задан существующий `PRIMARY_KEY`, строка будет перезаписана. При этом значения столбцов, не участвующих в операции, заменяются на значения по умолчанию. - -## Примеры - -* Задание значений для `REPLACE INTO` c помощью `VALUES`: - -```yql - REPLACE INTO my_table (Key1, Key2, Value2) VALUES - (1u, "One", 101), - (2u, "Two", 102); - COMMIT; - ``` - -* Получение значений для `REPLACE INTO` с помощью выборки `SELECT`: - -```yql - REPLACE INTO my_table - SELECT Key AS Key1, "Empty" AS Key2, Value AS Value1 - FROM my_table1; - COMMIT; - ``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/resource_pool_classifier_parameters.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/resource_pool_classifier_parameters.md deleted file mode 100644 index 8601ae1968c7..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/resource_pool_classifier_parameters.md +++ /dev/null @@ -1,3 +0,0 @@ -* `RANK` (Int64) — опциональное поле, задающее порядок выбора классификатора пула ресурсов. Если значение не указано, берётся максимальный существующий `RANK` и к нему прибавляется 1000. Допустимые значения: уникальное число в диапазоне $[0, 2^{63}-1]$. -* `RESOURCE_POOL` (String) — обязательное поле, задающее имя пула ресурсов, в который будут отправлены запросы, удовлетворяющие критериям классификатора. -* `MEMBER_NAME` (String) — опциональное поле, определяющее, какой пользователь или группа пользователей будут отправлены в указанный пул ресурсов. Если поле не указано, классификатор игнорирует `MEMBER_NAME`, и классификация осуществляется по другим признакам. \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/calc.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/calc.md deleted file mode 100644 index 7c1e24cd17a2..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/calc.md +++ /dev/null @@ -1,15 +0,0 @@ -# SELECT - -Возвращает результат вычисления выражений, указанных после `SELECT`. - -Может использоваться в сочетании с другими операциями для получения иного эффекта. - -## Примеры - -```yql -SELECT "Hello, world!"; -``` - -```yql -SELECT 2 + 2; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/column_order.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/column_order.md deleted file mode 100644 index c5ca7a4fb463..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/column_order.md +++ /dev/null @@ -1,23 +0,0 @@ -## Порядок колонок в YQL {#orderedcolumns} - -В стандартном SQL порядок колонок указанных в проекции (в `SELECT`) имеет значение. Помимо того, что порядок колонок должен сохраняться при отображении результатов запроса или при записи в новую таблицу, некоторые конструкции SQL этот порядок используют. -Это относится в том числе к [UNION ALL](union_all.md) и к позиционному [ORDER BY](order_by.md) (ORDER BY ordinal). - -По умолчанию в YQL порядок колонок игнорируется: - -* порядок колонок в выходных таблицах и в результатах запроса не определен -* схема данных результата `UNION ALL` выводится по именам колонок, а не по позициям - -При включении `PRAGMA OrderedColumns;` порядок колонок сохраняется в результатах запроса и выводится из порядка колонок во входных таблицах по следующим правилам: - -* `SELECT` с явным перечислением колонок задает соответствующий порядок; -* `SELECT` со звездочкой (`SELECT * FROM ...`) наследует порядок из своего входа; - -{% if feature_join %} - -* порядок колонок после [JOIN](../../join.md): сначала колонки левой стороны, потом правой. Если порядок какой-либо из сторон присутствующей в выходе `JOIN` не определен, порядок колонок результата также не определен; - -{% endif %} - -* порядок `UNION ALL` зависит от режима выполнения [UNION ALL](union_all.md); -* порядок колонок для [AS_TABLE](from_as_table.md) не определен; diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/combining_queries.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/combining_queries.md deleted file mode 100644 index ce93ab1b14bc..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/combining_queries.md +++ /dev/null @@ -1,26 +0,0 @@ -### Комбинация запросов {#combining-queries} - -Результаты нескольких SELECT (или подзапросов) могут быть объединены с помощью ключевых слов `UNION` и `UNION ALL`. - -```yql -query1 UNION [ALL] query2 (UNION [ALL] query3 ...) -``` - -Объединение более двух запросов интерпретируется как левоассоциативная операция, то есть - -```yql -query1 UNION query2 UNION ALL query3 -``` - -интерпретируется как - -```yql -(query1 UNION query2) UNION ALL query3 -``` - -При наличии `ORDER BY/LIMIT/DISCARD/INTO RESULT` в объединяемых подзапросах применяются следующие правила: - -* `ORDER BY/LIMIT/INTO RESULT` допускается только после последнего подзапроса; -* `DISCARD` допускается только перед первым подзапросом; -* указанные операторы действуют на результат `UNION [ALL]`, а не на подзапрос; -* чтобы применить оператор к подзапросу, подзапрос необходимо взять в скобки. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/execution.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/execution.md deleted file mode 100644 index 16f6faa32594..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/execution.md +++ /dev/null @@ -1,23 +0,0 @@ -## Процедура выполнения SELECT {#selectexec} - -Результат запроса `SELECT` вычисляется следующим образом: - -* определяется набор входных таблиц – вычисляются выражения после [FROM](../../select/from.md); -* к входным таблицам применяется [SAMPLE](sample.md) / [TABLESAMPLE](sample.md) -* выполняется [FLATTEN COLUMNS](../../flatten.md#flatten-columns) или [FLATTEN BY](../../flatten.md); алиасы, заданные во `FLATTEN BY`, становятся видны после этой точки; -{% if feature_join %} -* выполняются все [JOIN](../../join.md); -{% endif %} -* к полученным данным добавляются (или заменяются) колонки, заданные в [GROUP BY ... AS ...](../../group_by.md); -* выполняется [WHERE](where.md) — все данные не удовлетворяющие предикату отфильтровываются; -* выполняется [GROUP BY](../../group_by.md), вычисляются значения агрегатных функций; -* выполняется фильтрация [HAVING](../../group_by.md#having); -{% if feature_window_functions %} -* вычисляются значения [оконных функций](../../window.md); -{% endif %} -* вычисляются выражения в `SELECT`; -* выражениям в `SELECT` назначаются имена заданные алиасами; -* к полученным таким образом колонкам применяется top-level [DISTINCT](distinct.md); -* таким же образом вычисляются все подзапросы в [UNION ALL](union_all.md), выполняется их объединение (см. [PRAGMA AnsiOrderByLimitInUnionAll](../../pragma.md#pragmas)); -* выполняется сортировка согласно [ORDER BY](order_by.md); -* к полученному результату применяются [OFFSET и LIMIT](limit_offset.md). \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/federated_with.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/federated_with.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/functional_tables.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/functional_tables.md deleted file mode 100644 index 5172c20b76bb..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/functional_tables.md +++ /dev/null @@ -1,113 +0,0 @@ -# Обращение к нескольким таблицам в одном запросе - -В стандартном SQL для выполнения запроса по нескольким таблицам используется [UNION ALL](../../select/union.md#union_all), который объединяет результаты двух и более `SELECT`. Это не совсем удобно для сценария использования, в котором требуется выполнить один и тот же запрос по нескольким таблицам (например, содержащим данные на разные даты). В YQL, чтобы было удобнее, в `SELECT` после `FROM` можно указывать не только одну таблицу или подзапрос, но и вызывать встроенные функции, позволяющие объединять данные нескольких таблиц. - -Для этих целей определены следующие функции: - -```CONCAT(`table1`, `table2`, `table3` VIEW view_name, ...)``` — объединяет все перечисленные в аргументах таблицы. - -`EACH($list_of_strings)` или `EACH($list_of_strings VIEW view_name)` — объединяет все таблицы, имена которых перечислены в списке строк. Опционально можно передать несколько списков в отдельных аргументах по аналогии с `CONCAT`. - -```RANGE(`prefix`, `min`, `max`, `suffix`, `view`)``` — объединяет диапазон таблиц. Аргументы: - -* prefix — каталог для поиска таблиц, указывается без завершающего слеша. Единственный обязательный аргумент, если указан только он, то используются все таблицы в данном каталоге. -* min, max — следующие два аргумента задают диапазон имен для включения таблиц. Диапазон инклюзивный с обоих концов. Если диапазон не указан, используются все таблицы в каталоге prefix. Имена таблиц или директорий, находящихся в указанной в prefix директории, сравниваются с диапазоном `[min, max]` лексикографически, а не конкатенируются, таким образом важно указывать диапазон без лидирующих слешей. -* suffix — имя таблицы. Ожидается без начального слеша. Если suffix не указан, то аргументы `[min, max]` задают диапазон имен таблиц. Если suffix указан, то аргументы `[min, max]` задают диапазон папок, в которых существует таблица с именем, указанным в аргументе suffix. - -```LIKE(`prefix`, `pattern`, `suffix`, `view`)` и `REGEXP(`prefix`, `pattern`, `suffix`, `view`)``` — аргумент pattern задается в формате, аналогичном одноименным бинарным операторам: [LIKE](../../expressions.md#like) и [REGEXP](../../expressions.md#regexp). - -```FILTER(`prefix`, `callable`, `suffix`, `view`)``` — аргумент callable должен являться вызываемым выражением с сигнатурой `(String)->Bool`, который будет вызван для каждой таблицы/подкаталога в каталоге prefix. В запросе будут участвовать только те таблицы, для которых вызываемое значение вернуло `true`. В качестве вызываемого значения удобнее всего использовать [лямбда функции](../../expressions.md#lambda){% if yql == true %}, либо UDF на [Python](../../../udf/python.md) или [JavaScript](../../../udf/javascript.md){% endif %}. - -{% note warning %} - -Порядок, в котором будут объединены таблицы, всеми вышеперечисленными функциями не гарантируется. - -Список таблиц вычисляется **до** запуска самого запроса. Поэтому созданные в процессе запроса таблицы не попадут в результаты функции. - -{% endnote %} - -По умолчанию схемы всех участвующих таблиц объединяются по правилам [UNION ALL](../../select/index.md#union_all). Если объединение схем не желательно, то можно использовать функции с суффиксом `_STRICT`, например `CONCAT_STRICT` или `RANGE_STRICT`, которые работают полностью аналогично оригинальным, но считают любое расхождение в схемах таблиц ошибкой. - -Для указания кластера объединяемых таблиц нужно указать его перед названием функции. - -Все аргументы описанных выше функций могут быть объявлены отдельно через [именованные выражения](../../expressions.md#named-nodes). В этом случае в них также допустимы и простые выражения посредством неявного вызова [EvaluateExpr](../../../builtins/basic.md#evaluate_expr_atom). - -Имя исходной таблицы, из которой изначально была получена каждая строка, можно получить при помощи функции [TablePath()](../../../builtins/basic.md#tablepath). - -## Примеры - -```yql -USE some_cluster; -SELECT * FROM CONCAT( - `table1`, - `table2`, - `table3`); -``` - -```yql -USE some_cluster; -$indices = ListFromRange(1, 4); -$tables = ListMap($indices, ($index) -> { - RETURN "table" || CAST($index AS String); -}); -SELECT * FROM EACH($tables); -- идентично предыдущему примеру -``` - -```yql -USE some_cluster; -SELECT * FROM RANGE(`my_folder`); -``` - -```yql -SELECT * FROM some_cluster.RANGE( -- Кластер можно указать перед названием функции - `my_folder`, - `from_table`, - `to_table`); -``` - -```yql -USE some_cluster; -SELECT * FROM RANGE( - `my_folder`, - `from_folder`, - `to_folder`, - `my_table`); -``` - -```yql -USE some_cluster; -SELECT * FROM RANGE( - `my_folder`, - `from_table`, - `to_table`, - ``, - `my_view`); -``` - -```yql -USE some_cluster; -SELECT * FROM LIKE( - `my_folder`, - "2017-03-%" -); -``` - -```yql -USE some_cluster; -SELECT * FROM REGEXP( - `my_folder`, - "2017-03-1[2-4]?" -); -``` - -```yql -$callable = ($table_name) -> { - return $table_name > "2017-03-13"; -}; - -USE some_cluster; -SELECT * FROM FILTER( - `my_folder`, - $callable -); -``` \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/s3_with.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/s3_with.md deleted file mode 100644 index bcde20496639..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/s3_with.md +++ /dev/null @@ -1,6 +0,0 @@ -* `FORMAT` - формат хранимых данных в файловых хранилищах в [федеративных запросах](../../../../../concepts/federated_query/s3/formats.md). Допустимые значения: `csv_with_names`, `tsv_with_names`, `json_list`, `json_each_row`, `json_as_string`, `parquet`, `raw`. -* `COMPRESSION` - формат сжатия файлов в файловых хранилищах в [федеративных запросах](../../../../../concepts/federated_query/s3/partition_projection). Допустимые значения: [gzip](https://ru.wikipedia.org/wiki/Gzip), [zstd](https://ru.wikipedia.org/wiki/Zstandard), [lz4](https://ru.wikipedia.org/wiki/LZ4), [brotli](https://ru.wikipedia.org/wiki/Brotli), [bzip2](https://ru.wikipedia.org/wiki/Bzip2), [xz](https://ru.wikipedia.org/wiki/XZ). -* `PARTITIONED_BY` - список [колонок партиционирования](../../../../../concepts/federated_query/s3/partitioning.md) данных в файловых хранилищах в федеративных запросах. Содержит список колонок в порядке их размещения в файловом хранилище. -* `projection.enabled` - флаг включения [расширенного партиционирования данных](../../../../../concepts/federated_query/s3/partition_projection.md). Допустимые значения: `true`, `false`. -* `projection..type` - тип поля [расширенного партиционирования данных](../../../../../concepts/federated_query/s3/partition_projection.md). Допустимые значения: `integer`, `enum`, `date`. -* `projection..` - расширенные свойства поля [расширенного партиционирования данных](../../../../../concepts/federated_query/s3/partition_projection.md). diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/union.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/union.md deleted file mode 100644 index 219285f56005..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/union.md +++ /dev/null @@ -1,13 +0,0 @@ -## UNION {#union} - -Объединение результатов нескольких подзапросов с удалением дубликатов. -Поведение идентично последовательному исполнению `UNION ALL` и `SELECT DISTINCT *`. -См. [UNION ALL](../../select/union.md#union-all) для информации о деталях поведения. - -### Примеры - -```yql -SELECT key FROM T1 -UNION -SELECT key FROM T2 -- возвращает таблицу различных ключей, лежащих хотя бы в одной из исходных таблиц -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/union_all_rules.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/union_all_rules.md deleted file mode 100644 index 8bc9561e1098..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/union_all_rules.md +++ /dev/null @@ -1,4 +0,0 @@ -* в результирующую таблицу включаются все колонки, которые встречались хоть в одной из входных таблиц; -* если колонка присутствовала не во всех входных таблицах, то ей автоматически присваивается [опциональный тип данных](../../../types/optional.md) (допускающий значение `NULL`); -* если колонка в разных входных таблицах имела разные типы, то выводится общий тип (наиболее широкий); -* если колонка в разных входных таблицах имела разнородный тип, например строку и число, то это считается ошибкой. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/with.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/with.md deleted file mode 100644 index 240fd8210345..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/_includes/select/with.md +++ /dev/null @@ -1,57 +0,0 @@ -# WITH - -Задается после источника данных во `FROM` и используется для указания дополнительных подсказок использования {% if backend_name == "YDB" %}строковых и колоночных{% endif %} таблиц. Подсказки нельзя задать для подзапросов и [именованных выражений](../../expressions.md#named-nodes). - -Поддерживаются следующие значения: - -* `INFER_SCHEMA` — задает флаг вывода схемы таблицы. Поведение аналогично заданию [прагмы yt.InferSchema](../../pragma.md#inferschema), только для конкретного источника данных. Можно задать число строк для выведения (число от 1 до 1000). -* `FORCE_INFER_SCHEMA` — задает флаг вывода схемы таблицы. Поведение аналогично заданию [прагмы yt.ForceInferSchema](../../pragma.md#inferschema), только для конкретного источника данных. Можно задать число строк для выведения (число от 1 до 1000). -* `DIRECT_READ` — подавляет работу некоторых оптимизаторов и заставляет использовать содержимое таблицы как есть. Поведение аналогично заданию отладочной [прагмы DirectRead](../../pragma.md#debug), только для конкретного источника данных. -* `INLINE` — указание на то, что содержимое таблицы небольшое и нужно использовать его представление в памяти для обработки запроса. Реальный объем таблицы при этом не контролируется, и если он большой, то запрос может упасть по превышению памяти. -* `UNORDERED` — подавляет использование исходной сортировки таблицы. -* `XLOCK` — указание на то, что нужно брать эксклюзивный лок на таблицу. Полезен, когда чтение таблицы происходит на стадии обработки [метапрограммы запроса](../../action.md), а затем ее содержимое обновляется в основном запросе. Позволяет избежать потери данных, если между исполнением фазы метапрограммы и основной частью запроса внешний процесс успел изменить таблицу. -* `SCHEMA` type — указание на то, что следует использовать указанную схему таблицы целиком, игнорируя схему в метаданных. -* `COLUMNS` type — указание на то, что следует использовать указанные типы для колонок, чьи имена совпадают с именами колонок таблицы в метаданных, а также какие колонки дополнительно присутствуют в таблице. -* `IGNORETYPEV3`, `IGNORE_TYPE_V3` — задает флаг игнорирования type_v3 типов в таблице. Поведение аналогично заданию [прагмы yt.IgnoreTypeV3](../../pragma.md#ignoretypev3), только для конкретного источника данных. - -{% if feature_federated_queries %} - -При работе с [внешними файловыми источниками данных](../../../../../concepts/datamodel/external_data_source.md) можно дополнительно указывать ряд параметров: - -{% include [s3_with](s3_with.md) %} - -{% endif %} - -При задании подсказок `SCHEMA` и `COLUMNS` в качестве значения типа type должен быть задан тип [структуры](../../../types/containers.md). - -{% if feature_bulk_tables %} - -Если задана подсказка `SCHEMA`, то при использовании табличных функций [EACH](#each), [RANGE](#range), [LIKE](#like), [REGEXP](#regexp), [FILTER](#filter) допускается пустой список таблиц, который обрабатывается как пустая таблица с колонками, описанными в `SCHEMA`. - -{% endif %} - -## Примеры - -```yql -SELECT key FROM my_table WITH INFER_SCHEMA; -SELECT key FROM my_table WITH FORCE_INFER_SCHEMA="42"; -``` - -```yql -$s = (SELECT COUNT(*) FROM my_table WITH XLOCK); - -INSERT INTO my_table WITH TRUNCATE -SELECT EvaluateExpr($s) AS a; -``` - -```yql -SELECT key, value FROM my_table WITH SCHEMA Struct; -``` - -```yql -SELECT key, value FROM my_table WITH COLUMNS Struct; -``` - -```yql -SELECT key, value FROM EACH($my_tables) WITH SCHEMA Struct>; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/action.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/action.md deleted file mode 100644 index 97797f79b143..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/action.md +++ /dev/null @@ -1,11 +0,0 @@ -# ACTION - -{% include [x](_includes/action/define_do.md) %} - -{% include [x](_includes/action/begin.md) %} - -{% if feature_mapreduce %} - -{% include [x](_includes/action/evaluate.md) %} - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-resource-pool.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-resource-pool.md deleted file mode 100644 index df1aeb77e917..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/alter-resource-pool.md +++ /dev/null @@ -1,55 +0,0 @@ -# ALTER RESOURCE POOL - -`ALTER RESOURCE POOL` изменяет определение [пула ресурсов](../../../concepts/glossary.md#resource-pool.md). - -## Синтаксис - -### Изменение параметров - -Синтаксис для изменения любого параметра пула ресурсов выглядит следующим образом: - -```yql -ALTER RESOURCE POOL SET ( = ); -``` - -`` — имя параметра, `` — его новое значение. - -Например, такая команда включит ограничение на число параллельных запросов, равное 100: - -```yql -ALTER RESOURCE POOL olap SET (CONCURRENT_QUERY_LIMIT = "100"); -``` - -### Сброс параметров - -Команда для сброса параметра пула ресурсов выглядит следующим образом: - -```yql -ALTER RESOURCE POOL RESET (); -``` - -`````` — имя параметра. - -Например, такая команда сбросит настройки `TOTAL_CPU_LIMIT_PERCENT_PER_NODE` для пула ресурсов: - -```yql -ALTER RESOURCE POOL olap RESET (TOTAL_CPU_LIMIT_PERCENT_PER_NODE); -``` - -## Разрешения - -Требуется [разрешение](grant.md#permissions-list) `ALTER SCHEMA` на пул ресурсов в директории `.metadata/workload_manager/pools`, пример выдачи такого разрешения: - -```yql -GRANT 'ALTER SCHEMA' ON `.metadata/workload_manager/pools/olap_pool` TO `user1@domain`; -``` - -## Параметры - -{% include [x](_includes/resource_pool_parameters.md) %} - -## См. также - -* [{#T}](../../../dev/resource-consumption-management.md) -* [{#T}](create-resource-pool.md) -* [{#T}](drop-resource-pool.md) \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/commit.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/commit.md deleted file mode 100644 index 57f171ccc40b..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/commit.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/select/commit.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table.md deleted file mode 100644 index afc4f96ab9e1..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/create_table.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/create_table.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/declare.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/declare.md deleted file mode 100644 index c3b29c2de89c..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/declare.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/declare/general.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/delete.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/delete.md deleted file mode 100644 index 152f774f9f80..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/delete.md +++ /dev/null @@ -1,3 +0,0 @@ - -{% include [x](_includes/delete.md) %} - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/discard.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/discard.md deleted file mode 100644 index e00213ace769..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/discard.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/discard.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop_table.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop_table.md deleted file mode 100644 index d708dc5d9ef1..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/drop_table.md +++ /dev/null @@ -1,3 +0,0 @@ - -{% include [x](_includes/drop_table.md) %} - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/export_import.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/export_import.md deleted file mode 100644 index 874d843a7b72..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/export_import.md +++ /dev/null @@ -1,2 +0,0 @@ -{% include [x](_includes/export_import.md) %} - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/expressions.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/expressions.md deleted file mode 100644 index 559b6743c1fa..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/expressions.md +++ /dev/null @@ -1,32 +0,0 @@ -# Выражения - -{% include [x](_includes/expressions/concatenation.md) %} - -{% include [x](_includes/expressions/check-match.md) %} - -{% include [x](_includes/expressions/operators.md) %} - -{% include [x](_includes/expressions/is-null.md) %} - -{% include [x](_includes/expressions/is-distinct-from.md) %} - -{% include [x](_includes/expressions/between.md) %} - -{% include [x](_includes/expressions/in.md) %} - -{% include [x](_includes/expressions/as.md) %} - -{% include [x](_includes/expressions/cast.md) %} - -{% include [x](_includes/expressions/bitcast.md) %} - -{% include [x](_includes/expressions/case.md) %} - -{% include [x](_includes/expressions/named-nodes.md) %} - -{% include [x](_includes/expressions/tables.md) %} - -{% include [x](_includes/expressions/lambda.md) %} - -{% include [x](_includes/expressions/items-access.md) %} - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/flatten.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/flatten.md deleted file mode 100644 index 4068bae5b7e1..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/flatten.md +++ /dev/null @@ -1,7 +0,0 @@ -{% include [x](_includes/flatten/flatten_by.md) %} - -{% include [x](_includes/flatten/flatten_type_by.md) %} - -{% include [x](_includes/flatten/flatten_other_db.md) %} - -{% include [x](_includes/flatten/flatten_columns.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/group_by.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/group_by.md deleted file mode 100644 index b68596578bbe..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/group_by.md +++ /dev/null @@ -1,27 +0,0 @@ -{% if select_command == "SELECT STREAM" %} - - {% include [x](_includes/group_by/general_stream.md) %} - - {% include [x](_includes/group_by/having_stream.md) %} - -{% else %} - -{% include [x](_includes/group_by/general.md) %} - -{% include [x](_includes/group_by/session_window.md) %} - -{% if feature_group_by_rollup_cube %} - - {% include [x](_includes/group_by/rollup_cube_sets.md) %} - -{% endif %} - -{% include [x](_includes/group_by/distinct.md) %} - -{% include [x](_includes/group_by/compact.md) %} - -{% include [x](_includes/group_by/having.md) %} - -{% endif %} - - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/insert_into.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/insert_into.md deleted file mode 100644 index 1b0084b8bf2e..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/insert_into.md +++ /dev/null @@ -1,6 +0,0 @@ - -{% include [x](_includes/insert_into.md) %} - -{% include [x](_includes/insert_hints.md) %} - -{% include [x](_includes/insert_with.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/into_result.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/into_result.md deleted file mode 100644 index a4fa2e247ef2..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/into_result.md +++ /dev/null @@ -1,3 +0,0 @@ - -{% include [x](_includes/into_result.md) %} - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/join.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/join.md deleted file mode 100644 index cbef5bb3693e..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/join.md +++ /dev/null @@ -1,3 +0,0 @@ - -{% include [x](_includes/join.md) %} - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/lexer.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/lexer.md deleted file mode 100644 index 1b7534021033..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/lexer.md +++ /dev/null @@ -1,3 +0,0 @@ - -{% include [x](_includes/lexer.md) %} - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/not_yet_supported.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/not_yet_supported.md deleted file mode 100644 index 442e95d576a8..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/not_yet_supported.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/not_yet_supported.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/pragma.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/pragma.md deleted file mode 100644 index fe9a5ebabfc0..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/pragma.md +++ /dev/null @@ -1,17 +0,0 @@ -# PRAGMA - -{% include [x](_includes/pragma/definition.md) %} - -{% include [x](_includes/pragma/global.md) %} - -{% include [x](_includes/pragma/yson.md) %} - -{% include [x](_includes/pragma/files.md) %} - -{% if backend_name == "YDB" %} - -{% include [x](_includes/pragma/ydb.md) %} - -{% endif %} - -{% include [x](_includes/pragma/debug.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/process.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/process.md deleted file mode 100644 index 62b45707b1f5..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/process.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/process.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/reduce.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/reduce.md deleted file mode 100644 index 5885c8354c62..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/reduce.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/reduce.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/replace_into.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/replace_into.md deleted file mode 100644 index 66a3b3145e39..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/replace_into.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/replace_into.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select.md deleted file mode 100644 index 122079fa19b9..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select.md +++ /dev/null @@ -1,71 +0,0 @@ -# Синтаксис SELECT - -{% include [x](_includes/select/calc.md) %} - -{% include [x](_includes/select/from.md) %} - -{% if feature_secondary_index %} - - {% include [x](_includes/select/secondary_index.md) %} - -{% endif %} - -{% include [x](_includes/select/with.md) %} - -{% include [x](_includes/select/where.md) %} - -{% include [x](_includes/select/order_by.md) %} - -{% include [x](_includes/select/limit_offset.md) %} - -{% include [x](_includes/select/assume_order_by.md) %} - -{% include [x](_includes/select/sample.md) %} - -{% include [x](_includes/select/distinct.md) %} - -{% include [x](_includes/select/unique_distinct_hints.md) %} - -{% include [x](_includes/select/execution.md) %} - -{% include [x](_includes/select/column_order.md) %} - -{% include [x](_includes/select/combining_queries.md) %} - -{% include [x](_includes/select/union_all.md) %} - -{% include [x](_includes/select/union.md) %} - -{% include [x](_includes/select/commit.md) %} - -{% if feature_bulk_tables %} - - {% include [x](_includes/select/functional_tables.md) %} - -{% endif %} - -{% if yt %} - - {% include [x](_includes/select/folder.md) %} - - {% include [x](_includes/select/walk_folders.md) %} - -{% endif %} - -{% include [x](_includes/select/without.md) %} - -{% include [x](_includes/select/from_select.md) %} - -{% if feature_mapreduce %} - - {% include [x](_includes/select/view.md) %} - -{% endif %} - -{% if feature_temp_table %} - - {% include [x](_includes/select/temporary_table.md) %} - -{% endif %} - -{% include [x](_includes/select/from_as_table.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/assume_order_by.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/assume_order_by.md deleted file mode 100644 index 084e7e7c1ff7..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/assume_order_by.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/assume_order_by.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/distinct.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/distinct.md deleted file mode 100644 index 0f27bb32d78c..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/distinct.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/distinct.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/folder.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/folder.md deleted file mode 100644 index ef425dd99856..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/folder.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/folder.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/from_as_table.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/from_as_table.md deleted file mode 100644 index f840fecb5d66..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/from_as_table.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/from_as_table.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/from_select.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/from_select.md deleted file mode 100644 index 557bbeb8d469..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/from_select.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/from_select.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/index.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/index.md deleted file mode 100644 index 2055c2957d4a..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/index.md +++ /dev/null @@ -1,57 +0,0 @@ -{% include [x](../_includes/select/calc.md) %} - -{% include [x](../_includes/select/execution.md) %} - -{% include [x](../_includes/select/column_order.md) %} - -{% include [x](../_includes/select/combining_queries.md) %} - -{% include [x](../_includes/select/functional_tables.md) %} - -## Поддерживаемые конструкции в SELECT - -* [FROM](from.md) -* [FROM AS_TABLE](from_as_table.md) -* [FROM SELECT](from_select.md) -* [DISTINCT](distinct.md) -* [UNIQUE DISTINCT](unique_distinct_hints.md) -* [UNION](union.md) -* [WITH](with.md) -* [WITHOUT](without.md) -* [WHERE](where.md) -* [ORDER BY](order_by.md) -* [ASSUME ORDER BY](assume_order_by.md) -* [LIMIT OFFSET](limit_offset.md) -* [SAMPLE](sample.md) -* [TABLESAMPLE](sample.md) - -{% if yt %} - -* [FOLDER](folder.md) -* [WalkFolders](walk_folders.md) - -{% endif %} - -{% if feature_mapreduce %} - -* [VIEW](view.md) - -{% endif %} - -{% if feature_temp_table %} - -* [TEMPORARY TABLE](temporary_table.md) - -{% endif %} - -{% if feature_bulk_tables %} - -* [CONCAT](concat.md) - -{% endif %} - -{% if feature_secondary_index %} - -* [VIEW INDEX](secondary_index.md) - -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/limit_offset.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/limit_offset.md deleted file mode 100644 index bc0ca29fdf63..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/limit_offset.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/limit_offset.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/order_by.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/order_by.md deleted file mode 100644 index 01b1606a4b0d..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/order_by.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/order_by.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/sample.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/sample.md deleted file mode 100644 index 5996bdd2b8da..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/sample.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/sample.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/secondary_index.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/secondary_index.md deleted file mode 100644 index a31ea8141e18..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/secondary_index.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/secondary_index.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/temporary_table.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/temporary_table.md deleted file mode 100644 index 8e456affcca5..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/temporary_table.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/temporary_table.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/union.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/union.md deleted file mode 100644 index e6efaf9e6337..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/union.md +++ /dev/null @@ -1,11 +0,0 @@ -# Объединение результатов подзапросов (UNION) - -{% if oss == true and backend_name == "YDB" %} - -{% include [olap_warning_note](../../../../_includes/not_allow_for_olap_note.md) %} - -{% endif %} - -{% include [union](../_includes/select/union.md) %} - -{% include [union](../_includes/select/union_all.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/unique_distinct_hints.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/unique_distinct_hints.md deleted file mode 100644 index 68332b95e095..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/unique_distinct_hints.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/unique_distinct_hints.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/view.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/view.md deleted file mode 100644 index 7774fb111619..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/view.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/view.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/walk_folders.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/walk_folders.md deleted file mode 100644 index 8346b26c2db2..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/walk_folders.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/walk_folders.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/where.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/where.md deleted file mode 100644 index 8751d2c67233..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/where.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/where.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/with.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/with.md deleted file mode 100644 index b9252d16ac5f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/with.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/with.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/without.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/without.md deleted file mode 100644 index 8e9cc1c5660b..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select/without.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](../_includes/select/without.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select_stream.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/select_stream.md deleted file mode 100644 index 285d0df84077..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/select_stream.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/select_stream.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/subquery.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/subquery.md deleted file mode 100644 index 75c6ac92a808..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/subquery.md +++ /dev/null @@ -1,3 +0,0 @@ - -{% include [x](_includes/subquery.md) %} - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/update.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/update.md deleted file mode 100644 index 6b2cb43b7bba..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/update.md +++ /dev/null @@ -1,3 +0,0 @@ - -{% include [x](_includes/update.md) %} - diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/upsert_into.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/upsert_into.md deleted file mode 100644 index 7ca3636a7354..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/upsert_into.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/upsert_into.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/use.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/use.md deleted file mode 100644 index d35121c3930a..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/use.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/use.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/values.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/values.md deleted file mode 100644 index a5473cf9284a..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/values.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/values.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/syntax/window.md b/ydb/docs/ru/core/yql/reference/yql-core/syntax/window.md deleted file mode 100644 index c07321d69e7e..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/syntax/window.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/window.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/toc_m.yaml b/ydb/docs/ru/core/yql/reference/yql-core/toc_m.yaml deleted file mode 100644 index 35ad87ba4d80..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/toc_m.yaml +++ /dev/null @@ -1,2 +0,0 @@ -items: -- include: { mode: merge, path: yql-product/toc_product.yaml } diff --git a/ydb/docs/ru/core/yql/reference/yql-core/toc_product.yaml b/ydb/docs/ru/core/yql/reference/yql-core/toc_product.yaml deleted file mode 100644 index 8ed779c15e6f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/toc_product.yaml +++ /dev/null @@ -1,9 +0,0 @@ -title: YQL over {{ backend_name }} -# href: index.md -items: -- name: Типы данных - include: { mode: link, path: types/toc_i.yaml } -- name: Синтаксис - include: { mode: link, path: syntax/toc_i.yaml } -- name: Встроенные функции - include: { mode: link, path: builtins/toc_i.yaml } diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/datatypes_primitive_datetime.md b/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/datatypes_primitive_datetime.md deleted file mode 100644 index a9b97a78c532..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/datatypes_primitive_datetime.md +++ /dev/null @@ -1,9 +0,0 @@ -Тип | Описание | Примечания ------ | ----- | ----- -`Date` | Дата, точность до дней | Диапазон значений для всех временных типов кроме `Interval` - от нуля часов 01.01.1970 до нуля часов 01.01.2106. Внутреннее представление `Date` – беззнаковое целое 16 бит | -`Datetime` | Дата/время, точность до секунд | Внутреннее представление – беззнаковое целое 32 бит | -`Timestamp` | Дата/время, точность до микросекунд | Внутреннее представление – беззнаковое целое 64 бит | -`Interval` | Интервал времени (знаковый), точность до микросекунд | Диапазон значений – от -136 лет до +136 лет. Внутреннее представление – знаковое целое 64 бит. {% if feature_map_tables %}Не может быть использован в первичном ключе{% endif %} -`TzDate` | Дата с меткой временной зоны, точность до дней | Не поддерживается в столбцах таблиц -`TzDateTime` | Дата/время с меткой временной зоны, точность до секунд | Не поддерживается в столбцах таблиц -`TzTimestamp` | Дата/время с меткой временной зоны, точность до микросекунд | Не поддерживается в столбцах таблиц \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/datatypes_primitive_number.md b/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/datatypes_primitive_number.md deleted file mode 100644 index 785b348d9151..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/datatypes_primitive_number.md +++ /dev/null @@ -1,17 +0,0 @@ -Тип | Описание | Примечания ------ | ----- | ----- -`Bool` | Логическое значение. | -`Int8` | Целое число со знаком.
Допустимые значения: от –27 до 27–1. | -`Int16` | Целое число со знаком.
Допустимые значения: от –215 до 215–1. | -`Int32` | Целое число со знаком.
Допустимые значения: от –231 до 231–1. | -`Int64` | Целое число со знаком.
Допустимые значения: от –263 до 263–1. | -`Uint8` | Беззнаковое целое число.
Допустимые значения: от 0 до 28–1. | -`Uint16` | Беззнаковое целое число.
Допустимые значения: от 0 до 216–1. | -`Uint32` | Беззнаковое целое число.
Допустимые значения: от 0 до 232–1. | -`Uint64` | Беззнаковое целое число.
Допустимые значения: от 0 до 264–1. | -`Float` | Вещественное число с переменной точностью размером 4 байта. | {% if feature_map_tables %}Не может быть использован в первичном ключе{% endif %} -`Double` | Вещественное число с переменной точностью размером 8 байт. | {% if feature_map_tables %}Не может быть использован в первичном ключе{% endif %} -`Decimal` | Вещественное число с указанной точностью, до 35 десятичных знаков | {% if feature_map_tables %}При использовании в колонках таблиц точность фиксирована: Decimal (22,9).{% endif %} -{% if feature_map_tables %} -`DyNumber` | Бинарное представление вещественного числа точностью до 38 знаков.
Допустимые значения: положительные от 1×10-130 до 1×10126–1, отрицательные от -1×10126–1 до -1×10-130 и 0.
Совместим с типом `Number` AWS DynamoDB. Не рекомендуется для использования в {{ backend_name_lower }}-native приложениях. | -{% endif %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/datatypes_primitive_string.md b/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/datatypes_primitive_string.md deleted file mode 100644 index bf3f23e6f0a4..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/datatypes_primitive_string.md +++ /dev/null @@ -1,26 +0,0 @@ -Тип | Описание | Примечания ------ | ----- | ----- -`String` | Строка, может содержать произвольные бинарные данные | -`Utf8` | Текст в кодировке [UTF-8](https://en.wikipedia.org/wiki/UTF-8) | -`Json` | [JSON](https://en.wikipedia.org/wiki/JSON) в текстовом представлении|Не поддерживает возможность сравнения{% if feature_map_tables %}, не может быть использован в первичном ключе{% endif %} -`JsonDocument` | [JSON](https://en.wikipedia.org/wiki/JSON) в бинарном индексированном представлении | Не поддерживает возможность сравнения{% if feature_map_tables %}, не может быть использован в первичном ключе{% endif %} -`Yson` | [YSON](../yson.md) в текстовом или бинарном представлении | Не поддерживает возможность сравнения{% if feature_map_tables %}, не может быть использован в первичном ключе{% endif %} -`Uuid` | Универсальный идентификатор [UUID](https://tools.ietf.org/html/rfc4122) | - -{% note info "Ограничения на размер" %} - -Максимальный размер значения в ячейке {% if feature_map_tables %} неключевого столбца {% endif %} с любым строковым типом данных — 8 МБ. - -{% endnote %} - -В отличие от типа данных `Json`, который хранит исходное текстовое представление, переданное пользователем, `JsonDocument` использует бинарное индексированное представление. Важное отличие с точки зрения семантики состоит в том, что `JsonDocument` не сохраняет форматирование, порядок ключей в объектах и их дубликаты. - -За счет индексированного представления `JsonDocument` позволяет обходить документную модель с использованием `JsonPath` без необходимости парсинга всего содержимого. Это позволяет эффективно выполнять операции из [JSON API](../../builtins/json.md), уменьшая задержки и стоимость пользовательских запросов. Выполнение запросов над `JsonDocument` может быть до нескольких раз эффективнее в зависимости от типа нагрузки. - -Из-за добавленной избыточности `JsonDocument` менее эффективен в хранении. Дополнительные накладные расходы на хранение зависят от конкретного содержимого и в среднем составляют 20–30% от исходного объема. Сохранение данных в формате `JsonDocument` требует дополнительной конвертации из текстового представления, что делает его запись менее эффективной. Тем не менее, для большинства read-intensive сценариев, подразумевающих обработку данных из JSON, этот тип данных является предпочтительным и рекомендуется к использованию. - -{% note warning %} - -Для хранения чисел (JSON Number) в `JsonDocument`, а также для арифметических операций над ними в [JSON API](../../builtins/json.md) используется тип [Double](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). Возможна потеря точности при использовании нестандартных представлений чисел в исходном JSON-документе. - -{% endnote %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/primitive.md b/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/primitive.md deleted file mode 100644 index 214ac2562905..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/primitive.md +++ /dev/null @@ -1,149 +0,0 @@ -# Примитивные типы данных - - - -Термины «простые», «примитивные» и «элементарные» типы данных используются как синонимы. - -## Числовые типы {#numeric} - -{% include [datatypes](datatypes_primitive_number.md) %} - -## Строковые типы {#string} - -{% include [datatypes](datatypes_primitive_string.md) %} - -## Дата и время {#datetime} - -{% include [datatypes](datatypes_primitive_datetime.md) %} - -{% include [x](tz_date_types.md) %} - -## Приведение простых типов данных {#cast} - -### Явное приведение {#explicit-cast} - -Явное приведение при помощи [CAST](../../syntax/expressions.md#cast): - -#### Приведение к численным типам - -Тип | Bool | Int8 | Int16 | Int32 | Int64 | Uint8 | Uint16 | Uint32 | Uint64 | Float | Double | Decimal ---- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- -**Bool** | — | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Да1 | Нет -**Int8** | Да2 | — | Да | Да | Да | Да3 | Да3 | Да3 | Да3 | Да | Да | Да -**Int16** | Да2 | Да4 | — | Да | Да | Да3,4 | Да3 | Да3 | Да3 | Да | Да | Да -**Int32** | Да2 | Да4 | Да4 | — | Да | Да3,4 | Да3,4 | Да3 | Да3 | Да | Да | Да -**Int64** | Да2 | Да4 | Да4 | Да4 | — | Да3,4 | Да3,4 | Да3,4 | Да3 | Да | Да | Да -**Uint8** | Да2 | Да4 | Да | Да | Да | — | Да | Да | Да | Да | Да | Да -**Uint16** | Да2 | Да4 | Да4 | Да | Да | Да4 | — | Да | Да | Да | Да | Да -**Uint32** | Да2 | Да4 | Да4 | Да4 | Да | Да4 | Да4 | — | Да | Да | Да | Да -**Uint64** | Да2 | Да4 | Да4 | Да4 | Да4 | Да4 | Да4 | Да4 | — | Да | Да | Да -**Float** | Да2 | Да4 | Да4 | Да4 | Да4 | Да3,4 | Да3,4 | Да3,4 | Да3,4 | — | Да | Нет -**Double** | Да2 | Да4 | Да4 | Да4 | Да4 | Да3,4 | Да3,4 | Да3,4 | Да3,4 | Да | — | Нет -**Decimal** | Нет | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | — -**String** | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да -**Utf8** | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да | Да -**Json** | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет -**Yson** | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Да5 | Нет -**Uuid** | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет | Нет -**Date** | Нет | Да4 | Да4 | Да | Да | Да4 | Да | Да | Да | Да | Да | Да | Нет -**Datetime** | Нет | Да4 | Да4 | Да4 | Да | Да4 | Да4 | Да | Да | Да | Да | Нет -**Timestamp** | Нет | Да4 | Да4 | Да4 | Да4 | Да4 | Да4 | Да4 | Да | Да | Да | Нет -**Interval** | Нет | Да4 | Да4 | Да4 | Да | Да3,4 | Да3,4 | Да3,4 | Да3 | Да | Да | Нет - -1 `True` преобразуется в `1`, `False` преобразуется в `0`. -2 Любое значение кроме `0` преобразуется в `True`, `0` преобразуется в `False`. -3 Возможно только в случае неотрицательного значения. -4 Возможно только в случае попадания в диапазон допустимых значений. -5 При помощи встроенной функции [Yson::ConvertTo](../../udf/list/yson.md#ysonconvertto). - -#### Приведение к типам данных даты и времени - -Тип | Date | Datetime | Timestamp | Interval ---- | --- | --- | --- | --- -**Bool** | Нет | Нет | Нет | Нет -**Int8** | Да | Да | Да | Да -**Int16** | Да | Да | Да | Да -**Int32** | Да | Да | Да | Да -**Int64** | Да | Да | Да | Да -**Uint8** | Да | Да | Да | Да -**Uint16** | Да | Да | Да | Да -**Uint32** | Да | Да | Да | Да -**Uint64** | Да | Да | Да | Да -**Float** | Нет | Нет | Нет | Нет -**Double** | Нет | Нет | Нет | Нет -**Decimal** | Нет | Нет | Нет | Нет -**String** | Да | Да | Да | Да -**Utf8** | Да | Да | Да | Да -**Json** | Нет | Нет | Нет | Нет -**Yson** | Нет | Нет | Нет | Нет -**Uuid** | Нет | Нет | Нет | Нет -**Date** | — | Да | Да | Нет -**Datetime** | Да | — | Да | Нет -**Timestamp** | Да | Да | — | Нет -**Interval** | Нет | Нет | Нет | — | — - -#### Приведение к другим типам данных - -Тип | String | Utf8 | Json | Yson | Uuid ---- | --- | --- | --- | --- | --- -**Bool** | Да | Нет | Нет | Нет | Нет | -**Int8** | Да | Нет | Нет | Нет | Нет -**Int16** | Да | Нет | Нет | Нет | Нет -**Int32** | Да | Нет | Нет | Нет | Нет -**Int64** | Да | Нет | Нет | Нет | Нет -**Uint8** | Да | Нет | Нет | Нет | Нет -**Uint16** | Да | Нет | Нет | Нет | Нет -**Uint32** | Да | Нет | Нет | Нет | Нет -**Uint64** | Да | Нет | Нет | Нет | Нет -**Float** | Да | Нет | Нет | Нет | Нет -**Double** | Да | Нет | Нет | Нет | Нет -**Decimal** | Да | Нет | Нет | Нет | Нет -**String** | — | Да | Да | Да | Да -**Utf8** | Да | — | Нет | Нет | Нет -**Json** | Да | Да | — | Нет | Нет -**Yson** | Да1 | Нет | Нет | Нет | Нет -**Uuid** | Да | Да | Нет | Нет | — -**Date** | Да | Да | Нет | Нет | Нет -**Datetime** | Да | Да | Нет | Нет | Нет -**Timestamp** | Да | Да | Нет | Нет | Нет -**Interval** | Да | Да | Нет | Нет | Нет - -1 При помощи встроенной функции [Yson::ConvertTo](../../udf/list/yson.md#ysonconvertto). - -##### Примеры - -{% include [x](../../_includes/cast_examples.md) %} - -### Неявное приведение {#implicit-cast} - -Неявное приведение типов, которое возникает в базовых операциях (`+`, `-`, `*`, `/`, `%`) между разными типами данных. В ячейках таблицы указан тип результата операции, если она возможна: - -#### Численные типы - -При несовпадении численных типов сначала выполняется BitCast обоих аргументов к типу результата, а потом уже операция. - -Тип | Int8 | Int16 | Int32 | Int64 | Uint8 | Uint16 | Uint32 | Uint64 | Float | Double ---- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- -**Int8** | — | `Int16` | `Int32` | `Int64` | `Int8` | `Uint16` | `Uint32` | `Uint64` | `Float` | `Double` -**Int16** | `Int16` | — | `Int32` | `Int64` | `Int16` | `Int16` | `Uint32` | `Uint64` | `Float` | `Double` -**Int32** | `Int32` | `Int32` | — | `Int64` | `Int32` | `Int32` | `Int32` | `Uint64` | `Float` | `Double` -**Int64** | `Int64` | `Int64` | `Int64` | — | `Int64` | `Int64` | `Int64` | `Int64` | `Float` | `Double` -**Uint8** | `Int8` | `Int16` | `Int32` | `Int64` | — | `Uint16` | `Uint32` | `Uint64` | `Float` | `Double` -**Uint16** | `Uint16` | `Int16` | `Int32` | `Int64` | `Uint16` | — | `Uint32` | `Uint64` | `Float` | `Double` -**Uint32** | `Uint32` | `Uint32` | `Int32` | `Int64` | `Uint32` | `Uint32` | — | `Uint64` | `Float` | `Double` -**Uint64** | `Uint64` | `Uint64` | `Uint64` | `Int64` | `Uint64` | `Uint64` | `Uint64` | — | `Float` | `Double` -**Float** | `Float` | `Float` | `Float` | `Float` | `Float` | `Float` | `Float` | `Float` | — | `Double` -**Double** | `Double` | `Double` | `Double` | `Double` | `Double` | `Double` | `Double` | `Double` | `Double` | — - - -#### Типы даты и времени - -Тип | Date | Datetime | Timestamp | Interval | TzDate | TzDatetime | TzTimestamp ---- | --- | --- | --- | --- | --- | --- | --- -**Date** | — | — | — | `Date` | — | — | — -**Datetime** | — | — | — | `Datetime` | — | — | — -**Timestamp** | — | — | — | `Timestamp` | — | — | — -**Interval** | `Date` | `Datetime` | `Timestamp` | — | `TzDate` | `TzDatetime` | `TzTimestamp` -**TzDate** | — | — | — | `TzDate` | — | — | — -**TzDatetime** | — | — | — | `TzDatetime` | — | — | — -**TzTimestamp** | — | — | — | `TzTimestamp` | — | — | — diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/tz_date_types.md b/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/tz_date_types.md deleted file mode 100644 index 734c015dc084..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/_includes/tz_date_types.md +++ /dev/null @@ -1,18 +0,0 @@ -### Особенности поддержки типов с меткой временной зоны - -Метка временной зоны у типов `TzDate`, `TzDatetime`, `TzTimestamp` это атрибут, который используется: - -* При преобразовании ([CAST](../../syntax/expressions.md#cast), [DateTime::Parse](../../udf/list/datetime.md#parse), [DateTime::Format](../../udf/list/datetime.md#format)) в строку и из строки. -* В [DateTime::Split](../../udf/list/datetime.md#split) - появляется компонент таймзоны в `Resource`. - -Само значение позиции во времени у этих типов хранится в UTC, и метка таймзоны никак не участвует в прочих расчётах. Например: - -```yql -SELECT --эти выражения всегда true для любых таймзон: таймзона не влияет на точку во времени. - AddTimezone(CurrentUtcDate(), "Europe/Moscow") == - AddTimezone(CurrentUtcDate(), "America/New_York"), - AddTimezone(CurrentUtcDatetime(), "Europe/Moscow") == - AddTimezone(CurrentUtcDatetime(), "America/New_York"); -``` - -Важно понимать, что при преобразованиях между `TzDate` и `TzDatetime` или `TzTimestamp` дате соответствует не полночь по локальному времени таймзоны, а полночь по UTC для даты в UTC. diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/cast.md b/ydb/docs/ru/core/yql/reference/yql-core/types/cast.md deleted file mode 100644 index c4581473ba98..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/cast.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/cast.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/containers.md b/ydb/docs/ru/core/yql/reference/yql-core/types/containers.md deleted file mode 100644 index 94779f7479bc..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/containers.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/containers.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/json.md b/ydb/docs/ru/core/yql/reference/yql-core/types/json.md deleted file mode 100644 index 2a96f5886eca..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/json.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/json.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/optional.md b/ydb/docs/ru/core/yql/reference/yql-core/types/optional.md deleted file mode 100644 index a2722f9f6b44..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/optional.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/optional.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/primitive.md b/ydb/docs/ru/core/yql/reference/yql-core/types/primitive.md deleted file mode 100644 index 4ed6b08c3cb5..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/primitive.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/primitive.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/serial.md b/ydb/docs/ru/core/yql/reference/yql-core/types/serial.md deleted file mode 100644 index bcfe4cc06f04..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/serial.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/serial.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/special.md b/ydb/docs/ru/core/yql/reference/yql-core/types/special.md deleted file mode 100644 index bed7bcb5571b..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/special.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include [x](_includes/special.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/types/type_string.md b/ydb/docs/ru/core/yql/reference/yql-core/types/type_string.md deleted file mode 100644 index 22a951f99ec9..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/types/type_string.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/type_string.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/index/list.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/index/list.md deleted file mode 100644 index 29f034c1a037..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/index/list.md +++ /dev/null @@ -1,14 +0,0 @@ -* [DateTime](../../datetime.md) -* [Digest](../../digest.md) -* [Histogram](../../histogram.md) -* [Hyperscan](../../hyperscan.md) -* [Ip](../../ip.md) -* [Knn](../../knn.md) -* [Math](../../math.md) -* [Pcre](../../pcre.md) -* [Pire](../../pire.md) -* [Re2](../../re2.md) -* [String](../../string.md) -* [Unicode](../../unicode.md) -* [Url](../../url.md) -* [Yson](../../yson.md) \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/pgliterals.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/pgliterals.md deleted file mode 100644 index 3a93fe60682f..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/pgliterals.md +++ /dev/null @@ -1,95 +0,0 @@ -### Целочисленные литералы {#intliterals} - -Суффикс | Тип | Комментарий ------ | ----- | ----- -`p` | `PgInt4` | 32-битное знаковое целое (в PostgreSQL нет беззнаковых типов) -`ps`| `PgInt2` | 16-битное знаковое целое -`pi`| `PgInt4` | -`pb`| `PgInt8` | 64-битное знаковое цело -`pn`| `PgNumeric` | знаковое целое произвольной точности (до 131072 цифр) - -### Литералы с плавающей точкой {#floatliterals} - -Суффикс | Тип | Комментарий ------ | ----- | ----- -`p` | `PgFloat8` | число с плавающей точкой (64 бит double) -`pf4`| `PgFloat4` | число с плавающей точкой (32 бит float) -`pf8`| `PgFloat8` | -`pn` | `PgNumeric` | число с плавающей точкой произвольной точности (до 131072 цифр перед запятой, до 16383 цифр после запятой) - -### Строковые литералы {#stringliterals} - -Суффикс | Тип | Комментарий ------ | ----- | ----- -`p` | `PgText` | текстовая строка -`pt`| `PgText` | -`pv`| `PgVarchar` | текстовая строка -`pb`| `PgBytea` | бинарная строка - -{% note warning "Внимание" %} - -Значения строковых/числовых литералов (т.е. то что идет перед суффиксом) должны быть валидной строкой/числом с точки зрения YQL. -В частности, должны соблюдаться правила эскейпинга YQL, а не PostgreSQL. - -{% endnote %} - -Пример: - -```yql -SELECT - 1234p, -- pgint4 - 0x123pb, -- pgint8 - "тест"pt, -- pgtext - 123e-1000pn; -- pgnumeric -; -``` - -### Литерал массива - -Для построения литерала массива используется функция `PgArray`: - -```yql -SELECT - PgArray(1p, NULL ,2p) -- {1,NULL,2}, тип _int4 -; -``` - -### Конструктор литералов произвольного типа {#literals_constructor} - -Литералы всех типов (в том числе и Pg типов) могут создаваться с помощью конструктора литералов со следующей сигнатурой: -`Имя_типа(<строковая константа>)`. - -Напрмер: - -```yql -DECLARE $foo AS String; -SELECT - PgInt4("1234"), -- то же что и 1234p - PgInt4(1234), -- в качестве аргумента можно использовать литеральные константы - PgInt4($foo), -- и declare параметры - PgBool(true), - PgInt8(1234), - PgDate("1932-01-07"), -; -``` - -Также поддерживается встроенная функция `PgConst` со следующей сигнатурой: `PgConst(<строковое значение>, <тип>)`. -Такой способ более удобен для кодогенерации. - -Например: - -```yql -SELECT - PgConst("1234", PgInt4), -- то же что и 1234p - PgConst("true", PgBool) -; -``` - -Для некоторых типов в функции `PgConst` можно указать дополнительные модификаторы. Возможные модификаторы для типа `pginterval` перечислены в [документации PostgreSQL](https://www.postgresql.org/docs/16/datatype-datetime.html). - -```yql -SELECT - PgConst(90, pginterval, "day"), -- 90 days - PgConst(13.45, pgnumeric, 10, 1); -- 13.5 -; -``` diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/yson/intro_footer.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/yson/intro_footer.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/yson/intro_header.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/yson/intro_header.md deleted file mode 100644 index 78f522f214de..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/yson/intro_header.md +++ /dev/null @@ -1 +0,0 @@ -YSON — разработанный в Яндексе формат данных, похожий на JSON. \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/yson/ypath_overlay.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/_includes/yson/ypath_overlay.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/histogram.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/histogram.md deleted file mode 100644 index 921030daeb7c..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/histogram.md +++ /dev/null @@ -1,2 +0,0 @@ - -{% include[x](_includes/histogram.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/index.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/index.md deleted file mode 100644 index eaa62dd0598d..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/index.md +++ /dev/null @@ -1,3 +0,0 @@ -{% include [intro](_includes/index/intro.md) %} - -{% include [list](_includes/index/list.md) %} diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/string.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/string.md deleted file mode 100644 index 3af9fa2dde1e..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/string.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/string.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/unicode.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/unicode.md deleted file mode 100644 index 2a2d7aebd6d5..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/unicode.md +++ /dev/null @@ -1 +0,0 @@ -{% include [x](_includes/unicode.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/url.md b/ydb/docs/ru/core/yql/reference/yql-core/udf/list/url.md deleted file mode 100644 index 07f8fc410cf5..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-core/udf/list/url.md +++ /dev/null @@ -1 +0,0 @@ -{% include [url.md](_includes/url.md) %} \ No newline at end of file diff --git a/ydb/docs/ru/core/yql/reference/yql-product/toc_product.yaml b/ydb/docs/ru/core/yql/reference/yql-product/toc_product.yaml deleted file mode 100644 index 1ed7baf44c38..000000000000 --- a/ydb/docs/ru/core/yql/reference/yql-product/toc_product.yaml +++ /dev/null @@ -1,7 +0,0 @@ -items: -- name: Типы данных - include: { mode: link, path: types/toc_i.yaml } -- name: Синтаксис - include: { mode: link, path: syntax/toc_i.yaml } -- name: Встроенные функции - include: { mode: link, path: builtins/toc_i.yaml }