# Aggregate Functions
Source: https://docs.ocient.com/aggregate-functions
Reference for Ocient SQL aggregate functions, including SUM, AVG, COUNT, MIN, MAX, and approximate aggregates for computing values across rows in queries.
The has aggregated and sorted aggregate functions. Aggregate and sorted aggregate functions compute a single result from a group of rows. You can use the `DISTINCT` keyword with any aggregation function, such as `COUNT(DISTINCT col)`. Whereas sorted aggregate functions use the standard ORDER BY syntax to dictate the ordering of the aggregation. To sort the elements of an array, use the [ARRAY\_SORT](/transform-data-in-data-pipelines#array-data-transformation-functions) function during data load.
## Aggregate Functions
Supported input types vary by function. In general, numeric types include `TINYINT`, `SMALLINT`, `INT`, `BIGINT`, `FLOAT`, `DOUBLE`, and `DECIMAL`.
Various examples on this page use these tables.
```sql SQL theme={null}
CREATE TABLE sample_data (val INT, label VARCHAR(10));
INSERT INTO sample_data (val, label) VALUES
(2, 'alpha'), (4, 'beta'), (4, 'alpha'), (5, NULL),
(7, 'gamma'), (8, 'alpha'), (12, 'beta'), (15, 'gamma');
```
```sql SQL theme={null}
CREATE TABLE predictions (actual INT, predicted INT);
INSERT INTO predictions (actual, predicted) VALUES
(10, 12), (20, 18), (30, 33),
(40, 37), (50, 52), (60, 58);
```
For simple functions, examples use the `sys.dummy` virtual table. For details, see [Generate Tables Using sys.dummy](/generate-tables-using-sys-dummy).
### ACCURACY\_SCORE
Returns the fraction of predictions that match the actual class labels. This function calculates the ratio of correctly predicted rows to the total number of rows.
```sql SQL theme={null}
ACCURACY_SCORE(y, y_hat)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ------------------- | -------------------------- |
| `y` | All types supported | The actual class label. |
| `y_hat` | All types supported | The predicted class label. |
The return type is `DOUBLE`. The result represents the proportion of correct predictions, ranging from 0 to 1.
**Examples**
**Calculate the Accuracy Score for Matched Values**
This query returns the accuracy score when all predictions match the actual values.
```sql SQL theme={null}
SELECT ACCURACY_SCORE(c1, c1) FROM sys.dummy10;
```
Output: `1`
**Calculate the Accuracy Score with Comparison Against Squared Values**
This query returns the accuracy score when comparing actual values against their squared values.
```sql SQL theme={null}
SELECT ACCURACY_SCORE(c1, c1 * c1) FROM sys.dummy10;
```
Output: `0.1`
### ANY\_VALUE
Returns an arbitrary non-`NULL` value from the input column. The function returns `NULL` only if all rows in the column are `NULL`.
The `ANY_VALUE` function does not support window aggregation.
**Syntax**
```sql SQL theme={null}
ANY_VALUE(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ------------- | -------------------------------------------------------------- |
| `col` | Any type | The column from which to return an arbitrary non-`NULL` value. |
**Example**
```sql SQL theme={null}
SELECT
ANY_VALUE(label) AS sample_label
FROM sample_data;
```
Output: `alpha`
The returned value is non-deterministic. The database can return any non-`NULL` value from the column.
### APPROX\_COUNT\_DISTINCT
Returns an approximate count of distinct values in the column using the HyperLogLog algorithm, with a 95% confidence interval that the result is within 4.5% of the exact count.
**Syntax**
```sql SQL theme={null}
APPROX_COUNT_DISTINCT(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | --------------------- | ------------------------------------------------------- |
| `col` | Any non-interval type | The column for the approximation of the distinct count. |
**Example**
```sql SQL theme={null}
SELECT
APPROX_COUNT_DISTINCT(val) AS approx_distinct
FROM sample_data;
```
Output: `7`
The `sample_data` table has 8 rows, but there are only 7 distinct values in the `val` column (the value `4` appears twice).
### APPROX\_SUM
Computes a sum using a faster, non-deterministic ordering for floating-point columns. This summation can lead to minor differences in the result on the order of the machine epsilon. For integral column types, the function uses the standard `SUM` algorithm.
**Syntax**
```sql SQL theme={null}
APPROX_SUM(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | --------------------------------------- | ------------------ |
| `col` | `FLOAT`, `DOUBLE`, or any integral type | The column to sum. |
For integral inputs, the `APPROX_SUM` function uses the standard `SUM` algorithm and returns the same result. The performance benefit applies to large floating-point data sets.
**Example**
```sql SQL theme={null}
SELECT
APPROX_SUM(c1) AS approx_total
FROM sys.dummy5;
```
Output: `15`
### AVG
Computes the arithmetic mean over the set of values.
**Syntax**
```sql SQL theme={null}
AVG(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `col` | Any numeric type or `MATRIX` | The column to average.
Integral and `FLOAT` inputs return `DOUBLE`.
`DOUBLE`, `DECIMAL`, and `MATRIX` inputs preserve their type. |
**Example**
```sql SQL theme={null}
SELECT
AVG(c1) AS avg_val
FROM sys.dummy5;
```
Output: `3.0`
### COEFFICIENT\_OF\_DETERMINATION
Computes the coefficient of determination (R²) between actual and predicted values. Primarily used to evaluate the performance of machine learning regression models, R² measures the proportion of variance in the actual values that the predicted values explain. A value of `1.0` indicates a perfect fit, while `0.0` indicates that the predictions explain none of the variance.
This function returns `NULL` when the total sum of squares is zero (i.e., all actual values are identical).
**Syntax**
```sql SQL theme={null}
COEFFICIENT_OF_DETERMINATION(actual, predicted)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------- | ------------------------------- |
| `actual` | Any numeric type | The column of observed values. |
| `predicted` | Any numeric type | The column of predicted values. |
**Example**
```sql SQL theme={null}
SELECT
COEFFICIENT_OF_DETERMINATION(actual, predicted) AS r_squared
FROM predictions;
```
Output: `0.980571428571429`
### CONFUSION\_MATRIX
Returns a structured representation of the counts for every combination of actual and predicted class labels relative to a specified positive class. This function aggregates predictions into a 2x2 matrix in the format `[[TP, FP], [FN, TN]]` for binary classification analysis.
```sql SQL theme={null}
CONFUSION_MATRIX(y, y_hat, positive_class)
```
| **Argument** | **Data Type** | **Description** |
| ---------------- | ------------------- | --------------------------------------------------------------------------------------- |
| `y` | All types supported | The actual class label. |
| `y_hat` | All types supported | The predicted class label. |
| `positive_class` | All types supported | The class label to treat as the positive class. Must match the type of `y` and `y_hat`. |
The return type is `TUPLE`. Each entry in the result contains the count of rows for a specific combination of actual and predicted class values, organized as true positives, false positives, false negatives, and true negatives.
**Examples**
**Calculate the Confusion Matrix with Matched Values**
This query returns the confusion matrix when all predictions match the actual values.
```sql SQL theme={null}
SELECT CONFUSION_MATRIX(
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
1
) FROM sys.dummy10;
```
Output: `[[5, 0], [0, 5]]`
**Calculate the Confusion Matrix with Mismatched Classifiers**
This query returns the confusion matrix for two mismatched binary classifiers, where actual positives are rows with `c1 > 5` and predicted positives are rows with `c1 < 3`.
```sql SQL theme={null}
SELECT CONFUSION_MATRIX(
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
CASE WHEN c1 < 3 THEN 1 ELSE 0 END,
1
) FROM sys.dummy10;
```
Output: `[[0, 2], [5, 3]]`
### CORR
Alias for [CORRELATIONP](#correlationp).
### CORRELATION
Alias for [CORRELATIONP](#correlationp).
### CORRELATIONP
Computes the population Pearson correlation coefficient between two columns. Returns `DOUBLE`, or `DECIMAL` if both inputs are `DECIMAL`-compatible.
Alias for `CORRELATION` and `CORR`.
**Syntax**
```sql SQL theme={null}
CORRELATIONP(col1, col2)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------- | ------------------ |
| `col1` | Any numeric type | The first column. |
| `col2` | Any numeric type | The second column. |
**Example**
```sql SQL theme={null}
SELECT
CORRELATIONP(actual, predicted) AS corr_val
FROM predictions;
```
Output: `0.9904654955172436`
### COUNT
Returns the number of rows in the set where values in `col` are not `NULL`. When you use the `COUNT(*)` SQL statement, the function returns the total number of rows. The return type is `BIGINT`.
**Syntax**
```sql SQL theme={null}
COUNT(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | --------------------- | ----------------------------------------------------------------------------------------- |
| `col` | Any non-interval type | The column for counting non-`NULL` values.
Use `*` to count all rows instead. |
**Examples**
**Count All Rows**
```sql SQL theme={null}
SELECT COUNT(*) AS total_rows FROM sample_data;
```
Output: `8`
**Count Non-NULL Values**
The `label` column has one `NULL` row.
```sql SQL theme={null}
SELECT COUNT(label) AS rows_with_label FROM sample_data;
```
Output: `7`
### COVAR\_POP
Alias for [COVARIANCEP](#covariancep).
### COVAR\_SAMP
Alias for [COVARIANCE](#covariance).
### COVARIANCE
Computes the sample covariance between two columns. Returns `DOUBLE` by default, or `DECIMAL` if both inputs are `DECIMAL`-compatible. `MATRIX` inputs preserve their type.
Alias for `COVAR_SAMP`.
**Syntax**
```sql SQL theme={null}
COVARIANCE(col1, col2)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ------------------------------------- | ------------------ |
| `col1` | Any numeric type or `MATRIX` (square) | The first column. |
| `col2` | Any numeric type or `MATRIX` (square) | The second column. |
Matrix arguments must have matching dimensions.
**Example**
```sql SQL theme={null}
SELECT
COVARIANCE(actual, predicted) AS cov_samp
FROM predictions;
```
Output: `336.0`
### COVARIANCEP
Computes the population covariance between two columns. Returns `DOUBLE` by default, or `DECIMAL` if both inputs are compatible with `DECIMAL`.
`MATRIX` inputs preserve their type.
Alias for `COVAR_POP`.
**Syntax**
```sql SQL theme={null}
COVARIANCEP(col1, col2)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ------------------------------------- | ------------------ |
| `col1` | Any numeric type or `MATRIX` (square) | The first column. |
| `col2` | Any numeric type or `MATRIX` (square) | The second column. |
Matrix arguments must have matching dimensions.
**Example**
```sql SQL theme={null}
SELECT
COVARIANCEP(actual, predicted) AS cov_pop
FROM predictions;
```
Output: `280.0`
### F1\_SCORE
Returns the harmonic mean of precision and recall for a specified positive class. This function calculates `2 * (Precision * Recall) / (Precision + Recall)` and provides a single score that balances both precision and recall. The function returns `NULL` when both precision and recall are 0.
```sql SQL theme={null}
F1_SCORE(y, y_hat, positive_class)
```
| **Argument** | **Data Type** | **Description** |
| ---------------- | ------------------- | --------------------------------------------------------------------------------------- |
| `y` | All types supported | The actual class label. |
| `y_hat` | All types supported | The predicted class label. |
| `positive_class` | All types supported | The class label to treat as the positive class. Must match the type of `y` and `y_hat`. |
The return type is `DOUBLE`. The result ranges from 0 to 1, where 1 represents perfect precision and recall.
**Examples**
**Calculate the F1 Score with Matching Values**
This query returns the F1 score when all predictions match the actual values.
```sql SQL theme={null}
SELECT F1_SCORE(
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
1
) FROM sys.dummy10;
```
Output: `1`
**Calculate the F1 Score for Mismatched Classifiers**
This query returns `NULL` because both precision and recall are 0 for the mismatched classifiers.
```sql SQL theme={null}
SELECT F1_SCORE(
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
CASE WHEN c1 < 3 THEN 1 ELSE 0 END,
1
) FROM sys.dummy10;
```
Output: `NULL`
### KURTOSIS
Computes the sample excess kurtosis over the set of values. Kurtosis measures the difference between the tails of a distribution and the tails of a normal distribution. Returns `DOUBLE`, or `DECIMAL` if the input is `DECIMAL`.
**Syntax**
```sql SQL theme={null}
KURTOSIS(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------- | --------------------------------------------- |
| `col` | Any numeric type | The column for computing the sample kurtosis. |
**Example**
```sql SQL theme={null}
SELECT
KURTOSIS(val) AS kurt_val
FROM sample_data;
```
Output: `4.763725276787391`
### KURTOSISP
Computes the population kurtosis over the set of values. Returns `DOUBLE`, or `DECIMAL` if the input is `DECIMAL`.
**Syntax**
```sql SQL theme={null}
KURTOSISP(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------- | --------------------------------------------- |
| `col` | Any numeric type | The column for computing population kurtosis. |
**Example**
```sql SQL theme={null}
SELECT
KURTOSISP(val) AS kurtp_val
FROM sample_data;
```
Output: `2.268440607993995`
### MAX
Returns the maximum value in the specified column. The return type matches the input.
**Syntax**
```sql SQL theme={null}
MAX(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | --------------------- | ------------------------------------------- |
| `col` | Any non-interval type | The column for returning the maximum value. |
**Example**
```sql SQL theme={null}
SELECT
MAX(c1) AS max_val
FROM sys.dummy5;
```
Output: `5`
### MEAN\_ABSOLUTE\_ERROR
Returns the mean absolute error (MAE) between actual and predicted values. This function calculates the average of the absolute differences between each pair of actual and predicted values, treating all errors equally regardless of direction.
```sql SQL theme={null}
MEAN_ABSOLUTE_ERROR(y, y_hat)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ------------- | -------------------- |
| `y` | NUMERIC | The actual value. |
| `y_hat` | NUMERIC | The predicted value. |
The return type is `DOUBLE`. The result is always zero or positive. A value of 0 indicates perfect predictions.
Examples
**Calculate the MAE for Matched Values**
This query returns the mean absolute error when all predictions match the actual values.
```sql SQL theme={null}
SELECT MEAN_ABSOLUTE_ERROR(c1, c1) FROM sys.dummy10;
```
Output: `0`
**Calculate the MAE with Comparison Against Squared Values**
This query returns the mean absolute error when comparing actual values against their squared values.
```sql SQL theme={null}
SELECT MEAN_ABSOLUTE_ERROR(c1, c1 * c1) FROM sys.dummy10;
```
Output: `33.0`
### MEAN\_ABSOLUTE\_PERCENTAGE\_ERROR
Returns the mean absolute percentage error (MAPE) between actual and predicted values. This function calculates the average of the absolute percentage differences using the formula `Average( AbsoluteValue( (y - y_hat) / y ) ) * 100`, which expresses the error relative to the actual values.
```sql SQL theme={null}
MEAN_ABSOLUTE_PERCENTAGE_ERROR(y, y_hat)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ------------- | ----------------------------------------------------------------------------------------------------- |
| `y` | NUMERIC | The actual value. Must not be 0, because this value is the denominator in the percentage calculation. |
| `y_hat` | NUMERIC | The predicted value. |
The return type is `DOUBLE`. The result is a percentage value where 0 indicates perfect predictions.
Examples
**Calculate the MAPE for Matched Values**
This query returns the mean absolute percentage error when all predictions match the actual values.
```sql SQL theme={null}
SELECT MEAN_ABSOLUTE_PERCENTAGE_ERROR(c1, c1) FROM sys.dummy10;
```
Output: `0`
**Calculate the MAPE with Comparison Against Squared Values**
This query returns the mean absolute percentage error when comparing actual values against their squared values.
```sql SQL theme={null}
SELECT MEAN_ABSOLUTE_PERCENTAGE_ERROR(c1, c1 * c1)
FROM sys.dummy10;
```
Output: `450.0`
### MIN
Returns the minimum value in the specified column. The return type matches the input.
**Syntax**
```sql SQL theme={null}
MIN(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | --------------------- | ------------------------------------------- |
| `col` | Any non-interval type | The column for returning the minimum value. |
**Example**
```sql SQL theme={null}
SELECT
MIN(c1) AS min_val
FROM sys.dummy5;
```
Output: `1`
### PRECISION\_SCORE
Returns the precision score for a specified positive class. This function calculates the ratio of true positives to the total number of predicted positives using the formula `True Positives / (True Positives + False Positives)`. Of all the predictions for the specified class, this score measures how many are correct.
```sql SQL theme={null}
PRECISION_SCORE(y, y_hat, positive_class)
```
| **Argument** | **Data Type** | **Description** |
| ---------------- | ------------------- | --------------------------------------------------------------------------------------- |
| `y` | All types supported | The actual class label. |
| `y_hat` | All types supported | The predicted class label. |
| `positive_class` | All types supported | The class label to treat as the positive class. Must match the type of `y` and `y_hat`. |
The return type is `DOUBLE`. The result ranges from 0 to 1, where 1 indicates that every prediction for the positive class is correct.
**Examples**
**Calculate the Precision Score for Matched Values**
This query returns the precision score when all predictions match the actual values.
```sql SQL theme={null}
SELECT PRECISION_SCORE(
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
1
) FROM sys.dummy10;
```
Output: `1`
**Calculate the Precision Score for Mismatched Classifiers**
This query returns the precision score for two mismatched binary classifiers, where none of the predicted positives are actual positives.
```sql SQL theme={null}
SELECT PRECISION_SCORE(
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
CASE WHEN c1 < 3 THEN 1 ELSE 0 END,
1
) FROM sys.dummy10;
```
Output: `0.0`
### PRODUCT
Computes the product of all values in the column.
**Syntax**
```sql SQL theme={null}
PRODUCT(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | --------------------------------------------------------------------- | -------------------------------------------------------- |
| `col` | `FLOAT`, `DOUBLE`, `DECIMAL`, any integral type, or `MATRIX` (square) | The column to multiply. Integral inputs return `BIGINT`. |
Matrix arguments must have matching dimensions.
**Example**
```sql SQL theme={null}
SELECT
PRODUCT(c1) AS factorial_5
FROM sys.dummy5;
```
Output: `120`
### RECALL\_SCORE
Returns the recall score for a specified positive class. This function calculates the ratio of true positives to the total number of actual positives using the formula `True Positives / (True Positives + False Negatives)`. Of all the actual instances of the specified class, this score measures how many the model correctly identifies.
```sql SQL theme={null}
RECALL_SCORE(y, y_hat, positive_class)
```
| **Argument** | **Data Type** | **Description** |
| ---------------- | ------------------- | --------------------------------------------------------------------------------------- |
| `y` | All types supported | The actual class label. |
| `y_hat` | All types supported | The predicted class label. |
| `positive_class` | All types supported | The class label to treat as the positive class. Must match the type of `y` and `y_hat`. |
The return type is `DOUBLE`. The result ranges from 0 to 1, where 1 indicates that every actual instance of the positive class is correctly identified.
**Examples**
**Calculate the Recall Score for Matched Values**
This query returns the recall score when all predictions match the actual values.
```sql SQL theme={null}
SELECT RECALL_SCORE(
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
1
) FROM sys.dummy10;
```
Output: `1`
**Calculate the Recall Score for Mismatched Classifiers**
This query returns the recall score for two mismatched binary classifiers, where none of the actual positives are correctly predicted.
```sql SQL theme={null}
SELECT RECALL_SCORE(
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
CASE WHEN c1 < 3 THEN 1 ELSE 0 END,
1
) FROM sys.dummy10;
```
Output: `0.0`
### ROC\_AUC\_SCORE
Returns the area under the receiver operating characteristic (ROC) curve (AUC). This function measures the ability of a binary classification model to distinguish between classes. A score of 1.0 represents a perfect classifier, while a score of 0.5 represents performance no better than random guessing.
```sql SQL theme={null}
ROC_AUC_SCORE(y_true, y_score, positive_class)
```
| **Argument** | **Data Type** | **Description** |
| ---------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `y_true` | BOOLEAN or INTEGER | The true binary class label, where the values represent two classes (for example, 0 or 1). |
| `y_score` | NUMERIC | The predicted probability or confidence score for the positive class. A score of 1.0 is a perfect classifier, while 0.5 is no better than random guessing. |
| `positive_class` | | The class label to treat as the positive class. Must match the type of `y_true`. |
The return type is `DOUBLE`. The result ranges from 0 to 1.
**Example**
This query returns the AUC score for a classifier in which higher probability scores correspond to actual positives, indicating perfect class separation.
```sql SQL theme={null}
SELECT ROC_AUC_SCORE(
CASE WHEN c1 > 5 THEN 1 ELSE 0 END,
DOUBLE(c1) / 10,
1
) FROM sys.dummy10;
```
Output: `1.0`
### SKEW
Computes the sample skewness over the set of values. Skewness measures the asymmetry of a distribution. Returns `DOUBLE`, or `DECIMAL` if the input is `DECIMAL`.
**Syntax**
```sql SQL theme={null}
SKEW(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------- | --------------------------------------------- |
| `col` | Any numeric type | The column for computing the sample skewness. |
**Example**
```sql SQL theme={null}
SELECT
SKEW(val) AS skew_val
FROM sample_data;
```
Output: `0.8804164883619399`
### SKEWP
Computes the population skewness over the set of values. Returns `DOUBLE`, or `DECIMAL` if the input is `DECIMAL`.
**Syntax**
```sql SQL theme={null}
SKEWP(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------- | ------------------------------------------------- |
| `col` | Any numeric type | The column for computing the population skewness. |
**Example**
```sql SQL theme={null}
SELECT
SKEWP(val) AS skewp_val
FROM sample_data;
```
Output: `0.7059036122393627`
### STDEV
Computes the sample standard deviation over the set of values. Returns `DOUBLE`, or `DECIMAL` if the input is `DECIMAL`.
Alias for `STDDEV` and `STDDEV_SAMP`.
**Syntax**
```sql SQL theme={null}
STDEV(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------- | ------------------------------------------------------- |
| `col` | Any numeric type | The column for computing the sample standard deviation. |
**Example**
```sql SQL theme={null}
SELECT
STDEV(val) AS stdev_val
FROM sample_data;
```
Output: `4.421942042651783`
### STDDEV
Alias for [STDEV](#stdev).
### STDDEV\_POP
Alias for [STDEVP](#stdevp).
### STDDEV\_SAMP
Alias for [STDEV](#stdev).
### STDEVP
Computes the population standard deviation over the set of values. Returns `DOUBLE`, or `DECIMAL` if the input is `DECIMAL`.
Alias for `STDDEV_POP`.
**Syntax**
```sql SQL theme={null}
STDEVP(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------- | ----------------------------------------------------------- |
| `col` | Any numeric type | The column for computing the population standard deviation. |
**Example**
```sql SQL theme={null}
SELECT
STDEVP(val) AS stdevp_val
FROM sample_data;
```
Output: `4.136348026943574`
### SUM
Computes the sum of all values in the column.
**Syntax**
```sql SQL theme={null}
SUM(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `col` | Any numeric type or `MATRIX` | The column to sum.
Integral inputs return `BIGINT`. d `FLOAT` inputs return `FLOAT`.
`DOUBLE`, `DECIMAL`, and `MATRIX` inputs preserve their type. |
**Example**
```sql SQL theme={null}
SELECT
SUM(c1) AS total
FROM sys.dummy5;
```
Output: `15`
### VAR\_POP
Alias for [VARIANCEP](#variancep).
### VAR\_SAMP
Alias for [VARIANCE](#variance).
### VARIANCE
Computes the sample variance over the set of values. Returns `DOUBLE`, or `DECIMAL` if the input is `DECIMAL`.
`MATRIX` inputs preserve their type and must be square.
Alias for `VAR_SAMP`.
**Syntax**
```sql SQL theme={null}
VARIANCE(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ------------------------------------- | --------------------------------------------- |
| `col` | Any numeric type or `MATRIX` (square) | The column for computing the sample variance. |
Matrix arguments must have matching dimensions.
**Example**
```sql SQL theme={null}
SELECT
VARIANCE(val) AS var_val
FROM sample_data;
```
Output: `19.553571428571427`
### VARIANCEP
Computes the population variance over the set of values. Returns `DOUBLE`, or `DECIMAL` if the input is `DECIMAL`.
`MATRIX` inputs preserve their type and must be square.
Alias for `VAR_POP`.
**Syntax**
```sql SQL theme={null}
VARIANCEP(col)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ------------------------------------- | --------------------------------------------- |
| `col` | Any numeric type or `MATRIX` (square) | The column for computing population variance. |
**Example**
```sql SQL theme={null}
SELECT
VARIANCEP(val) AS varp_val
FROM sample_data;
```
Output: `17.109375`
## Sorted Aggregate Functions
The general syntax for sorted aggregate functions adds the DISTINCT and ORDER BY keywords in the function invocation.
```sql SQL theme={null}
AGGREGATE([DISTINCT] arg1, arg2, ... [ORDER BY ...])
```
### ARRAY\_AGG
Returns an array containing every row from the expression.
**Syntax**
```sql SQL theme={null}
ARRAY_AGG(expr)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | ---------------- | ----------------------------------------- |
| `expr` | Any numeric type | Expression for aggregation into an array. |
**Example**
Aggregate ten rows into an array in descending order.
```sql SQL theme={null}
SELECT
ARRAY_AGG(c1 ORDER BY c1 DESC)
FROM sys.dummy10;
```
Output: `[10,9,8,7,6,5,4,3,2,1]`
### ARRAY\_CONCAT\_AGG
Returns an array that concatenates arrays across rows. The input argument is a SQL expression. The element type must be consistent across rows. The function ignores NULL inputs and returns NULL only when all inputs are NULL.
The `DISTINCT` keyword removes duplicate arrays. To remove duplicate elements from an array, use the `ARRAY_DISTINCT` function during load.
The `ORDER BY` syntax controls the order of concatenation across rows. To sort elements in the array, use the `ARRAY_SORT` function during load.
**Syntax**
```sql SQL theme={null}
ARRAY_CONCAT_AGG(expr)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | -------------- | ----------------------------------------- |
| `expr` | SQL expression | Expression for concatenation across rows. |
**Example**
Create the `data_type_example` table with a column that stores arrays of integers.
```sql SQL theme={null}
CREATE TABLE
data_type_example (col_int_array INT[] NOT NULL DEFAULT 'INT[0,1,2,3]');
```
Insert one array with values `1`, `2`, and `3` into the table.
```sql SQL theme={null}
INSERT INTO data_type_example SELECT ARRAY[1,2,3];
```
Insert the second array with values `4`, `5`, and `6` into the table.
```sql SQL theme={null}
INSERT INTO data_type_example SELECT ARRAY[4,5,6];
```
Concatenate the two arrays into one array in ascending order.
```sql SQL theme={null}
SELECT ARRAY_CONCAT_AGG(col_int_array ORDER BY col_int_array ASC)
FROM data_type_example;
```
Output: `[1,2,3,4,5,6]`
### STRING\_AGG
Returns a string concatenated from every row of the expression.
**Syntax**
```sql SQL theme={null}
ARRAY_CONCAT_AGG(expr, delimiter)
```
| **Argument** | **Data Type** | **Description** |
| ------------ | -------------- | ----------------------------------------- |
| `expr` | SQL expression | Expression for concatenation across rows. |
| `delimiter` | | Optional. |
**Examples**
**Concatenate Rows as a String**
Concatenate ten rows into a string in descending order. Cast integers into strings using the `CHAR` casting function.
```sql SQL theme={null}
SELECT
STRING_AGG(char(c1) ORDER BY c1 DESC)
FROM sys.dummy10;
```
Output: `"10987654321"`
**Concatenate Rows as a String with a Delimiter**
Concatenate ten rows into a string in ascending order. Cast integers into strings using the `CHAR` casting function. Use the `|` delimiter.
```sql SQL theme={null}
SELECT
STRING_AGG(char(c1), '|' ORDER BY c1 ASC)
FROM sys.dummy10;
```
Output: `"1|2|3|4|5|6|7|8|9|10"`
## Related Links
[Math Functions and Operators](/math-functions-and-operators)
[Query Ocient](/query-ocient)
# Air-Gapped Environment with an Ocient System
Source: https://docs.ocient.com/air-gapped-environment-with-an-ocient-system
Deploy and operate an Ocient System in an air-gapped environment to protect sensitive data, with no special configuration required for full isolation.
An air gap is a security measure that physically isolates a computer or network from any other network, including the internet. This isolation removes wired or wireless connections between the isolated system and any external and potentially unsecured networks. Organizations that handle highly sensitive information, such as government agencies, financial institutions, and critical infrastructure operators, use air-gapped environments to protect against various security incidents.
supports using an Ocient System in an air-gapped environment without any special configuration. Here, you can find the general workflow for using an Ocient System in an air-gapped environment and the required installation steps.
## Work with an Ocient System in an Air-Gapped Environment
This workflow shows the high-level steps to set up an Ocient System in an air-gapped environment.
Ensure that your drive firmware and operating system is up to date.
Install and configure an Ocient System in a connected environment where you can download the required files from the internet.
Disassemble the cluster.
Pack and deliver the hardware to your secured location.
Reassign a new IP address.
Reassign a new hostname.
Bootstrap the system again.
## Install an Ocient System in an Air-Gapped Environment
Follow these steps to install the Ocient System in an air-gapped environment. These steps assume that you have met the system requirements for installation.
#### Bootstrap the Node
Connect to the initial SQL Node with the username and password of your server and the IP address of your node. This example connects as the administrator `admin` to the IP Address `10.10.10.10`.
```shell Shell theme={null}
ssh admin@10.10.10.10
```
Use your preferred text editor with `sudo` to create the `/var/opt/ocient/bootstrap.conf` file as root with these contents.
`/var/opt/ocient/bootstrap.conf` **example**
```yaml YAML theme={null}
initialSystem: true
```
Start the database.
```shell Shell theme={null}
sudo systemctl start rolehostd
```
Verify that the node and the service is active by executing this status command.
```shell Shell theme={null}
systemctl status rolehostd
rolehostd.service - Rolehostd daemon startup
Loaded: loaded (/etc/systemd/system/rolehostd.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2022-01-26 23:31:36 UTC; 7s ago
...
```
If the `rolehostd` service is running, you can also check the Ocient logs on your node. Search and ensure there are no \[ERROR] log messages.
```shell Shell theme={null}
tail -f /var/opt/ocient/log/rolehostd.log
```
#### Verify Connection to the SQL Node
At this point, you have a running database with a single node. You should be able to connect to the database using JDBC or `pyocient` and execute commands.
Every new system starts with a `system` database. To connect to a new system, use the username and password configured in the `bootstrap.conf` file or the username `admin@system` and password `admin` if none were provided.
For example, assume your node named `sql0` has an IP address of `10.10.0.1`. Use the JDBC driver CLI to connect with this connection string.
```shell Shell theme={null}
connect to jdbc:ocient://10.10.0.1:4050/system user "myuser@system" using "mypassword";
```
To see the roles running on the single node, execute this query.
```sql SQL theme={null}
select name, operational_status, software_version, array_agg(service_role_type)
from sys.node_status as ns
left join sys.nodes as n on ns.node_id = id
left join sys.service_roles as sr on sr.node_id = n.id
group by name, operational_status,software_version;
```
The initial node should be listed as running the `sql`, `admin`, `health`, and `operatorvm` roles. If all of these roles are present and the node is Active, you can proceed to the next step to bootstrap the remaining nodes.
Performing the bootstrapping process on the remaining nodes is identical on all nodes. The remaining nodes can be bootstrapped in any order.
On each node, log in using SSH and use your text editor with `sudo` to create the file `/var/opt/ocient/bootstrap.conf` that contains this text by replacing `` with the IP address of the initial node you created in Step 1.
`/var/opt/ocient/bootstrap.conf` **example**
```yaml YAML theme={null}
adminHost:
```
`` is the DNS name or IP address of the initial node.
You can obtain the IP Address of the initial node by executing `ifconfig` on that node.
If the password for the system administrator has changed, set the correct username `adminUserName` and password `adminPassword` in the bootstrap configuration file `bootstrap.conf`.
On each node, start the database.
```shell Shell theme={null}
sudo systemctl start rolehostd
```
When you replace Foundation Nodes, the Ocient System removes the prior node after the creation of the new node. Some queries of the system catalog tables might not return results until the prior node is removed.
At this point, all the remaining nodes are not configured with any roles. After all nodes have been started, you should see them when you execute this query with only the `health` role listed. This query uses the `sys.node_status`, `sys.nodes`, and `sys.service_roles` system catalog tables to retrieve node information for the node name, operation status, version, and all service role types. The query uses the ARRAY\_AGG function to retrieve the service role type for all rows.
```sql SQL theme={null}
SELECT name, operational_status, software_version, array_agg(service_role_type)
FROM sys.node_status AS ns
LEFT JOIN sys.nodes AS n ON ns.node_id = id
LEFT JOIN sys.service_roles AS sr ON sr.node_id = n.id
GROUP BY name, operational_status,software_version;
```
## Remove a Cluster in an Air-Gapped Environment
Use this information and workflow to remove a cluster by shutting down all Ocient processes and erasing the drives and data.
The system administrator must download the `sedutil-cli` utility used in this workflow.
You can classify the drives in an Ocient System in two categories based on their usage.
* Operating System (OS) drives: These drives contain the installation of the operating system and software, including the . A system might have a single physical OS drive or an OS installed on a RAID disk created by using more than one drive. The OS drives on nodes with the administrator role (Metadata and possibly SQL Nodes) also store configuration information related to the Ocient System that can include:
* Node names
* Node IP addresses
* User data mapping information for compressed columns
* Encryption keys for the data drives (unless the keys are under the control of an external key management system)
* Data drives: The data drives are present in all types of nodes except the node running only the administrator role. On the Foundation Node, the data drives store tables. On SQL Nodes, the data drives store transient query information. And, on Loader Nodes, the data drives store transient loading information.
The data drives in the Ocient System are exclusively NVMe drives. The OS drives can be NVMe or SSD. These drives can support The Computing Group (TCG) Opal Specification or not support it. The type of drive (Opal-supported or not) determines how the system removes all data on the drive. Follow these steps to remove a cluster for Opal-supported drives. To remove data for Opal-supported drives, follow these steps.
These steps irreversibly remove the data. Follow these steps after you ensure that you no longer need the applicable data from the system.
Stop the Ocient processes running on the nodes using these commands.
For Loader Nodes, use this command. The command combines two commands that stop all processes related to loading.
```shell Shell theme={null}
sudo systemctl disable lat && sudo systemctl stop lat
```
For all types of nodes, use this command. The command combines two commands where the first command stops processing on all nodes and the second command stops the main Ocient System process.
```shell Shell theme={null}
sudo systemctl disable rolehostd && sudo systemctl kill -s SIGKILL rolehostd
```
Bind the data drives to an NVMe driver so that the drives become visible to the OS.
```shell Shell theme={null}
sudo /opt/ocient/scripts/nvme-driver-util.sh bind-nvme
```
Run this command for each data drive. The impacted drives are the drives displayed as their association change from `uio` drivers to `nvme` drivers. You can see the `nvme` drive association by running the `/opt/ocient/scripts/nvme-driver-util.sh` script. All data drives are erased.
You can move drives to another node with the `sedutil-cli` utility if the nodes are already powered off and you cannot power them on. Use the same command to erase the drive: `sedutil-cli -n --revertTPer admin /dev/nvmeXn1`.
```shell Shell theme={null}
sedutil-cli -n --revertTPer admin /dev/nvmeXn1
```
You cannot securely erase the OS drives while the OS is running. You can either use the secure erase facility from BIOS or move drives to an external host with a utility approved by your organization for the remove operation.
## Related Links
[Install an Ocient System](/install-an-ocient-system)
[Ocient System Bootstrapping](/ocient-system-bootstrapping)
[Set Up System Monitoring with the TIG Stack and Kapacitor](/set-up-system-monitoring-with-the-tig-stack-and-kapacitor)
# Alphabetical SQL Functions List
Source: https://docs.ocient.com/alphabetical-sql-functions-list
Alphabetical reference of all SQL functions in Ocient, including math, string, date, conversion, geospatial, machine learning, and aggregates.
| **Function Name** | **Category Name** | **Function Description** |
| --------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [ABS](/math-functions-and-operators#abs) | Math Functions | Returns the absolute value of a specified floating-point number. |
| [ABS](/matrix-functions-and-operators#matrix-functions) | Matrix Functions | Returns the magnitude of one-dimensional matrix or vector. |
| [ACOS](/math-functions-and-operators#acos) | Math Functions | Returns the inverse cosine of a specified floating-point number. |
| [ACOSH](/math-functions-and-operators#acosh) | Math Functions | Returns the hyperbolic arc-cosine of a specified floating-point number. |
| [ACCURACY\_SCORE](/aggregate-functions#accuracy_score) | Aggregate Functions | Returns the fraction of predictions that match the actual class labels. |
| [ADD\_MONTHS](/date-and-time-functions#add_months) | Date and Time Functions | Adds the specified number of months to the date. |
| [ANY\_VALUE](/aggregate-functions#any_value) | Aggregate Functions | Returns an arbitrary, non-NULL value from the input column. |
| [APPROX\_COUNT\_DISTINCT](/aggregate-functions#approx_count_distinct) | Aggregate Functions | Approximate distinct count by using hyper-log-log (95% confidence interval that the value is within 4.5%). |
| [APPROX\_SUM](/aggregate-functions#approx_sum) | Aggregate Functions | Allows the aggregation engine to use a faster, non-deterministic ordering to summate floating-point columns. |
| [ARRAY\[\]](/array-functions-and-operators) | Array Functions | -compliant constructor. The type of the array is deduced from the elements. |
| [ARRAY\_AGG](/aggregate-functions#array_agg) | Aggregate Functions | Returns an array containing every row from the expression. |
| [ARRAY\_APPEND](/array-functions-and-operators) | Array Functions | Add value to the back of an array. |
| [ARRAY\_ARGMAX](/array-functions-and-operators) | Array Functions | Returns the corresponding argmax of the array as a BIGINT index. |
| [ARRAY\_ARGMIN](/array-functions-and-operators) | Array Functions | Returns the corresponding argmin of the array as a BIGINT index. |
| [ARRAY\_CAT](/array-functions-and-operators) | Array Functions | Concatenate 2 arrays into a new one. |
| [ARRAY\_CAT\_DISTINCT](/array-functions-and-operators#array_cat_distinct) | Array Functions | Concatenates two or more arrays in the order of the input arguments. |
| [ARRAY\_CAP](/transform-data-in-data-pipelines#array-data-transformation-functions) | Special Data Pipeline Transformation Functions | Restrict the length of an array to a maximum number of elements. |
| [ARRAY\_COMPACT](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Removes NULL values from the array. |
| [ARRAY\_CONCAT\_AGG](/aggregate-functions#array_concat_agg) | Aggregate Functions | Returns an array that concatenates arrays across rows. |
| [ARRAY\_CONTAINS](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Returns `true` if the array contains the specified value. |
| [ARRAY\_DISTINCT](/array-functions-and-operators#array_distinct) | Array Functions | Removes duplicates from an array while preserving the first occurrence order. |
| [ARRAY\_LENGTH](/array-functions-and-operators) | Array Functions | Return the number of elements of a given array. |
| [ARRAY\_MAX](/array-functions-and-operators) | Array Functions | Returns the corresponding maximum of the array. |
| [ARRAY\_MIN](/array-functions-and-operators) | Array Functions | Returns the corresponding minimum of the array. |
| [ARRAY\_POSITION](/array-functions-and-operators) | Array Functions | Returns the position of the first matching scalar in the array. |
| [ARRAY\_POSITIONS](/array-functions-and-operators) | Array Functions | Returns all elements stored in the right array and returns their respective positions in the left array. |
| [ARRAY\_PREPEND](/array-functions-and-operators) | Array Functions | Add value to the front of an array. |
| [ARRAY\_REMOVE](/array-functions-and-operators) | Array Functions | Remove value from the array. |
| [ARRAY\_REPLACE](/array-functions-and-operators) | Array Functions | Replace value by another in an array. |
| [ARRAY\_SORT](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Sort and return the input array based on the natural ordering of its elements or the specified Lambda function. |
| [ARRAY\_SUM](/array-functions-and-operators) | Array Functions | Returns the sum of the array. The array must be one-dimensional and contain numeric values. NULL values do not contribute to the sum. |
| [ARRAY\_TO\_STRING](/array-functions-and-operators) | Array Functions | Converts array to a list of elements separated by 'delimiter'. |
| [ASCII](/character-and-binary-functions#ascii) | Character and Binary Functions | Returns the ASCII code value of the leftmost character of the character value. |
| [ASIN](/math-functions-and-operators#asin) | Math Functions | Returns the inverse sine of a specified floating-point number. |
| [ASINH](/math-functions-and-operators#asinh) | Math Functions | Returns the hyperbolic arc-sine of a specified floating-point number. |
| [ATAN](/math-functions-and-operators#atan) | Math Functions | Returns the inverse tangent of a specified floating-point number. |
| [ATAN2](/math-functions-and-operators#atan2) | Math Functions | Returns the inverse tangent of two numeric, floating-point values. |
| [ATANH](/math-functions-and-operators#atanh) | Math Functions | Returns the hyperbolic arc-tangent of a specified floating-point number. |
| [AVG](/aggregate-functions#avg) | Aggregate Functions | Average, or arithmetic mean, over the set. |
| [BICDF](/math-functions-and-operators#bicdf) | Math Functions | The cumulative distribution function of the standard bivariate normal distribution. |
| [BIGINT](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type `bigint`. |
| [BINARY](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses a hexadecimal string (such as 0x54ab) to create a binary value. Letters can be of either case. |
| [BIPDF](/math-functions-and-operators#bipdf) | Math Functions | The probability density function of the standard bivariate normal distribution. |
| [BIT\_LENGTH](/character-and-binary-functions#bit_length) | Character and Binary Functions | Returns the length of the character value in bits. |
| [BITAND](/math-functions-and-operators#bitand) | Math Functions | Alias for the BITFUNC syntax `BITFUNC('AND', x, y)`. |
| [BITFUNC](/math-functions-and-operators#bitfunc) | Math Functions | Performs a variety of bit operations. Can be any of these string literals: `'AND'`, `'OR'`, or `'XOR'`. |
| [BITNOT](/math-functions-and-operators#bitnot) | Math Functions | Returns the bitwise negation of integral\_x. |
| [BITOR](/math-functions-and-operators#bitor) | Math Functions | Alias for the BITFUNC syntax BITFUNC('OR', x, y). |
| [BITXOR](/math-functions-and-operators#bitxor) | Math Functions | Alias for the BITFUNC syntax BITFUNC('XOR', x, y). |
| [BOOLAND](/math-functions-and-operators#booland) | Math Functions | Alias for the BOOLFUNC syntax BOOLFUNC('AND', x, y). |
| [BOOLEAN](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses a string to create a Boolean value. The string must contain either true or false. It is case-insensitive. |
| [BOOLFUNC](/math-functions-and-operators#boolfunc) | Math Functions | Performs a Boolean logical evaluation on arguments x and y. Can be any of these string literals: `'AND'`, `'OR'`, or `'XOR'`. |
| [BOOLNOT](/math-functions-and-operators#boolnot) | Math Functions | Returns the logical negation of the BOOLFUNC function. |
| [BOOLOR](/math-functions-and-operators#boolor) | Math Functions | Alias for the BOOLFUNC syntax BOOLFUNC('OR', x, y). |
| [BOOLXOR](/math-functions-and-operators#boolxor) | Math Functions | Alias for the BOOLFUNC syntax BOOLFUNC('XOR', x, y). |
| [BTRIM](/character-and-binary-functions#btrim) | Character and Binary Functions | Alias for TRIM. |
| [BYTE](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type byte. |
| [CANCEL](/query-management#cancel) | Query Management | Cancels a running query based on its specific query identifier. |
| [CASE](/other-functions-and-expressions#case) | Conditional Functions | CASE operates similarly to conditional scripting in other programming languages, allowing it to function like an if / then / else statement or as a switch statement. |
| [CASE WHEN](/transform-data-in-data-pipelines#special-data-pipeline-transformation-functions)
| Special Data Pipeline Transformation Functions | Returns the `result` value based on whether an expression is `true`. |
| [CAST\_TO\_ARRAY](/array-functions-and-operators) | Array Functions | Casts the elements of the array to another type. |
| [CAST\_TO\_TUPLE](/tuple-functions-and-operators) | Tuple Functions | Converts a tuple into another tuple of a different type. |
| [CBRT](/math-functions-and-operators#cbrt) | Math Functions | Returns the cube root of the numeric value x. |
| [CDF](/math-functions-and-operators#cdf) | Math Functions | The cumulative distribution function of the standard normal distribution. Returns the probability that a random sample is less than or equal to the specified value. |
| [CEIL](/math-functions-and-operators#ceil) | Math Functions | Returns the nearest integer greater than or equal to x. |
| [CEILING](/math-functions-and-operators#ceiling) | Math Functions | Alias for CEIL. |
| [CENTURY](/date-and-time-functions#century) | Date and Time Functions | Returns the number of centuries. |
| [CHAR](/array-functions-and-operators) | Array Functions | Converts array to its string representation. |
| [CHAR](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Creates a string version of the numeric value. |
| [CHAR](/tuple-functions-and-operators) | Tuple Functions | Converts a tuple to its string representation. |
| [CHAR\_LENGTH](/character-and-binary-functions#char_length) | Character and Binary Functions | Alias for LENGTH. |
| [CHARACTER\_LENGTH](/character-and-binary-functions#character_length) | Character and Binary Functions | Alias for LENGTH. |
| [CHR](/character-and-binary-functions#chr) | Character and Binary Functions | Converts an integer value to a string. |
| [COALESCE](/other-functions-and-expressions#coalesce) | Conditional Functions | Evaluates to the first argument that is not NULL, or NULL if all arguments are NULL. |
| [COEFFICIENT\_OF\_DETERMINATION](/aggregate-functions#coefficient_of_determination) | Aggregate Functions | Computes the coefficient of determination (R²) between actual and predicted values. |
| [COMMIT](/other-functions-and-expressions#commit) | System Functions | Returns the most recent commit hash of the database to which the client is currently connected. |
| [CONCAT](/character-and-binary-functions#concat) | Character and Binary Functions | Concatenates two values, which must both be either binary, hash, or string data types. This function is equivalent to the \|\| operator. |
| [CONFUSION\_MATRIX](/aggregate-functions#confusion_matrix) | Aggregate Functions | Returns a structured representation of the counts for every combination of actual and predicted class labels relative to a specified positive class. |
| [CONVERT\_LOCAL\_TIMESTAMP\_TO\_UTC](/time-zone-functions#convert_local_timestamp_to_utc) | Time Zone Functions | The function converts a timestamp in a specified local time zone to the UTC time zone. |
| [CONVERT\_UTC\_TIMESTAMP\_TO\_LOCAL](/time-zone-functions#convert_utc_timestamp_to_local) | Time Zone Functions | The function converts a timestamp from the UTC time zone to a specified local time zone. |
| [CORR](/aggregate-functions#corr) | Aggregate Functions | Alias for CORRELATION. |
| [CORRELATION](/aggregate-functions#correlation) | Aggregate Functions | Sample correlation. |
| [CORRELATIONP](/aggregate-functions#correlationp) | Aggregate Functions | Population correlation. |
| [COS](/math-functions-and-operators#cos) | Math Functions | Returns the cosine of x. |
| [COSH](/math-functions-and-operators#cosh) | Math Functions | Returns the hyperbolic cosine of x. |
| [COT](/math-functions-and-operators#cot) | Math Functions | Returns the cotangent of x. |
| [COUNT](/aggregate-functions#count) | Aggregate Functions | Number of rows in the set. |
| [COVAR\_POP](/aggregate-functions#covar_pop) | Aggregate Functions | Alias for COVARIANCEP. |
| [COVAR\_SAMP](/aggregate-functions#covar_samp) | Aggregate Functions | Alias for COVARIANCE. |
| [COVARIANCE](/aggregate-functions#covariance) | Aggregate Functions | Sample covariance. |
| [COVARIANCEP](/aggregate-functions#covariancep) | Aggregate Functions | Population covariance. |
| [CROSS\_ENTROPY\_LOSS](/array-functions-and-operators) | Array Functions | Returns the cross entropy loss of two arrays. |
| [CROSS\_ENTROPY\_LOSS](/matrix-functions-and-operators) | Matrix Functions | Returns the cross entropy loss of two one-dimensional matrices or vectors. |
| [CUME\_DIST](/window-aggregate-functions#cume_dist) | Window Aggregate Functions | Returns a number 0 \< n 1 and can be used to calculate the percentage of values less than or equal to the current value in the group. |
| [CURDATE](/date-and-time-functions#curdate) | Date and Time Functions | Alias for CURRENT\_DATE. |
| [CURRENT\_DATABASE](/other-functions-and-expressions#current_database) | System Functions | Alias for DATABASE. |
| [CURRENT\_DATE](/date-and-time-functions#current_date) | Date and Time Functions | Returns the current date in the format YYYY-MM-DD. |
| [CURRENT\_GROUPS](/other-functions-and-expressions#current_groups) | System Functions | Returns the fully-qualified names of groups in the database. |
| [CURRENT\_NODE](/other-functions-and-expressions#current_node) | System Functions | Returns the name of the SQL Node where the current query executes. The name of the node corresponds to the name column in the `sys.nodes` system catalog table. |
| [CURRENT\_NODE\_ID](/other-functions-and-expressions#current_node_id) | System Functions | Returns the identifier of the SQL Node where the current query executes. |
| [CURRENT\_SCHEMA](/other-functions-and-expressions#current_schema) | System Functions | Returns the name of the current schema. |
| [CURRENT\_SESSION\_ID](/other-functions-and-expressions#current_session_id) | System Functions | Returns the Universally Unique IDentifier (UUID) of the current session. |
| [CURRENT\_SYSTEM](/other-functions-and-expressions#current_system) | System Functions | Returns the name of the system. |
| [CURRENT\_TIME](/date-and-time-functions#current_time) | Date and Time Functions | Returns the current time as a TIME value (e.g., `hh:mm:ss.mm`). |
| [CURRENT\_TIMESTAMP](/date-and-time-functions#current_timestamp) | Date and Time Functions | Returns the current date and time as a TIMESTAMP value (e.g., YYYY-MM-DD hh🇲🇲ss.mmm). |
| [CURRENT\_USER](/other-functions-and-expressions#current_user) | System Functions | Returns the user for the current connection. |
| [DATABASE](/other-functions-and-expressions#database) | System Functions | Returns the name of the database to which the client is currently connected. |
| [DATE](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses a string in the form 'YYYY-MM-DD' to create a date. Extra characters are ignored. |
| [DATE\_PART](/date-and-time-functions#date_part) | Date and Time Functions | Alias for EXTRACT. |
| [DATE\_TRUNC](/date-and-time-functions#date_trunc) | Date and Time Functions | Returns the date or timestamp entered, truncated to the specified precision. |
| [DATEADD](/date-and-time-functions#dateadd) | Date and Time Functions | Adds a specified number value (as a signed integer) to a specified date part of an input date value, and then returns that modified value. |
| [DATEDIFF](/date-and-time-functions#datediff) | Date and Time Functions | This function returns an INT representing the difference between two date or time values in a specified date or time unit. |
| [DAY](/date-and-time-functions#day) | Date and Time Functions | Alias for DAY\_OF\_MONTH. |
| [DAY\_OF\_MONTH](/date-and-time-functions#day_of_month) | Date and Time Functions | Extracts the day-of-month portion of a timestamp or date as an integer. |
| [DAY\_OF\_WEEK](/date-and-time-functions#day_of_week) | Date and Time Functions | Returns an integer, in the range of 1 to 7, that represents the day of the week. |
| [DAY\_OF\_YEAR](/date-and-time-functions#day_of_year) | Date and Time Functions | Returns an integer in the range 1 to 366 that represents the day of the year. |
| [DAYS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type days to be used in date calculations. |
| [DECADE](/date-and-time-functions#decade) | Date and Time Functions | The decade is the year divided by 10. |
| [DECIMAL](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type decimal. |
| [DEGREES](/math-functions-and-operators#degrees) | Math Functions | Returns the corresponding angle in degrees for x in radians. |
| [DELTA](/window-aggregate-functions#delta) | Window Aggregate Functions | Computes the finite difference between successive values of expression under the specified ordering. This is a backwards difference, which means that, at degree one, the value for a given row is the difference between the value of expression for that row and the previous row. |
| [DENSE\_RANK](/window-aggregate-functions#dense_rank) | Window Aggregate Functions | Assigns a number to each row in the result set with equal values having the same number. There will be no gaps between ranks. |
| [DERIVATIVE](/window-aggregate-functions#derivative) | Window Aggregate Functions | Computes the difference quotient between successive values of expression with respect to expression2. |
| [DET](/matrix-functions-and-operators) | Matrix Functions | Returns the determinant of the matrix as a double. |
| [DIV](/math-functions-and-operators#div) | Math Functions | Returns the result of x divided by y. If y is zero, returns NULL. |
| [DOT](/matrix-functions-and-operators) | Matrix Functions | Returns dot product of two one-dimensional matrices/vectors. |
| [DOUBLE](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type double. |
| [DOW](/date-and-time-functions#dow) | Date and Time Functions | Alias for DAY\_OF\_WEEK. |
| [DOY](/date-and-time-functions#doy) | Date and Time Functions | Alias for DAY\_OF\_YEAR. |
| [EIGEN](/matrix-functions-and-operators) | Matrix Functions | Returns eigenvalues and eigenvalues of a square matrix as a vector of pairs. |
| [ELEMENT\_AT](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Returns the element value of the array or tuple at the specified index. |
| [ENDSWITH](/character-and-binary-functions#endswith) | Character and Binary Functions | Returns true if x ends with y and false otherwise. |
| [EOMONTH](/date-and-time-functions#eomonth) | Date and Time Functions | Returns the last day of the timestamp or date. |
| [EPOCH](/date-and-time-functions#epoch) | Date and Time Functions | The number of seconds after 1970-01-01 00:00:00 UTC. |
| [ERF](/math-functions-and-operators#erf) | Math Functions | The error function is used for measurements that follow a normal distribution. |
| [ERFC](/math-functions-and-operators#erfc) | Math Functions | The complement of the error function. ERFC(x) = 1 - ERF(x). |
| [EXP](/math-functions-and-operators#exp) | Math Functions | Returns the exponential of x (e raised to the power of x). |
| [EXPLODE\_OUTER](/special-data-pipeline-transformation-functions#explode_outer) | Special Data Pipeline Transformation Functions | Expands a one-dimensional or multidimensional array into its elements with one element per row of output from the system. |
| [EXTRACT](/date-and-time-functions#extract) | Date and Time Functions | Extract a component from a timestamp or date. |
| [F1\_SCORE](/aggregate-functions#f1_score) | Aggregate Functions | Returns the harmonic mean of precision and recall for a specified positive class. |
| [FILTER](/special-data-pipeline-transformation-functions#filter) | Special Data Pipeline Transformation Functions | Filters elements in an array based on the logic in a lambda expression. |
| [FIRST\_VALUE](/window-aggregate-functions#first_value) | Window Aggregate Functions | Returns the first value in the ordered result set. |
| [FLATTEN](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Transforms an `N`-dimensional array into an `N-1`-dimensional array. |
| [FLOAT](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type float. |
| [FLOOR](/math-functions-and-operators#floor) | Math Functions | Returns the nearest integer less than or equal to x. |
| [FROBENIUS](/matrix-functions-and-operators) | Matrix Functions and Operators | Returns the Frobenius norm of a matrix. |
| [GAMMA](/math-functions-and-operators#gamma) | Math Functions | [Gamma function.](https://en.wikipedia.org/wiki/Gamma_function) |
| [GREATEST](/other-functions-and-expressions#greatest) | Conditional Functions | Returns the largest non-NULL value of all the arguments, or NULL if all the arguments are NULL. |
| [HASH](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Creates a fixed length binary value, with length ``, from a string, i.e. `0x1234abcd`. Zero extended if the string does not have enough bytes, truncated if it has too many. |
| [HEXBINX](/math-functions-and-operators#hexbinx) | Math Functions | Returns the x-coordinate of the center of the nearest hexagonal bin to the point (x, y). |
| [HEXBINY](/math-functions-and-operators#hexbiny) | Math Functions | Returns the y-coordinate of the center of the nearest hexagonal bin to the point (x, y). |
| [HINGE\_LOSS](/array-functions-and-operators) | Array Functions | Returns the hinge loss of two arrays. |
| [HINGE\_LOSS](/matrix-functions-and-operators) | Matrix Functions | Returns the hinge loss of two one-dimensional matrices or vectors. |
| [HLL\_SKETCH\_CREATE](/hyperloglog-functions#hll_sketch_create) | HyperLogLog Functions | Creates an HLL sketch from the data on a specified aggregated column. Returns a HASH((2^log2k) + 8) data representation of the sketch that you can store in a separate column. |
| [HLL\_SKETCH\_GET\_ESTIMATE](/hyperloglog-functions#hll_sketch_get_estimate) | HyperLogLog Functions | The scalar function converts a sketch into a distinct count estimate of a sketch value. Returns the distinct count estimate as a BIGINT. |
| [HLL\_SKETCH\_GET\_ESTIMATE\_BOUND](/hyperloglog-functions#hll_sketch_get_estimate_bound) | HyperLogLog Functions | Takes a HLL\_SKETCH column or an integral log2k literal value and returns the resulting bounding 95-percent confidence interval error proportion as a DOUBLE. |
| [HLL\_SKETCH\_TO\_STRING](/hyperloglog-functions#hll_sketch_to_string) | HyperLogLog Functions | The HLL\_SKETCH\_TO\_STRING scalar function takes a HLL\_SKETCH column or value and returns a string summary of the sketch. |
| [HLL\_SKETCH\_UNION (aggregate function)](/hyperloglog-functions#hll_sketch_union-aggregate-function) | HyperLogLog Functions | Merges multiple sketches in a single column into a unified sketch. All sketches must have the same precision. This function is an aggregate function and operates on a column. |
| [HLL\_SKETCH\_UNION (scalar function)](/hyperloglog-functions#hll_sketch_union-scalar-function) | HyperLogLog Functions | Merges two sketches into a new combined sketch. This function is a scalar function and operates row-wise. The scalar function merges two sketch columns with heterogeneous precisions into a sketch with the lower of the two precisions. |
| [HOUR](/date-and-time-functions#hour) | Date and Time Functions | Extracts the hour portion of a timestamp as an integer. |
| [HOURS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type hours. |
| [IDENTITY\_MATRIX](/matrix-functions-and-operators) | Matrix Functions | Returns an identity matrix of the specified dimension. |
| [IERF](/math-functions-and-operators#ierf) | Math Functions | The inverse of the ERF error function. |
| [IERFC](/math-functions-and-operators#ierfc) | Math Functions | The inverse of the complement of the error function. |
| [IF](/transform-data-in-data-pipelines#logical-operations-transformation-functions) | Special Data Pipeline Transformation Functions | Returns `T` if the expression `X` evaluates to `true`, or the function returns `F` if `X` evaluates to `false`. |
| [IF\_NULL](/other-functions-and-expressions#if_null) | Conditional Functions | Alias for COALESCE. |
| [INITCAP](/character-and-binary-functions#initcap) | Character and Binary Functions | For each word in the provided string, capitalize the first character if it is alphabetic. |
| [INSTR](/character-and-binary-functions#instr) | Character and Binary Functions | Returns the index position of the first occurrence where the character value char\_substring appears in the character value char by ignoring case. |
| [INTEGER](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type integer. |
| [INVERSE](/matrix-functions-and-operators) | Matrix Functions | Returns inverse of a square, invertible matrix. |
| [IP](/network-type-functions#ip) | Network Type Functions | Casts an IP data type from an IPV4 data type expression. |
| [IPV4](/network-type-functions#ipv4) | Network Type Functions | Casts an IPV4 address from an IPV6 address. |
| [ISDATE](/date-and-time-functions#isdate) | Date and Time Functions | Returns TRUE if the input argument can be successfully cast to a date. |
| [IS\_IPV4](/network-type-functions#is_ipv4) | Network Type Functions | Tests whether the database can convert the `IP` value to the `IPV4` data type. |
| [ISODOW](/date-and-time-functions#isodow) | Date and Time Functions | Extracts the day of the week based on ISO 8601, which ranges from Monday (1) to Sunday (7). |
| [JSON\_EXTRACT\_PATH\_TEXT](/character-and-binary-functions#json_extract_path_text) | Character and Binary Functions | Returns the value for the key-value pair referenced by a series of path elements in a JSON string. |
| [KILL](/query-management#kill) | Query Management | Cancels a running query based on its specific query identifier. |
| [KURTOSIS](/aggregate-functions#kurtosis) | Aggregate Functions | The sample over the set. |
| [KURTOSISP](/aggregate-functions#kurtosisp) | Aggregate Functions | The population over the set. |
| [LAG](/window-aggregate-functions#lag) | Window Aggregate Functions | Returns the row, which is the specified number backward from the current row. Default is 1 if offset is omitted. |
| [LAG\_VECTORS](/data-preparation#lag_vectors) | Data Preparation | Groups lagged columns generated by the `MULTI_LAGS` or `MULTI_LAGS_ZEROFILL` functions into vector columns. |
| [LAGS](/data-preparation#lags) | Data Preparation | Generates a series of lagged columns for a single variable in one statement. |
| [LAGS\_ZEROFILL](/data-preparation#lags_zerofill) | Data Preparation | Generates lagged columns for a single variable and replaces NULL values with `0`. |
| [LAST\_VALUE](/window-aggregate-functions#last_value) | Window Aggregate Functions | Returns the last value in the ordered result set. |
| [LCASE](/character-and-binary-functions#lcase) | Character and Binary Functions | Alias for LOWER. |
| [LEAD](/window-aggregate-functions#lead) | Window Aggregate Functions | Returns the row, which is the specified number forward from the current row. Default is 1 if offset is omitted. |
| [LEAKYRELU](/math-functions-and-operators#leakyrelu) | Math Functions | Returns the leaky rectified linear unit function of x. |
| [LEAST](/other-functions-and-expressions#least) | Conditional Functions | Returns the smallest non-NULL value of all arguments, or NULL if all arguments are NULL. |
| [LEFT](/character-and-binary-functions#left) | Character and Binary Functions | Return the number of characters in the string equal to the value integer. If the integer is negative, the function returns all but the last integer characters. |
| [LEFT\_SHIFT](/math-functions-and-operators#left_shift) | Math Functions | Returns x shifted to the left by y bits. |
| [LENGTH](/character-and-binary-functions#length) | Character and Binary Functions | For character data types, this value is in terms of characters. For binary data types, this value is in terms of bytes. |
| [LN](/math-functions-and-operators#ln) | Math Functions | Returns the natural logarithm of x. |
| [LOCATE](/character-and-binary-functions#locate) | Character and Binary Functions | Alias for POSITION. Returns the index position of the first occurrence of the character value substring in the character value string. |
| [LOG](/math-functions-and-operators#log) | Math Functions | Returns the base 10 logarithm of x. The optional base argument specifies the numeral system to use. If unspecified, the function defaults to base 10. |
| [LOG\_GAMMA](/math-functions-and-operators#log_gamma) | Math Functions | The natural logarithm of the absolute value of the gamma function. |
| [LOG\_LOSS](/array-functions-and-operators) | Array Functions | Returns the log loss of two arrays. |
| [LOG\_LOSS](/matrix-functions-and-operators) | Matrix Functions | Returns the log loss of two one-dimensional matrices or vectors. |
| [LOG2](/math-functions-and-operators#log2) | Math Functions | Returns the base 2 logarithm of x. |
| [LOGITS\_LOSS](/array-functions-and-operators) | Array Functions | Returns the logits loss of two arrays. |
| [LOGITS\_LOSS](/matrix-functions-and-operators) | Matrix Functions | Returns the logits loss of two one-dimensional matrices or vectors. |
| [LOOKUP](/load-data-from-external-sources-in-data-pipelines) | Special Data Pipeline Transformation Functions | Look up and load data in an external data source. |
| [LOWER](/character-and-binary-functions#lower) | Character and Binary Functions | Alias for LCASE. Convert string to lowercase. |
| [LPAD](/character-and-binary-functions#lpad) | Character and Binary Functions | Pad the input text to the specified length with the pad string on the left side. |
| [LTRIM](/character-and-binary-functions#ltrim) | Character and Binary Functions | Removes leading blanks from the string value string. |
| [LUPQ\_DECOMP](/matrix-functions-and-operators) | Matrix Functions | Returns LUPQ decomposition of a square matrix A as a tuple of 4 matrices where PAQ = LU. |
| [MAP\_KEYS](/transform-data-in-data-pipelines#other-data-transformation-functions) | Special Data Pipeline Transformation Functions | Returns the keys in the specified JSON string. |
| [MAP\_VALUES](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Returns the values in the specified JSON string. |
| [MATRIX\_DIM](/matrix-functions-and-operators) | Matrix Functions | Returns the dimensions of the specified matrix as a tuple of (row, col) integers. |
| [MAKE\_MATRIX\_IXJ](/matrix-functions-and-operators) | Matrix Functions | Creates an `ixj` matrix with elements `e_00`, `…`, `e_ij`. |
| [MAKEDATETIME](/date-and-time-functions#makedatetime) | Date and Time Functions | Returns a timestamp consisting of the specified date and time. |
| [MATRIX\_FROM\_TEXT](/matrix-functions-and-operators) | Matrix Functions | Creates a matrix from the specified string. |
| [MATRIX\_TRACE](/matrix-functions-and-operators) | Matrix Functions | Returns trace of a square matrix as a double. |
| [MAX](/aggregate-functions#max) | Aggregate Functions | Maximum value in the specified column. |
| [MD5](/character-and-binary-functions#md5) | Character and Binary Functions | Returns the hexadecimal string (all lowercase) representing the md5 hash of char. |
| [MEAN\_ABSOLUTE\_ERROR](/aggregate-functions#mean_absolute_error) | Aggregate Functions | Returns the mean absolute error (MAE) between actual and predicted values. |
| [MEAN\_ABSOLUTE\_PERCENTAGE\_ERROR](/aggregate-functions#mean_absolute_percentage_error) | Aggregate Functions | Returns the mean absolute percentage error (MAPE) between actual and predicted values. |
| [METADATA](/load-metadata-and-file-based-partitioned-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Extracts the metadata value for the specified key from available metadata for the pipeline. |
| [MICROSECONDS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type microseconds. |
| [MID](/character-and-binary-functions#mid) | Character and Binary Functions | Alias for SUBSTRING. |
| [MILLISECOND](/date-and-time-functions#millisecond) | Date and Time Functions | Extracts the millisecond portion of a timestamp as an integer. |
| [MILLISECONDS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type milliseconds. |
| [MIN](/aggregate-functions#min) | Aggregate Functions | Minimum value in the specified column. |
| [MINUTE](/date-and-time-functions#minute) | Date and Time Functions | Extracts the minute portion of a timestamp or date as an integer. |
| [MINUTES](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type minutes. |
| [MOD](/math-functions-and-operators#mod) | Math Functions | Returns the remainder from x divided by y. |
| [MONTH](/date-and-time-functions#month) | Date and Time Functions | Extracts the month portion of a timestamp or date as an integer. |
| [MONTH\_NAME](/date-and-time-functions#month_name) | Date and Time Functions | Returns the calendar name in English of the month for the specified date. |
| [MONTHS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type months to be used in date calculations. |
| [MONTHS\_BETWEEN](/date-and-time-functions#months_between) | Date and Time Functions | Returns the difference between the two dates or timestamps in months as a DOUBLE. |
| [MSECS](/date-and-time-functions#msecs) | Date and Time Functions | The seconds field, including fractional parts. The function multiplies the seconds part of the value by 1,000. |
| [MULTI\_LAGS](/data-preparation#multi_lags) | Data Preparation | Generates lagged columns for multiple variables at once. |
| [MULTI\_LAGS\_ZEROFILL](/data-preparation#multi_lags_zerofill) | Data Preparation | Generates lagged columns for multiple variables and replaces NULL values with `0`. |
| [MURMUR3](/other-functions-and-expressions#murmur3) | Conditional Functions | [Returns a 32-bit MurmurHash3 hash of the input value as an INTEGER data type.](https://github.com/aappleby/smhasher/blob/master/README.md) |
| [NANOS\_TO\_TIMESTAMP](/date-and-time-functions#nanos_to_timestamp) | Date and Time Functions | Convert a number of nanoseconds into a timestamp equivalent to the duration after the epoch time. |
| [NANOSECONDS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type nanoseconds. |
| [NEXT\_DAY](/date-and-time-functions#next_day) | Date and Time Functions | Returns the closest date after a specified date that lies on a specific day of the week. |
| [NOW](/date-and-time-functions#now) | Date and Time Functions | Alias for CURRENT\_TIMESTAMP. |
| [NTH\_VALUE](/window-aggregate-functions#nth_value) | Window Aggregate Functions | Returns the nth value in the ordered result set. |
| [NULL\_IF](/other-functions-and-expressions#null_if) | Conditional Functions | Returns the NULL value if two arguments are equal; otherwise, returns the first argument. |
| [NULL\_MATRIX](/matrix-functions-and-operators) | Matrix Functions | Returns a null matrix of the given (row, col) dimensions. |
| [OCTET\_LENGTH](/character-and-binary-functions#octet_length) | Character and Binary Functions | Returns the length in bytes of a character or binary value. |
| [PARSE\_DELIMITED\_ARRAY](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Converts a string of text data representing an array into a `CHAR[]`. |
| [PERCENT\_RANK](/window-aggregate-functions#percent_rank) | Window Aggregate Functions | The value returned is 0 \< n ≤ 1 and can be used to calculate the percentage of values less than the current group, excluding the highest value. |
| [PERCENTILE](/window-aggregate-functions#percentile) | Window Aggregate Functions | Returns the value that corresponds to the specified percentile (0 ≤ n ≤ 1) within the group. |
| [PI](/math-functions-and-operators#pi) | Math Functions | Returns the constant value of π. |
| [PMOD](/math-functions-and-operators#pmod) | Math Functions | Returns the smallest non-negative equivalence class of x % y. |
| [POSITION](/character-and-binary-functions#position) | Character and Binary Functions | Alias for LOCATE. |
| [POWER](/math-functions-and-operators#power) | Math Functions | Returns x raised to the power of y. |
| [PRECISION\_SCORE](/aggregate-functions#precision_score) | Aggregate Functions | Returns the precision score for a specified positive class. |
| [PROBIT](/math-functions-and-operators#probit) | Math Functions | The inverse of the cumulative distribution function. |
| [PRODUCT](/aggregate-functions#product) | Aggregate Functions | Product over the set. |
| [QR\_DECOMP](/matrix-functions-and-operators) | Matrix Functions | Returns QR decomposition of a matrix as a tuple of 2 matrices. |
| [QUARTER](/date-and-time-functions#quarter) | Date and Time Functions | Returns an integer between 1 and 4 that represents the quarter of the year in which the specified date falls. |
| [RADIANS](/math-functions-and-operators#radians) | Math Functions | Returns the corresponding angle in radians for x in degrees. |
| [RAND](/math-functions-and-operators#rand) | Math Functions | Takes no argument and returns a random DOUBLE value in the range \[0, 1). |
| [RAND\_UUID](/other-functions-and-expressions#rand_uuid) | Other Functions and Expressions | Generates a random UUID value (version 4) |
| [RANK](/window-aggregate-functions#rank) | Window Aggregate Functions | Assigns a number to each row in the result set with equal values having the same number. There can be gaps between ranks. |
| [RATIO\_TO\_REPORT](/window-aggregate-functions#ratio_to_report) | Window Aggregate Functions | Computes the ratio of a value to the sum of the set of values. |
| [RECALL\_SCORE](/aggregate-functions#recall_score) | Aggregate Functions | Returns the recall score for a specified positive class. |
| [ROC\_AUC\_SCORE](/aggregate-functions#roc_auc_score) | Aggregate Functions | Returns the area under the receiver operating characteristic (ROC) curve (AUC). |
| [RECORD\_UUID](/lat-transformation-functions#record_uuid) | Other Transformation Functions | Returns string that represents a unique identifier for the record in a specified pipeline for a specified file\_group or topic. |
| [REDUCE](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Applies a merge function to a starting value and all elements in the array, and then reduces the array to a single value. Optionally, specify a finish function for the returned single value. |
| [REGEXP\_COUNT](/character-and-binary-functions#regexp_count) | Character and Binary Functions | Searches a string for all occurrences of a regular expression pattern. |
| [REGEXP\_INSTR](/character-and-binary-functions#regexp_instr) | Character and Binary Functions | Searches a string using a regular expression pattern and returns an integer representing the start position or end position of the substring that matches. |
| [REGEXP\_REPLACE](/character-and-binary-functions#regexp_replace) | Character and Binary Functions | Searches a string for all occurrences of a regular expression pattern. |
| [REGEXP\_SUBSTR](/character-and-binary-functions#regexp_substr) | Character and Binary Functions | Returns one substring from a string that matches a specified regular expression pattern. |
| [RELU](/math-functions-and-operators#relu) | Math Functions | Returns the rectified linear unit function of x. |
| [REPEAT](/character-and-binary-functions#repeat) | Character and Binary Functions | Repeats the character value char a number of times equal to num. |
| [REPLACE](/character-and-binary-functions#replace)
| Character and Binary Functions | Replaces all occurrences of `substr_to_remove` in the character value string with `substr_to_replace`. |
| [REVERSE](/character-and-binary-functions#reverse) | Character and Binary Functions | Reverse the input string. |
| [RIGHT](/character-and-binary-functions#right) | Character and Binary Functions | Return the number of trailing characters in the string equal to the value integer. |
| [RIGHT\_SHIFT](/math-functions-and-operators#right_shift) | Math Functions | Returns x shifted to the right by y bits. |
| [ROUND](/date-and-time-functions#round) | Date and Time Functions | Returns the specified date or timestamp, rounded to the specified precision. |
| [ROUND](/math-functions-and-operators#round) | Math Functions | Returns x rounded to the nearest integer. |
| [ROW\_NUMBER](/window-aggregate-functions#row_number) | Window Aggregate Functions | Assigns a unique number to each row in the result set. |
| [RPAD](/character-and-binary-functions#rpad) | Character and Binary Functions | Pad the input text to the specified length with the pad string on the right side. |
| [RSUBSTRING](/character-and-binary-functions#rsubstring) | Character and Binary Functions | Returns the substring from the right side of a string, based on a specified length. |
| [RTRIM](/character-and-binary-functions#rtrim) | Character and Binary Functions | Removes leading blanks from the string value string. |
| [SECOND](/date-and-time-functions#second) | Date and Time Functions | Extracts the seconds portion of a timestamp as an integer. |
| [SECONDS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type seconds. |
| [SHA1](/character-and-binary-functions#sha1) | Character and Binary Functions | Uses the \[SHA-1]\([https://en.wikipedia.org/wiki/SHA-1#:\~:text=In%20cryptography%2C%20SHA%2D1%20(,rendered%20as%2040%20hexadecimal%20digits](https://en.wikipedia.org/wiki/SHA-1#:~:text=In%20cryptography%2C%20SHA%2D1%20\(,rendered%20as%2040%20hexadecimal%20digits).) cryptographic hash function to convert a string into a 40-character string representing the hexadecimal value of a 160-bit checksum. |
| [SHOW](/other-functions-and-expressions#show) | System Functions | The SHOW function enables you to explore the database and its metadata for user-defined items. |
| [SIGN](/math-functions-and-operators#sign) | Math Functions | Returns the positive (+1), zero (0), or negative (-1) sign of x. |
| [SIN](/math-functions-and-operators#sin) | Math Functions | Returns the sine of x. |
| [SINH](/math-functions-and-operators#sinh) | Math Functions | Returns the hyperbolic sine of x. |
| [SKEW](/aggregate-functions#skew) | Aggregate Functions | The sample over the set. |
| [SKEWP](/aggregate-functions#skewp) | Aggregate Functions | Computes the population skewness over the set of values. |
| [SMALLINT](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type `smallint`. |
| [SOFTMAX](/array-functions-and-operators) | Array Functions | Returns the softmax of the array. |
| [SOFTMAX](/matrix-functions-and-operators) | Matrix Functions | Returns the softmax of a one-dimensional matrix or vector. |
| [SPACE](/character-and-binary-functions#space) | Character and Binary Functions | Returns a string of repeated spaces equal to the number value, repeat. |
| [SPLIT\_PART](/character-and-binary-functions#split_part) | Character and Binary Functions | Split the value string based on the delimiter value. The function returns a substring from the split operation based on the index value (starting from 1). |
| [SPLIT\_TO\_ARRAY](/character-and-binary-functions#split_to_array) | Character and Binary Functions | Splits a string into an array of substrings. |
| [SQRT](/math-functions-and-operators#sqrt) | Math Functions | Returns the square root of x. |
| [SQUARE](/math-functions-and-operators#square) | Math Functions | Returns the square of x. |
| [ST\_ADDPOINT](/linestring-functions#st_addpoint) | Geospatial Linestring Function | Adds a POINT to the given LINESTRING at the specified 0-indexed location. |
| [ST\_ANGLE](/spatial-measurement#st_angle) | Geospatial Spatial Measurement | Calculates the angle between two lines. |
| [ST\_AREA](/spatial-measurement#st_area) | Geospatial Spatial Measurement | Returns the area of the specified geospatial object in the specified unit of measurement. |
| [ST\_ASBINARY](/conversion-functions#st_asbinary) | Geospatial Conversion Functions | Returns the well-known binary (WKB) representation of the specified geography. Alias of ST\_ASWKB. |
| [ST\_ASEWKT](/conversion-functions#st_asewkt) | Geospatial Conversion Functions | Returns a string that represents geographic coordinates of a specified POINT in the specified format. |
| [ST\_ASGEOJSON](/conversion-functions#st_asgeojson) | Geospatial Conversion Functions | Alias of ST\_ASBINARY. |
| [ST\_ASLATLONTEXT](/conversion-functions#st_aslatlontext) | Geospatial Conversion Functions | [Returns the GeoJSON representation of the specified geography using the IETF standards.](https://datatracker.ietf.org/doc/html/rfc7946) |
| [ST\_ASTEXT](/conversion-functions#st_astext) | Geospatial Conversion Functions | Alias of ST\_ASTEXT. |
| [ST\_ASWKB](/conversion-functions#st_aswkb) | Geospatial Conversion Functions | Alias of ST\_ASTEXT. |
| [ST\_ASWKT](/conversion-functions#st_aswkt) | Geospatial Conversion Functions | Alias of ST\_ASWKT and ST\_EWKT. Returns the WKT representation of the specified geography. |
| [ST\_AZIMUTH](/spatial-measurement#st_azimuth) | Geospatial Spatial Measurement | Returns the azimuth of the line from `point1` to `point2` in radians. |
| [ST\_BOUNDINGDIAGONAL](/spatial-operators#st_boundingdiagonal) | Geospatial Spatial Operators | Returns the diagonal LINESTRING from the minimum point to the maximum point of the bounding box that ST\_ENVELOPE returns. |
| [ST\_BUFFER](/spatial-operators#st_buffer) | Geospatial Spatial Operators | Returns a geography that contains all points where the distance from the geography is less than or equal to the specified distance. |
| [ST\_CENTROID](/point-constructors#st_centroid) | Geospatial Point Constructors | The geographic center of mass is calculated by taking the average of all points on a three-dimensional sphere, projecting the resultant point onto the sphere, and converting it back to latitude and longitude coordinates. |
| [ST\_CLOSESTPOINT](/spatial-operators#st_closestpoint) | Geospatial Spatial Operators | Returns the two-dimensional POINT of one specified geospatial object that is closest to a second specified geospatial object. |
| [ST\_CLUSTERDBSCAN](/spatial-relationships#st_clusterdbscan) | Geospatial Spatial Relationships | [Returns the cluster number for each input geography, based on a two-dimensional implementation of the density-based spatial clustering of applications with noise (DBSCAN) algorithm.](https://en.wikipedia.org/wiki/DBSCAN) |
| [ST\_CONTAINS](/spatial-relationships#st_contains) | Geospatial Spatial Relationships | Returns TRUE if the first geographic argument, geo1, contains the second geographic argument, geo2. |
| [ST\_CONTAINSPROPERLY](/spatial-relationships#st_containsproperly) | Geospatial Spatial Relationships | Returns true if geo2 lies entirely in the interior of geo1, and does not intersect or touch the boundary or exterior points. |
| [ST\_CONVEXHULL](/spatial-operators#st_convexhull) | Geospatial Spatial Operators | The convex hull is the smallest convex geometry that encloses the input geometry. |
| [ST\_COORDDIM](/attribute-functions#st_coorddim) | Geospatial Attribute Functions | Alias for ST\_NDIMS or ST\_NDIMENSION. Returns an INTEGER of the coordinate dimension of the specified geography. |
| [ST\_COVEREDBY](/spatial-relationships#st_coveredby) | Geospatial Spatial Relationships | Returns TRUE if no POINT in geo1 is outside of geo2. |
| [ST\_COVERS](/spatial-relationships#st_covers) | Geospatial Spatial Relationships | Returns TRUE if no POINT in geo2 is outside of geo1. |
| [ST\_CROSSES](/spatial-relationships#st_crosses) | Geospatial Spatial Relationships | Returns TRUE if two geospatial objects meet these criteria: The intersection of the geospatial interiors is not empty. The intersection is not equal to geo1 or geo2. Neither geospatial object is a single POINT. |
| [ST\_DIFFERENCEARRAY](/spatial-operators#st_differencearray) | Geospatial Spatial Operators | Returns an array containing any geospatial objects that are present in the first specified geospatial argument that are not found in the second geospatial argument. |
| [ST\_DIMENSION](/attribute-functions#st_dimension) | Geospatial Attribute Functions | Returns an INTEGER that represents the dimension of the specified geography. |
| [ST\_DISJOINT](/spatial-relationships#st_disjoint) | Geospatial Spatial Relationships | Returns true if the specified geographies have no intersection, including boundaries. Both geographic arguments can be different types. |
| [ST\_DISTANCE](/spatial-measurement#st_distance) | Geospatial Spatial Measurement | Returns the minimum distance between the specified arguments. |
| [ST\_DISTANCE](/spatiotemporal-measurement#st_distance) | Geospatial Spatiotemporal Measurement | Returns the two-dimensional interpolated minimum simultaneous distance between two LINESTRING-TIMESTAMP array pairs in the specified unit of measurement. |
| [ST\_DISTANCESPHERE](/spatial-measurement#st_distancesphere) | Geospatial Spatial Measurement | Returns the minimum distance between the specified arguments using a spherical computation. |
| [ST\_DISTANCESPHEROID](/spatial-measurement#st_distancespheroid) | Geospatial Spatial Measurement | Returns the minimum distance between the specified arguments using a spheroid computation. |
| [ST\_DWITHIN](/spatial-relationships#st_dwithin) | Geospatial Spatial Relationships | Returns TRUE if the geographies are within a specified distance in meters. |
| [ST\_ENDPOINT](/linestring-functions#st_endpoint) | Geospatial Linestring Function | Returns the endpoint of a specified LINESTRING. The returned value is a POINT. |
| [ST\_ENVELOPE](/spatial-operators#st_envelope) | Geospatial Spatial Operators | Returns a POLYGON that represents the minimum bounding box for the specified geography. |
| [ST\_EQUALS](/spatial-relationships#st_equals) | Geospatial Spatial Relationships | Returns TRUE if both geographies are spatially equal. |
| [ST\_EUCLIDEANDISTANCE3D](/spatial-measurement#st_euclideandistance3d) | Geospatial Spatial Measurement | Returns the minimum distance between two geospatial points with altitude values. |
| [ST\_EXPAND](/spatial-operators#st_expand) | Geospatial Spatial Operators | Returns the bounding box of a specified geospatial value, which is expanded by a specified length. |
| [ST\_EXTERIORRING](/spatial-operators#st_exteriorring) | Geospatial Spatial Operators | Returns a LINESTRING that represents the exterior ring of a provided POLYGON value. |
| [ST\_FLIPCOORDINATES](/spatial-operators#st_flipcoordinates) | Geospatial Spatial Operators | Returns a new geographic object with the X and Y coordinates switched using the specified argument. |
| [ST\_FORCE2D](/spatial-operators#st_force2d) | Geospatial Spatial Operators | Convert a geographic object into a two-dimensional geography. |
| [ST\_FORCECCW](/polygon-constructors#st_forceccw) | Geospatial Polygon Constructors | Creates a standardized polygon from an existing one. defines standardized as the exterior being counterclockwise (CCW) and all holes being clockwise (CW) oriented. |
| [ST\_GEOGPOINT](/point-constructors#st_geogpoint) | Geospatial Point Constructors | Creates and returns a POLYGON geography with a single point, defined by the longitude and latitude specified for the function. |
| [ST\_GEOHASH](/conversion-functions#st_geohash) | Geospatial Conversion Functions | Returns a string that represents the geohash of the input POINT. |
| [ST\_GEOMETRYTYPE](/attribute-functions#st_geometrytype) | Geospatial Attribute Functions | Returns a string representing the geometry type of the input value. |
| [ST\_HAUSDORFFDISTANCE](/spatial-measurement#st_hausdorffdistance) | Geospatial Spatial Measurement | Returns the Hausdorff distance between two geographies in a specified measurement. |
| [ST\_INTERIORRINGN](/spatial-operators#st_interiorringn) | Geospatial Spatial Operators | Returns a LINESTRING representing the interior ring of the specified POLYGON, which is specified by its index. (1-indexed) |
| [ST\_INTERSECTALL](/spatial-operators#st_intersectall) | Geospatial Spatial Operators | Returns the intersection of all geographies in the specified array. All geographies in the array must be the same type. |
| [ST\_INTERSECTION](/spatiotemporal-operators#st_intersection) | Geospatial Spatiotemporal Operators | Returns a tuple that represents the intersection of a spatiotemporal LINESTRING with a static geography. |
| [ST\_INTERSECTIONARRAY](/spatial-operators#st_intersectionarray) | Geospatial Spatial Operators | Returns a geography that represents the point-set intersection of two geographies. |
| [ST\_INTERSECTS](/spatial-relationships#st_intersects) | Geospatial Spatial Relationships | Returns TRUE if the specified geographies have an intersection, including boundaries. |
| [ST\_ISCCW](/spatial-relationships#st_isccw) | Geospatial Spatial Relationships | Alias for ST\_ISPOLYGONCCW. |
| [ST\_ISCLOSED](/spatial-relationships#st_isclosed) | Geospatial Spatial Relationships | Returns TRUE if an input POLYGON has an exterior that is counter-clockwise. |
| [ST\_ISEMPTY](/attribute-functions#st_isempty) | Geospatial Attribute Functions | Returns TRUE if the specified geography value is empty, such as 'POLYGON EMPTY'. |
| [ST\_ISPOLYGONCCW](/spatial-relationships#st_ispolygonccw) | Geospatial Spatial Relationships | Returns TRUE if an input LINESTRING has starting and ending points that are equal. |
| [ST\_ISPOLYGONCW](/spatial-relationships#st_ispolygoncw) | Geospatial Spatial Relationships | Returns TRUE if an input POLYGON has an exterior that is clockwise. |
| [ST\_ISRING](/spatial-relationships#st_isring) | Geospatial Spatial Relationships | Returns TRUE if the specified LINESTRING is closed and does not intersect itself. |
| [ST\_ISSIMPLE](/spatial-relationships#st_issimple) | Geospatial Spatial Relationships | For LINESTRING values, this function returns FALSE if any line segments intersect anywhere besides the endpoints. For POLYGON values, the function returns FALSE if either the exterior ring or any interior hole is not simple. |
| [ST\_ISVALID](/spatial-relationships#st_isvalid) | Geospatial Spatial Relationships | [Returns TRUE if the specified geospatial value is a well-formed and valid geography according to the OGC standards.](https://www.ogc.org/standard/sfa/) |
| [ST\_LENGTH](/spatial-measurement#st_length) | Geospatial Spatial Measurement | Returns the length of the specified line in the specified measurement unit. |
| [ST\_LENGTH2D](/spatial-measurement#st_length2d) | Geospatial Spatial Measurement | Alias for ST\_LENGTH. |
| [ST\_LINEFROMEWKT](/linestring-constructors#st_linefromewkt) | Geospatial Linestring Constructor | Creates a LINESTRING from the specified CHAR. |
| [ST\_LINEFROMGEOJSON](/linestring-constructors#st_linefromgeojson) | Geospatial Linestring Constructor | Creates a LINESTRING represented by the specified GeoJSON. |
| [ST\_LINEFROMTEXT](/linestring-constructors#st_linefromtext) | Geospatial Linestring Constructor | Creates a LINESTRING from a specified CHAR. The CHAR must be a LINESTRING value in WKT format. |
| [ST\_LINEFROMWKB](/linestring-constructors#st_linefromwkb) | Geospatial Linestring Constructor | Creates a LINESTRING from the specified BINARY. The BINARY value must be a LINESTRING in WKB format. |
| [ST\_LINEGETALLTIMESATPOINT](/spatiotemporal-operators#st_linegetalltimesatpoint) | Geospatial Spatiotemporal Operators | Returns a timestamp array of all times when the specified LINESTRING value intersects the specified POINT value. |
| [ST\_LINEGETPOINTATTIME](/spatiotemporal-operators#st_linegetpointattime) | Geospatial Spatiotemporal Operators | Returns a POINT within the bounds of the specified LINESTRING that corresponds to the interpolated point at the specified TIMESTAMP value. |
| [ST\_LINEGETTIMEATPOINT](/spatiotemporal-operators#st_linegettimeatpoint) | Geospatial Spatiotemporal Operators | Returns the interpolated time of the specified POINT on the specified LINESTRING that is paired with a TIMESTAMP ARRAY. |
| [ST\_LINEINTERPOLATEPOINT](/linestring-functions#st_lineinterpolatepoint) | Geospatial Linestring Function | Returns a POINT along a LINESTRING based on a specified fraction of its total length. |
| [ST\_LINELOCATEPOINT](/linestring-functions#st_linelocatepoint) | Geospatial Linestring Function | Similar to ST\_LINEINTERPOLATEPOINT, this function computes a fraction based on where a specified POINT is located along the length of a specified LINESTRING. |
| [ST\_LINESTRING](/linestring-constructors#st_linestring) | Geospatial Linestring Constructor | Creates a LINESTRING based on the specified inputs. |
| [ST\_LINESUBSTRING](/linestring-functions#st_linesubstring) | Geospatial Linestring Function | Returns a LINESTRING that is a substring of a specified line that starts and ends at the specified fractions of its total length. |
| [ST\_LONGESTLINE](/spatial-operators#st_longestline) | Geospatial Spatial Operators | Returns the longest LINESTRING between two given geospatial arguments. |
| [ST\_LONGESTLINE](/spatiotemporal-operators#st_longestline) | Geospatial Spatiotemporal Operators | With the specified two LINESTRING-TIMESTAMP ARRAY pairs, this function returns a two-point LINESTRING that represents the maximum distance between points at a concurrent time. |
| [ST\_MAKEENVELOPE](/spatial-operators#st_makeenvelope) | Geospatial Spatial Operators | Returns a POLYGON with vertices that represent the minimum bounding box for the specified coordinates. |
| [ST\_MAKELINE](/linestring-constructors#st_makeline) | Geospatial Linestring Constructor | Alias for ST\_LINESTRING. |
| [ST\_MAKEPOINT](/point-constructors#st_makepoint) | Geospatial Point Constructors | Alias for ST\_POINT. |
| [ST\_MAKEPOLYGON](/polygon-constructors#st_makepolygon) | Geospatial Polygon Constructors | Alias for ST\_POLYGON. |
| [ST\_MAXDISTANCE](/spatial-measurement#st_maxdistance) | Geospatial Spatial Measurement | Returns maximum distance between the specified arguments. |
| [ST\_MAXDISTANCE](/spatiotemporal-measurement#st_maxdistance) | Geospatial Spatiotemporal Measurement | Returns the two-dimensional interpolated maximum cotemporal distance between two LINESTRING-TIMESTAMP array pairs in the specified unit of measurement. |
| [ST\_MEMSIZE](/attribute-functions#st_memsize) | Geospatial Attribute Functions | Returns an INTEGER representing the number of bytes in memory required to store the specified geography. |
| [ST\_MINIMUMBOUNDINGCIRCLE](/spatial-operators#st_minimumboundingcircle) | Geospatial Spatial Operators | Returns the smallest circle POLYGON that contains the specified geographic object. |
| [ST\_MULTIDIFFERENCEARRAY](/spatial-operators#st_multidifferencearray) | Geospatial Spatial Operators | Returns an array of geographies that represents the parts of the union of the geographies in the first array that do not intersect with the union of geographies in the second array. |
| [ST\_MINIMUMDISTANCETOSURFACE](/spatial-measurement#st_minimumdistancetosurface) | Geospatial Spatial Measurement | Calculates the shortest distance between any point along a Euclidean line segment in three-dimensional space and the surface of the Earth. |
| [ST\_MULTIINTERSECTIONARRAY](/spatial-operators#st_multiintersectionarray) | Geospatial Spatial Operators | When you specify two arrays of geospatial objects, this function returns an array of any intersections. |
| [ST\_MULTISYMDIFFERENCEARRAY](/spatial-operators#st_multisymdifferencearray) | Geospatial Spatial Operators | When you specify two arrays of geospatial objects, this function returns an array of any geospatial values that do not intersect. |
| [ST\_MULTIUNIONARRAY](/spatial-operators#st_multiunionarray) | Geospatial Spatial Operators | When you specify two arrays of geospatial objects, this function returns one array that represents a union of all geographies in both arrays. |
| [ST\_NDIMENSION](/attribute-functions#st_ndims-or-st_ndimension) | Geospatial Attribute Functions | Alias for ST\_COORDDIM. |
| [ST\_NDIMS](/attribute-functions) | Geospatial Attribute Functions | Alias for ST\_COORDDIM. |
| [ST\_NPOINTS](/attribute-functions#st_npoints-or-st_numpoints) | Geospatial Attribute Functions | Returns an INTEGER representing the number of POINT values in a specified geography. |
| [ST\_NRINGS](/spatial-operators#st_nrings) | Geospatial Spatial Operators | Returns the number of rings of the specified POLYGON, including both interior and exterior rings. |
| [ST\_NUMINTERIORRING](/spatial-operators#st_numinteriorrings-or-st_numinteriorring) | Geospatial Spatial Operators | Returns the number of interior rings of the specified POLYGON. |
| [ST\_NUMINTERIORRINGS](/spatial-operators) | Geospatial Spatial Operators | Returns the number of interior rings of the specified POLYGON. |
| [ST\_NUMPOINTS](/attribute-functions) | Geospatial Attribute Functions | Returns an INTEGER representing the number of POINT values in a specified geography. |
| [ST\_OVERLAPS](/spatial-relationships#st_overlaps) | Geospatial Spatial Relationships | Returns TRUE if both geographic arguments are of the same dimension and they intersect each other, but neither contains the other. |
| [ST\_PERIMETER](/spatial-measurement#st_perimeter) | Geospatial Spatial Measurement | Returns the length of the exterior (outer ring) of the POLYGON in the specified unit of measurement. |
| [ST\_PERIMETER2D](/spatial-measurement#st_perimeter2d) | Geospatial Spatial Measurement | Alias for ST\_PERIMETER. |
| [ST\_POINT](/point-constructors#st_point) | Geospatial Point Constructors | Creates a POINT from the specified input arguments. |
| [ST\_POINTFROMEWKT](/point-constructors#st_pointfromewkt) | Geospatial Point Constructors | Alias for ST\_POINT. Creates a POINT using an EWKT-formatted CHAR as an input argument. |
| [ST\_POINTFROMGEOHASH](/point-constructors#st_pointfromgeohash) | Geospatial Point Constructors | Creates a POINT represented by the specified geohash. |
| [ST\_POINTFROMGEOJSON](/point-constructors#st_pointfromgeojson) | Geospatial Point Constructors | Creates a POINT represented by the specified GeoJSON value as an input argument. |
| [ST\_POINTFROMTEXT](/point-constructors#st_pointfromtext) | Geospatial Point Constructors | Alias for ST\_POINT(char). |
| [ST\_POINTFROMWKB](/point-constructors#st_pointfromwkb) | Geospatial Point Constructors | Alias for ST\_POINT(binary). |
| [ST\_POINTINSIDECIRCLE](/spatial-relationships#st_pointinsidecircle) | Geospatial Spatial Relationships | Returns TRUE if the geographic object is inside a circle that is centered at the specified point coordinates and with the specified radius. |
| [ST\_POINTN](/linestring-functions#st_pointn) | Geospatial Linestring Function | Returns the POINT value at a specified index of the given LINESTRING. |
| [ST\_POINTONSURFACE](/spatial-operators#st_pointonsurface) | Geospatial Spatial Operators | Returns a POINT guaranteed to intersect the specified geospatial object. |
| [ST\_POLYGON](/polygon-constructors#st_polygon) | Geospatial Polygon Constructors | Creates a POLYGON. |
| [ST\_POLYGONFROMEWKT](/polygon-constructors#st_polygonfromewkt) | Geospatial Polygon Constructors | Creates a POLYGON using an EWKT-formatted CHAR as an input argument. Alias for the ST\_POLYGON constructor. |
| [ST\_POLYGONFROMGEOJSON](/polygon-constructors#st_polygonfromgeojson) | Geospatial Polygon Constructors | Creates a POLYGON from the specified POINT, POINT array, LINESTRING, or POLYGON geography. |
| [ST\_POLYGONFROMTEXT](/polygon-constructors#st_polygonfromtext) | Geospatial Polygon Constructors | Alias for ST\_POLYGON(char). |
| [ST\_POLYGONFROMWKB](/polygon-constructors#st_polygonfromwkb) | Geospatial Polygon Constructors | Alias for ST\_POLYGON(binary). |
| [ST\_PROJECT](/spatial-operators#st_project) | Geospatial Spatial Operators | Returns a POINT by projecting a distance and an azimuth value from the specified starting POINT value. |
| [ST\_REDUCEPRECISION](/spatial-operators#st_reduceprecision) | Geospatial Spatial Operators | Returns a new geospatial object with all POINT values rounded to the specified decimal precision. |
| [ST\_RELATE](/spatial-relationships#st_relate) | Geospatial Spatial Relationships | Returns the [DE-9IM](https://postgis.net/workshops/postgis-intro/de9im.html) intersection string that represents the nature of the intersection with the specified geographies. |
| [ST\_REMOVEPOINT](/linestring-functions#st_removepoint) | Geospatial Linestring Functions | Removes a POINT value at a specified index from the specified line. |
| [ST\_REMOVEREPEATEDPOINTS](/spatial-operators#st_removerepeatedpoints) | Geospatial Spatial Operators | Returns a new geospatial object with no repeated POINT values. |
| [ST\_REVERSE](/spatial-operators#st_reverse) | Geospatial Spatial Operators | Returns a new geospatial object with the vertexes reversed. |
| [ST\_SEGMENTIZE](/spatial-operators#st_segmentize) | Geospatial Spatial Operators | Returns a geospatial object that the function modifies to have no segment longer than the specified max\_segment\_length in meters. |
| [ST\_SETPOINT](/linestring-functions#st_setpoint) | Geospatial Linestring Functions | Replaces a POINT value in a given LINESTRING at a specified index. The function returns the altered LINESTRING with the replaced point. |
| [ST\_SHORTESTLINE](/spatial-operators#st_shortestline) | Geospatial Spatial Operators | Returns the shortest LINESTRING between two specified geospatial arguments. |
| [ST\_SHORTESTLINE](/spatiotemporal-operators#st_shortestline) | Geospatial Spatiotemporal Operators | When you specify two LINESTRING-TIMESTAMP ARRAY pairs, this function returns a LINESTRING with two points that represents the minimum distance between points at a concurrent time. |
| [ST\_SIMPLIFY](/spatial-operators#st_simplify) | Geospatial Spatial Operators | Returns a simplified version of the specified geography, which is either a POINT or LINESTRING. |
| [ST\_SIMPLIFYARRAY](/spatial-operators#st_simplifyarray) | Geospatial Spatial Operators | Returns a POLYGON array that represents a simplified version of the specified geography, which is either a POINT, LINESTRING, or POLYGON. |
| [ST\_SNAPTOGRID](/spatial-operators#st_snaptogrid) | Geospatial Spatial Operators | Returns a new geography value with all POINT values rounded to the specified precisions. |
| [ST\_SRID](/attribute-functions#st_srid) | Geospatial Attribute Functions | Returns the EPSG code of the spatial reference identifier (SRID) of the input geography. |
| [ST\_STARTPOINT](/linestring-functions#st_startpoint) | Geospatial Linestring Functions | Returns the starting POINT value of the line. |
| [ST\_SYMDIFFERENCEARRAY](/spatial-operators#st_symdifferencearray) | Geospatial Spatial Operators | Returns a geographic array that contains the parts that are not common between two geographic objects, geo1 and geo2. |
| [ST\_TOTALSECONDSININTERSECTION](/spatiotemporal-measurement#st_totalsecondsinintersection) | Geospatial Spatiotemporal Measurement | Returns the total number of seconds spent in the intersection result calculated by the spatiotemporal version of ST\_INTERSECTION. |
| [ST\_TOUCHES](/spatial-relationships#st_touches) | Geospatial Spatial Relationships | Returns TRUE if the only POINT values in common between the two geographic arguments lie in the union of their boundaries. |
| [ST\_UNIONARRAY](/spatial-operators#st_unionarray) | Geospatial Spatial Operators | Performs a union of the input geography values to produce a geographic array. |
| [ST\_WHOLEEARTH](/polygon-constructors#st_wholeearth) | Geospatial Polygon Constructors | Returns the database internal representation of the whole earth polygon. |
| [ST\_WITHIN](/spatial-relationships#st_within) | Geospatial Spatial Relationships | Alias for ST\_CONTAINS. |
| [ST\_X](/attribute-functions#st_x) | Geospatial Attribute Functions | Returns the x value of the specified POINT. |
| [ST\_XMAX](/attribute-functions#st_xmax) | Geospatial Attribute Functions | Returns the maximum x value of the specified geography. |
| [ST\_XMIN](/attribute-functions#st_xmin) | Geospatial Attribute Functions | Returns the minimum x value of the specified geography. |
| [ST\_Y](/attribute-functions#st_y) | Geospatial Attribute Functions | Returns the y value of the specified POINT. |
| [ST\_YMAX](/attribute-functions#st_ymax) | Geospatial Attribute Functions | Returns the maximum y value of specified geography. |
| [ST\_YMIN](/attribute-functions#st_ymin) | Geospatial Attribute Functions | Returns the minimum y value of specified geography. |
| [STARTSWITH](/character-and-binary-functions#startswith) | Character and Binary Functions | Returns true if string starts with substring and false otherwise. |
| [STDEV](/aggregate-functions#stdev) | Aggregate Functions | Sample standard deviation. |
| [STDDEV](/aggregate-functions#stddev) | Aggregate Functions | Alias for STDEV. |
| [STDDEV\_POP](/aggregate-functions#stddev_pop) | Aggregate Functions | Alias for STDEVP. |
| [STDDEV\_SAMP](/aggregate-functions#stddev_samp) | Aggregate Functions | Alias for STDEV. |
| [STDEVP](/aggregate-functions#stdevp) | Aggregate Functions | Population standard deviation. |
| [STRING\_AGG](/aggregate-functions#string_agg) | Aggregate Functions | Returns a string concatenated from every row from the expression. The delimiter argument is optional. |
| [STRING\_TO\_ARRAY](/array-functions-and-operators) | Array Functions | Converts the string representation of an array (e.g., `'int[1,2,NULL]'`) into an array. |
| [STRING\_TO\_TUPLE](/tuple-functions-and-operators) | Tuple Functions | Converts the string representation of a tuple (e.g `'tuple<>(1,2,NULL)'`) into a tuple. |
| [STRPOS](/character-and-binary-functions#strpos) | Character and Binary Functions | Equivalent to using LOCATE as `LOCATE(substring, string)`. Note the reversed argument order. |
| [SUBSTR](/character-and-binary-functions#substr) | Character and Binary Functions | Alias for SUBSTRING. |
| [SUBSTRING](/character-and-binary-functions#substring) | Character and Binary Functions | Returns the substring of a character or binary value. |
| [SUBNET](/network-type-functions#subnet) | Network Type Functions | Computes the prefix from an `IP` or `IPV4` value and the size of the prefix. |
| [SUM](/aggregate-functions#sum) | Aggregate Functions | Sum over the set. |
| [SVD\_DECOMP](/matrix-functions-and-operators) | Matrix Functions | Returns SVD decomposition of a matrix as a tuple of 3 matrices. |
| [TAN](/math-functions-and-operators#tan) | Math Functions | Returns the tangent of x. |
| [TANH](/math-functions-and-operators#tanh) | Math Functions | Returns the hyperbolic tangent of x. |
| [TIME](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses the string to create a time value. The string must be in the form `'HH:MM[.SSSSSSSSS]'`. |
| [TIMESTAMP](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses a string and makes a timestamp value. The string must be in the format `'YYYY-MM-DD[ HH:MM][.SSSSSSSSS]'`. |
| [TIMESTAMP\_TO\_NANOS](/date-and-time-functions#timestamp_to_nanos) | Date and Time Functions | Convert timestamp into nanoseconds after epoch as BIGINT. |
| [TO\_ARRAY\_LENGTH](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Create the specified number of copies of any JSON object in an array. |
| [TO\_BASE](/math-functions-and-operators#to_base) | Math Functions | Converts an integer value to its string representation in a specified base (radix). |
| [TO\_CHAR](/character-and-binary-functions#to_char) | Character and Binary Functions | Converts a numeric, date, or timestamp value into a CHAR date type. |
| [TO\_DATE](/formatting-functions#to_date) | Formatting Functions | Converts a character value with the specified format to a DATE type. |
| [TO\_NUMBER](/formatting-functions#to_number) | Formatting Functions | Converts a character value with the specified format to a DECIMAL type. |
| [TO\_TIMESTAMP](/formatting-functions#to_timestamp) | Formatting Functions | Converts a character value with the specified format to a TIMESTAMP type. |
| [TRANSFORM](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Transforms an array based on the logic in a lambda expression. |
| [TRANSLATE](/character-and-binary-functions#translate) | Character and Binary Functions | Replaces specified characters in a provided string with a separate set of characters. |
| [TRANSPOSE](/matrix-functions-and-operators) | Matrix Functions | Returns transpose of the matrix. |
| [TRIM](/character-and-binary-functions#trim) | Character and Binary Functions | Alias for BTRIM. Trim leading and trailing blanks from the string. |
| [TRUNC](/math-functions-and-operators#trunc) | Math Functions | Returns x truncated to y decimal places. |
| [TRUNCATE](/math-functions-and-operators#truncate) | Math Functions | Alias for TRUNC. |
| [TUPLE()](/tuple-functions-and-operators) | Tuple Functions | Construct a tuple with the specified elements. Types of the tuple are inferred from the inner elements. |
| [TUPLE\<\<>>](/tuple-functions-and-operators) | Tuple Functions | Construct a tuple with the specified elements. NULL is also supported as an element. |
| [TYPE\[\]](/array-functions-and-operators) | Array Functions | Construct an array of SQL type TYPE giving the elements. |
| [TYPE\_STRIP](/other-functions-and-expressions#type_strip) | Other Functions and Expressions | Returns the SQL type of the specified value. |
| [UCASE](/character-and-binary-functions#ucase) | Character and Binary Functions | Alias for UPPER. |
| [UNNEST](/array-functions-and-operators#unnest) | Array Functions | Expand each element in an input array out to an individual row. |
| [UPPER](/character-and-binary-functions#upper) | Character and Binary Functions | Convert string to upper case. |
| [USECS](/date-and-time-functions#usecs) | Date and Time Functions | The seconds part of a time value, including fractional parts, returned as an integer. The function multiplies the seconds part of the value by 1,000,000. |
| [UUID](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses the string and makes a Universally Unique IDentifier (UUID) value. The string must be a valid UUID. |
| [UUID\_GENERATE](/other-functions-and-expressions#uuid_generate) | Other Functions and Expressions | Generates a random UUID value (version 4). |
| [VAR\_POP](/aggregate-functions#var_pop) | Aggregate Functions | Alias for VARIANCEP. |
| [VAR\_SAMP](/aggregate-functions#var_samp) | Aggregate Functions | Alias for VARIANCE. |
| [VARIANCE](/aggregate-functions#variance) | Aggregate Functions | Sample variance. |
| [VARIANCEP](/aggregate-functions#variancep) | Aggregate Functions | Population variance. |
| [VECTOR\_ARGMAX](/matrix-functions-and-operators) | Matrix Functions | Returns the argmax of a one-dimensional matrix or vector. |
| [VECTOR\_ARGMIN](/matrix-functions-and-operators) | Matrix Functions | Returns the argmin of a one-dimensional matrix or vector. |
| [VECTOR\_MAX](/matrix-functions-and-operators) | Matrix Functions | Returns the maximum of elements in a one-dimensional matrix/vector. |
| [VECTOR\_MIN](/matrix-functions-and-operators) | Matrix Functions | Returns the minimum of elements in a one-dimensional matrix/vector. |
| [VECTOR\_SUM](/matrix-functions-and-operators) | Matrix Functions | Returns the sum of elements in a one-dimensional matrix/vector. |
| [VERSION](/other-functions-and-expressions#version) | System Functions | Returns the version of the database to which the client is currently connected. |
| [WEEK](/date-and-time-functions#week) | Date and Time Functions | Returns the ISO-8601 week number, as an integer, of the specified timestamp or date value. |
| [WEEKS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type weeks to be used in date calculations. |
| [WIDTH\_BUCKET](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Creates `N` equal-width buckets in the range `[min,max)` as a histogram. |
| [YEAR](/date-and-time-functions#year) | Date and Time Functions | Extracts the year portion of a timestamp or date as an integer. |
| [YEARS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type years. |
| [ZERO\_MATRIX](/matrix-functions-and-operators) | Matrix Functions | Returns a zero matrix of the specified (row, col) dimensions. |
| [ZIP\_WITH](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Merges two or more input arrays, element-wise, into a single array using the trailing combining function. |
| [ZN](/other-functions-and-expressions#zn) | Conditional Functions | If x is NULL, returns 0. Otherwise, returns x. |
| [ZSCORE](/window-aggregate-functions#zscore) | Window Aggregate Functions | Zscore of the sample based on the `stddev()` function. |
| [ZSCOREP](/window-aggregate-functions#zscorep) | Window Aggregate Functions | Zscore of the sample based on the `stddevp()` function. |
# Alter Default Data Pipeline Behavior
Source: https://docs.ocient.com/alter-default-data-pipeline-behavior
Use the ALTER SYSTEM ALTER CONFIG SQL command in Ocient to tune data pipeline parameters such as execution time, partition counts, and type inference.
An administrator might configure some parameters that control the behavior of data pipelines to modify the default behavior across the System or specific nodes. You can use the `ALTER SYSTEM ALTER CONFIG` SQL statements to control the configuration parameters.
**Syntax**
```sql SQL theme={null}
ALTER SYSTEM ALTER CONFIG SET 'sql.pipelineparameters.parameter_name' 'parameter_value';
```
| **Parameter** | **Data** **Type** | **Description** |
| ----------------- | ----------------- | ------------------------------------------------------------------------------------ |
| `parameter_name` | string | The name of the pipeline parameter, either general or specific to the BINARY format. |
| `parameter_value` | string | The value for the pipeline parameter. |
**General Parameters**
| **General Parameter Name** | **Default** | **Data Type** | **Required Value and Description** |
| ---------------------------------------------------------- | ----------- | ---------------- | ------------------------------------------------------------------------------------------------------------------- |
| `sql.pipelineparameters.targetTimePerExtractorTask` | 600 | `UINT64_T` | Target execution time in seconds for `run_extractor` tasks for file loads. |
| `sql.pipelineparameters.defaultPartitionsPerExtractorTask` | -1 | `INT` | Number of partitions per task. If you set this parameter to -1, the number is based on available CPU cores. |
| `sql.pipelineparameters.defaultExtractorCores` | -1 | `INT` | Number of cores to use in a task. If you set this parameter to -1, the number is based on available CPU cores. |
**Binary Format Parameters**
You can modify these parameters to change the default behavior of the BINARY data format extraction.
| **Binary Format Parameter Name** | **Default** | **Data Type** | **Required Value and Description** |
| --------------------------------------------------------------- | ----------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sql.pipelineparameters.extract.binary.defaultEndianness` | `big` | string | The endianness of transforms when you do not specify it in another way. Supported values are `big` or `little`. |
| `sql.pipelineparameters.extract.binary.defaultCharset` | ibm1047 | string | Determines the default character set to use when you load data in the `BINARY` format. |
| `sql.pipelineparameters.extract.binary.defaultAutoTrimPadding` | true | Boolean | Determines the default for whether a padding character should be trimmed when decoding data in the `BINARY` format to a string. |
| `sql.pipelineparameters.extract.binary.defaultPaddingCharacter` | ' ' | `CHAR` | Determines the default padding character to trim from the end of a string when decoding data in the `BINARY` format. This parameter is effective only if the `extract.binary.defaultAutoTrimPadding` parameter is set to `true`. |
**Examples**
Set the target execution time for the extractor task to 600 seconds.
```sql SQL theme={null}
ALTER SYSTEM ALTER CONFIG SET 'sql.pipelineparameters.targetTimePerExtractorTask' 600;
```
Set the default endianness of transforms to little endian for the BINARY extract.
```sql SQL theme={null}
ALTER SYSTEM ALTER CONFIG SET 'sql.pipelineparameters.extract.binary.defaultEndianness' 'little';
```
The configuration values only go into effect after the `ALTER` SQL statement succeeds and you restart the affected nodes.
## Related Links
[Load Data](/load-data)
[Data Types for Data Pipelines](/data-types-for-data-pipelines)
[Data Formats for Data Pipelines](/data-formats-for-data-pipelines)
[Configuration Settings for Data Pipelines](/configuration-settings-for-data-pipelines)
# Amazon Web Services Ocient Installation
Source: https://docs.ocient.com/amazon-web-services-ocient-installation
Install and deploy an Ocient System on Amazon Web Services (AWS), including EC2 instance selection, storage configuration, and networking for cloud workloads.
This guide explains how to install an System in .
For details about AWS concepts, see these pages:
* [What is Amazon EC2?](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)
* [What is IAM?](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)
* [A Primer for Amazon Networking - VPC, Availability Zones & Subnets](https://aws.amazon.com/blogs/apn/amazon-vpc-for-on-premises-network-engineers-part-one/)
Ocient supports deployment in AWS for pilot or testing purposes, but this setup does not guarantee data durability. Stopping instances can result in permanent data loss.
The steps for deploying an Ocient System in AWS are:
1. Prepare AWS resources.
2. Set up an initial instance.
3. Create Amazon Machine Images (AMI) from the initial instance.
4. Launch other instances.
5. Follow the standard Ocient installation procedure.
## **Example Configuration**
The table below shows the recommended instance types for each node type.
| **Node Type** | **Instance Type** |
| -------------------- | ----------------------- |
| Foundation Nodes (3) | i3en.metal, i7ie.metal |
| Loader Nodes (1) | i3en.metal, i7ie.metal |
| SQL Nodes (1) | r5dn.metal, r6idn.metal |
This diagram shows an example of an Ocient cluster in AWS. The EC2 nodes (SQL, Loader, and Foundation) are deployed within a single subnet of an Amazon . AWS assigns each type of node to a separate security group (`sg1`, `sg2`, `sg3`).
## Prepare AWS Resources
Create and configure these AWS resources:
* The VPC and subnets for the Ocient System.
* Security groups to access the endpoints for each node type. For details about the network security configuration, see the [Ocient Security Guide](/ocient-security-guide).
* Identity and Access Management (IAM) roles.
If you are loading data from S3, the loader nodes require IAM access to an S3 bucket.
## Node Setup (SQL Role) for Initial Instance
Use this configuration for your AMI. Configuration steps differ depending on whether your setup uses a single-volume or multi-volume AMI.
### **Operating System (OS)**
To set up the AMI, you can use any Ocient-supported OS (see [Ocient System Requirements](/ocient-system-requirements)).
**Single-Volume AMI**
If you use a single-volume AMI, specify this configuration:
* Increase the root volume to 128GB or more.
**Multi-Volume AMI**
If you use a multi-volume AMI (e.g., CIS hardened (RHEL) 9), use this configuration:
* Increase root volume to 30GB or more.
* Increase Elastic Block Store (EBS) volume to 100GB or more.
This EBS volume supports key system directories in the image (`/home`, `/var`, `/var/log`, `/var/log/audit`, `/var/tmp`).
**Instance Type**
Use r5dn.metal or a similar instance type.
**Security Group**
Use one or more security groups with these rules:
* Allow SSH to the nodes.
* Allow communication internally between nodes.
* Allow access to SQL Node endpoints described in the [Ocient Security Guide](/ocient-security-guide).
Connect to your instance using Secure Shell (SSH). For details, see [Connect to your Linux instance using an SSH client](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-linux-inst-ssh.html).
This step applies only to multi-volume AMIs. If you are using a single-volume instance, skip this step.
If you use a multi-volume manager, extend the `/home` and `/var` LVM volumes and their file systems to fill up the expanded EBS volumes. These actions expand the LVM volume and the contained file system to accommodate the Ocient package, logging, and metadata.
These code examples show how to extend LVM volumes for a CIS RHEL 9 image.
Other AMI types might require different sizing. Contact Ocient support for the best sizing for your system for multi-volume instances.
**Example**
Resize the physical volumes of two drives to use their full capacity after expanding them (see Step 1).
```shell Shell theme={null}
sudo pvresize /dev/nvme0n1
sudo pvresize /dev/nvme1n1
```
Extend local volumes:
* Add 66 percent of the available free space in `vg-01` to the `var_vol` logical volume.
* Add all (100 percent) of the remaining free space in `vg-01` to the `home_vol` logical volume.
```shell Shell theme={null}
sudo lvextend -l +66%FREE /dev/vg-01/var_vol
sudo lvextend -l +100%FREE /dev/vg-01/home_vol
```
Extend the file system to use all available space on its underlying logical volume.
```shell Shell theme={null}
sudo xfs_growfs /home
sudo xfs_growfs /var
```
Update all your software packages to their latest versions and then reboot your instance.
For RHEL-compatible systems, use this command.
```shell Shell theme={null}
sudo dnf update
```
For -compatible systems, use this command.
```shell Shell theme={null}
sudo apt update
```
Reboot after the update.
```shell Shell theme={null}
sudo reboot
```
Copy over the `ocient` RPM or DEB package and install it.
For RHEL-compatible systems, use this command.
```shell Shell theme={null}
sudo dnf install ./ocient-RELEASE-XX.X.X-xxxxxxxxxxxxxx-x86_64.rpm
```
For Debian-compatible systems, use this command.
```shell Shell theme={null}
sudo apt install ./ocient-RELEASE-XX.X.X-xxxxxxxx.xxxxxx-xxxxxxxxxxxx-amd64.deb
```
Use the `ockernelparams` utility to set up kernel parameters automatically, including the huge pages configuration. Repeat this step on other nodes.
```shell Shell theme={null}
sudo /opt/ocient/scripts/ockernelparams --node-role sql
```
Reboot the system for the parameters to take effect.
```shell Shell theme={null}
sudo reboot
```
Check that the local storage drive is attached to the `uio` or `vfio` driver after reboot (the Ocient package installs a service that runs on startup to do this).
```shell Shell theme={null}
sudo /opt/ocient/scripts/nvme-driver-util.sh
```
For examples of attaching drivers to the NVMe drives, see [NVMe Drive Firmware Upgrade Process](/nvme-drive-firmware-upgrade-process#page-title).
If you are not using an OS-level firewall, skip this step.
If your base AMI includes a system firewall, you must configure rules that explicitly allow required network communication for your Ocient deployment. For details, see [Ocient Security Guide](/ocient-security-guide).
Required OS firewall rules:
* Allow all necessary ports and protocols between Ocient nodes by:
* Opening all TCP/UDP ports within the private network range (e.g., `10.0.0.0/16`).
* Or, allowing known Ocient ports.
* Allow external access where needed by:
* Enabling SSH access (port 22) from your administrator IP range.
* Allowing client access to SQL endpoints (for example, port 13101 or as specified in your setup).
* Opening any additional ports required for monitoring or management tools.
For a list of required ports, see [Network Exposure and Firewall](/ocient-security-guide#network-exposure-and-firewall).
## Create AMI
After your initial node is fully configured, you must replicate the setup process for the remaining nodes in your cluster. This action ensures consistency and allows for proper internal communication between nodes.
For details about creating an AMI, see [Creating an AMI from an Amazon EC2 Instance](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/tkv-create-ami-from-instance.html).
## Set Up Remaining Nodes to Launch the Remaining Instances
Go through this process for each of your remaining nodes.
Launch the remaining instances with these parameters:
* AMI — Use the AMI created in the [Node Setup (SQL Role) for Initial Instance](#node-setup-sql-role-for-initial-instance) step.
* Instance Type — Use `i3en.metal` or an equivalent instance that:
* Offers local NVMe SSDs for high-performance local storage.
* Has high throughput and network bandwidth for internal cluster communication.
* Security groups — Ensure these security rules are in place in the AWS security groups associated with the nodes:
* Allow SSH to the nodes.
* Allow internal communication between all Ocient nodes.
* Allow access to endpoints described in the [Ocient Security Guide](/ocient-security-guide).
Connect to your instance using Secure Shell (SSH). For details, see [Connect to your Linux instance using an SSH client](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connect-linux-inst-ssh.html).
Use the `ockernelparams` utility to set up kernel parameters automatically, including the `hugepages` parameters.
This example specifies a Foundation Node `foundation`. Use a different node type as necessary.
```shell Shell theme={null}
sudo /opt/ocient/scripts/ockernelparams --node-role foundation
```
## Bootstrap the Ocient System
Complete the bootstrapping process for your Ocient System. For details, see [Node Bootstrapping Reference](/node-bootstrapping-reference).
## Related Links
[Load Data](/load-data)
[Query Ocient](/query-ocient)
# callback
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/get-callback
openapi/generated-api-methods.json GET /v1/callback
Provides the authentication token for the OpenID Connect authentication process. The authorization server redirects to callback path after successful authentication. This endpoint receives the authorization code from the OpenID provider and exchanges it for a token. The provider redirects the user to the application callback URL specified in the initial authentication request. The client application should not call this endpoint directly. The OpenID provider automatically calls this endpoint in the authentication process.
# execute
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/get-execute
openapi/generated-api-methods.json GET /v1/execute/{database}
Alternative GET method for executing SQL statements. This method passes parameters as URL query parameters. This method does not support the params body parameter. Specify which database to access in the query parameters. If you do not specify a database, the connection defaults to the database from the authentication token or system settings. This method is most suitable for simple, read-only queries where the statement can be safely included in a URL. For complex queries or those with parameters, use the POST method instead.
# info
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/get-info
openapi/generated-api-methods.json GET /v1/info
Returns basic system version information about the Ocient System and the HTTP Query API server. You can use this endpoint to verify connectivity and to check compatible versions.
# execute
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/post-execute
openapi/generated-api-methods.json POST /v1/execute/{database}
Executes a SQL statement and returns the results. Supports requests for both regular and streaming responses. With streaming, results return as they become available using the HTTP chunked transfer encoding. Each chunk contains a valid JSON object that you can parse independently. For details on streaming, including large-response configuration, see the header parameters. You can specify the database in the request body. If you do not specify the database, the Ocient System defaults to the database specified in the authentication token or system settings. If you specify a database in the request, this value overrides any alternate database value specified as a body parameter.
# login
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/post-login
openapi/generated-api-methods.json POST /v1/login
Authenticates a user with a username and password and then returns a token for use in subsequent API calls. This request also sets a session cookie. Include the returned access token in the authorization header for subsequent requests in the format: Authorization: Bearer {token}.
# logout
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/post-logout
openapi/generated-api-methods.json POST /v1/logout
Log out from a SQL session. This clears any associated cookies, but does not invalidate any access tokens. This endpoint terminates only the cookie-based session. Any bearer tokens that were previously issued continue to work until they expire. You must discard any stored bearer tokens to complete the log out in a client application.
# sso_authentication
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/post-sso-authentication
openapi/generated-api-methods.json POST /v1/sso_authentication
Initiates the OpenID Connect authentication process by redirecting to the authorization server. This endpoint begins the standard OpenID Connect authentication process: 1. The client calls this endpoint with a callback path. 2. The server responds with a redirect to the identity provider. 3. The user authenticates with the identity provider. 4. The identity provider redirects back to the callback endpoint. 5. The client can exchange the authorization code for an access token.
# sso_device_grant
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/post-sso-device-grant
openapi/generated-api-methods.json POST /v1/sso_device_grant
Retrieve an OpenID device grant code that the Ocient System can verify and use with the sso_device_grant_verify endpoint. The device grant process is intended for devices with limited input capabilities or no web browser: 1. Call this endpoint to retrieve a user code and verification URI. 2. Display the user code and verification URI to the user. 3. The user visits the verification URI on another device and enters the code. 4. Call the sso_device_grant_verify endpoint to check if the user has completed verification.
# sso_device_grant_verify
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/post-sso-device-grant-verify
openapi/generated-api-methods.json POST /v1/sso_device_grant_verify
Verify a previous device grant request and return an authorization token. After initiating a device grant process with the sso_device_grant endpoint, use this endpoint to check if the user has completed the verification process. If the verification is successful, the endpoint returns an authorization token that you can use for subsequent API calls. You can call this endpoint multiple times until one of these outcomes: The user completes the verification (returns 200 OK with a token). The timeout is reached (returns error). The verification is canceled (returns error).
# sso_token
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/post-sso-token
openapi/generated-api-methods.json POST /v1/sso_token
Exchange an OpenID Connect identifier token or access token for an Ocient access token. This endpoint allows clients to directly exchange tokens without following the full browser-based authentication process. This exchange is useful for server-to-server scenarios or when the client already has a valid OpenID token from another process.
# token_refresh
Source: https://docs.ocient.com/api-playgrounds/ocient-http-query-api/post-token-refresh
openapi/generated-api-methods.json POST /v1/token_refresh
Refreshes an existing access token, extending its validity period. Call this endpoint before the current token expires to maintain uninterrupted access. Use the expires_in value from the login or previous refresh response to determine when to refresh the token. A common practice is to refresh when the token has half of its time remaining. On success, the endpoint returns the 200 response and a JSON object containing a new access token and metadata about the refreshed session. Replace the access token in your client with the new token returned by the endpoint, and use the expires_in value to decide when to refresh again.
# Get Configuration
Source: https://docs.ocient.com/api-playgrounds/system-information-rest-endpoints/get-configuration
openapi/generated-api-methods.json GET /v1/sysconfig
Retrieve the configuration about this node in JSON format.
# Get Configuration of Whole System
Source: https://docs.ocient.com/api-playgrounds/system-information-rest-endpoints/get-configuration-of-whole-system
openapi/generated-api-methods.json GET /v1/dbconfig
Retrieve the configuration of the system as a whole in JSON format.
# Get Configuration Parameters
Source: https://docs.ocient.com/api-playgrounds/system-information-rest-endpoints/get-configuration-parameters
openapi/generated-api-methods.json GET /v1/config
Retrieve values of configuration parameters.
# Get Statistics
Source: https://docs.ocient.com/api-playgrounds/system-information-rest-endpoints/get-statistics
openapi/generated-api-methods.json GET /v1/stats
Retrieve the statistics on each node in the database.
These fields appear in every entry returned in the response from the `http://oc1-lts0:9090/v1/stats` endpoint:
* `name`
* `time`
* `timestamp`
* `node`
* `value`
Additional fields can vary.
# Get Status
Source: https://docs.ocient.com/api-playgrounds/system-information-rest-endpoints/get-status
openapi/generated-api-methods.json GET /v1/status
Retrieve the status of the software running.
# Get Version
Source: https://docs.ocient.com/api-playgrounds/system-information-rest-endpoints/get-version
openapi/generated-api-methods.json GET /v1/version
Retrieve the version of the software running.
# Array Functions and Operators
Source: https://docs.ocient.com/array-functions-and-operators
Reference for Ocient SQL array functions and operators, with examples for constructing, accessing, slicing, concatenating, and aggregating array values.
The System enables you to work with data as arrays. The system contains functions that work with arrays and operators that enable you to parse data within arrays.
## ARRAY\_CAT\_DISTINCT
Concatenates two or more arrays in the order of the input arguments. After concatenation, the function removes duplicates from the result array while preserving the first occurrence order. The function skips any NULL input arguments. If all input arrays are NULL, the function returns a NULL. If at least one NULL element is present in the array, the function returns a NULL in the result array with the position of the first NULL the function finds in the order of the input arguments.
**Syntax**
```sql SQL theme={null}
ARRAY_CAT_DISTINCT(input_array1, input_array2 [, ...])
```
| **Argument** | **Data** **Type** | **Description** |
| ------------------------------------ | ----------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `input_array1, input_array2 [, ...]` | ARRAY | Two or more arrays for concatenation and deduplication. The elements within all input arrays must have the same data type. |
**Examples**
**Concatenate Two Arrays and Remove Duplicates**
Concatenate two arrays and remove duplicate elements within the arrays.
```sql SQL theme={null}
SELECT ARRAY_CAT_DISTINCT(ARRAY[1,2,2,3,1], ARRAY[2,3,4,4,5]);
```
Output: `[1,2,3,4,5]`
**Concatenate Two Arrays with NULLs and Remove Duplicates**
Deduplicate the contents of the array. In this case, the array contains NULLs.
```sql SQL theme={null}
SELECT ARRAY_CAT_DISTINCT(ARRAY[1,2,2,NULL,1], ARRAY[2,4,4,NULL]);
```
Output: `[1,2,NULL,4]`
## ARRAY\_DISTINCT
Removes duplicates from an array while preserving the first occurrence order. If at least one NULL is present in the array, the function returns a NULL with the position of the first NULL of the input array in the output array.
**Syntax**
```sql SQL theme={null}
ARRAY_DISTINCT(input_array)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ---------------------------- |
| `input_array` | ARRAY | The array for deduplication. |
**Examples**
**Remove Duplicates from an Array**
Deduplicate the contents of the array.
```sql SQL theme={null}
SELECT ARRAY_DISTINCT(ARRAY[1,2,2,3,1]);
```
Output: `[1,2,3]`
**Remove Duplicates from an Array with NULLs**
Deduplicate the contents of the array. In this case, the array contains NULLs.
```sql SQL theme={null}
SELECT ARRAY_DISTINCT(ARRAY[1,2,NULL,2,3,NULL,1]);
```
Output: `[1,2,NULL,3]`
## ARRAY\_LENGTH
Returns the length of the array for the specified dimension. If the array is a nested array, the function returns the length of the outermost array.
**Syntax**
```sql SQL theme={null}
ARRAY_LENGTH(input_array)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ------------------------------------------------------------------------------------------- |
| `input_array` | ARRAY | The array that contains any type of elements. The array can be single or multi-dimensional. |
**Example**
Return the length of the array.
```sql SQL theme={null}
SELECT ARRAY_LENGTH(ARRAY[1,2]);
```
Output: `2`
## ARRAY\_SORT
Sorts and returns the input array based on the natural ordering of its elements. The behavior of this function varies depending on the syntax you use.
**Syntaxes**
**Basic Array Sort**
Sorts and returns the input array based on the natural ordering of its elements. If one of the array elements is NULL, then this function sorts the NULL values to the end of the array.
```sql SQL theme={null}
ARRAY_SORT(input_array)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `input_array` | ARRAY | An array of elements with these types: `BIGINT`, `BOOLEAN`, `BYTE`, `DATE`, `DOUBLE`, `FLOAT`, `INT`, `SMALLINT`, `UUID`, or `VARCHAR`. |
**Sort an Array With a Lambda Function**
Sorts and returns the input array based on the results of the specified Lambda function. The function should have two arguments representing two elements of the array. This function should return a negative integer, 0, or a positive integer if the first element is less than, equal to, or greater than the second element, respectively.
```sql SQL theme={null}
ARRAY_SORT(input_array,function)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `input_array` | ARRAY | An array that contains any type of elements. The array can be single or multi-dimensional. |
| `function` | FUNCTION | This is an optional argument. A lambda function with the format `(x T, y T) -> INT` or another SQL reference function. |
The Ocient System supports this syntax with the data pipeline functionality only. For details, see [Transform Data in Data Pipelines](/transform-data-in-data-pipelines).
**Sort an Array in the Specified Order**
Determines how the array handles the order of elements in the array.
```sql SQL theme={null}
ARRAY_SORT(input_array,sort_order)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `input_array` | ARRAY | An array of elements with these types: `BIGINT`, `BOOLEAN`, `BYTE`, `DATE`, `DOUBLE`, `FLOAT`, `INT`, `SMALLINT`, `UUID`, or `VARCHAR`. |
| `sort_order` | BOOLEAN | This is an optional argument.
Determines the sort order of the array. The value `true` means ascending order. The value `false` means descending order. The default value is `true`. |
**Sort an Array in the Specified Order with NULL Elements**
Determines how the array handles the order of elements in the array and where NULL elements appear.
```sql SQL theme={null}
ARRAY_SORT(input_array,sort_order,nulls_first)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `input_array` | ARRAY | An array of elements with these types: `BIGINT`, `BOOLEAN`, `BYTE`, `DATE`, `DOUBLE`, `FLOAT`, `INT`, `SMALLINT`, `UUID`, or `VARCHAR`. |
| `sort_order` | BOOLEAN | This is an optional argument.
Determines the sort order of the array. The value `true` means ascending order. The value `false` means descending order. The default value is `true`. |
| `nulls_first` | BOOLEAN | This is an optional argument.
Determines whether NULL elements appear first or last in the array. The `true` value means that NULLs appear first in the array. The `false` value means that they appear last. If the array is in ascending order, the default value is `false`. Otherwise, the default value is `true`. |
**Examples**
**Sort an Array**
Sort an array of three elements `[2,3,1]`.
```sql SQL theme={null}
SELECT ARRAY_SORT(ARRAY[2,3,1]);
```
Output: `[1,2,3]`
**Sort an Array by Specifying the Sort Order**
Sort an array of four elements `[2,3,1,NULL]` and specify the order of the elements in descending order.
```sql SQL theme={null}
SELECT ARRAY_SORT(ARRAY[2,3,1,NULL],false);
```
Output: `[NULL,3,2,1]`
**Sort an Array by Specifying the Sort Order and NULL Placement**
Sort an array of four elements `[2,NULL,3,1]` and specify the order of the elements in ascending order, and have the NULL element appear last.
```sql SQL theme={null}
SELECT ARRAY_SORT(ARRAY[2,NULL,3,1],true,false);
```
Output: `[1,2,3,NULL]`
## UNNEST
Expands each element in an input array into an individual row.
For example, the `UNNEST` function on an array column of type `ARRAY(INT)` with values `[2, 6]` yields two result rows with integers `2` and `6`.
The values of the other columns in each input row are unchanged in each corresponding output row. You can specify multiple array columns to unnest the specified arrays from each row in parallel.
**Syntax**
```sql SQL theme={null}
UNNEST( array_column [, ... ] )
[ WITH ]
::=
{ ORDINALITY [ ord_identifier ]
| VALUE [ val_identifier ]
| NULL_INPUT }
```
| **Argument** | **Data** **Type** | **Description** |
| ---------------- | ----------------- | ----------------------------------------------------------------------------------------------------- |
| `array_column` | `ARRAY` | The array column to expand. |
| `ord_identifier` | `CHAR` | When you use this argument in an `ORDINALITY` clause, the argument is the name for the output column. |
| `val_identifier` | `CHAR` | When you use this argument in a `VALUE` clause, the argument is the name for the unnested column. |
The `UNNEST` function supports these options. When you use only one of these options, enclosing the option in parentheses is optional. However, if you use more than one of these options, you must enclose them in parentheses.
| **Options** | **Description** |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ORDINALITY [ord_identifier]` | Optional. Generates a new integer column that corresponds to the index position of each output element in the original array. The `ord_identifier` value specifies the name of the output ordinality column. If you do not specify this clause, the column name defaults to the original column name with the suffix `_ord`. |
| `VALUE [val_identifier]` | Optional. Rename the unnested column to the new name specified in the `val_identifier` argument. If you do not specify this clause, the column name defaults to the original column name with the suffix `_val`. |
| `NULL_INPUT` | Optional. When the input column array is empty or NULL, this clause specifies to replace each output row with an array with one NULL element. This replacement preserves the contents of other input rows. By default, this option is not enabled. |
These examples demonstrate how the `UNNEST` function operates on arrays and other objects. Most of the examples use the data rows from this table.
```Text Text theme={null}
a b c d e f
--------------------------------------------
1 [1, 2] [6, 9] [] NULL [[1, 2], [5], []]
2 [7, 5] [4] [3] [8] [[6], [9, 4, 7], [3, 8]]
```
**Examples**
**Expand a Column**
This example performs a simple `UNNEST` on column `b`.
```sql SQL theme={null}
SELECT UNNEST(b);
```
*Output*
```Text Text theme={null}
b_val
-----------
1
2
7
5
```
**Expand a Column Using the** `ORDINALITY` **Option**
In this example, the `ORDINALITY` option adds a second return column that represents the index position of the value in the input array.
```sql SQL theme={null}
SELECT UNNEST(b) WITH ORDINALITY;
```
*Output*
```Text Text theme={null}
b_val b_ord
--------------------
1 1
2 2
7 1
5 2
```
**Expand a Column with Empty Data**
In this example, the `UNNEST` query returns only one row because one of the two rows in column `d` is an empty array.
If you use the `NULL_INPUT` option, the query returns a second row with the `NULL` value.
```sql SQL theme={null}
SELECT UNNEST(d);
```
*Output*
```Text Text theme={null}
d_val
------------
3
```
**Expand a Column with NULL Data**
`UNNEST` also does not return array values that are `NULL` unless you specify the `NULL_INPUT` option.
```sql SQL theme={null}
SELECT UNNEST(e);
```
*Output*
```Text Text theme={null}
e_val
------------
8
```
**Expand a Column with Multiple Array Layers**
The `UNNEST` function expands only one array layer.
The empty array remains in the returned values.
```sql SQL theme={null}
SELECT UNNEST(f);
```
*Output*
```Text Text theme={null}
f_val
------------
[1,2]
[5]
[]
[6]
[9,4,7]
[3,8]
```
**Expand Columns Using Multiple** `UNNEST` **Statements**
Multiple `UNNEST` statements in a query produce a per-row Cartesian product of all the unnested values.
```sql SQL theme={null}
SELECT UNNEST(b), UNNEST(c);
```
*Output*
```Text Text theme={null}
b_val c_val
------------
1 6
1 9
2 6
2 9
7 4
5 4
```
**Expand Columns Using Multiple** `UNNEST` **Statements in Reverse Order**
This example uses `UNNEST` on the same columns but in reverse order.
```sql SQL theme={null}
SELECT UNNEST(c), UNNEST(b);
```
*Output*
```Text Text theme={null}
c_val b_val
------------
6 1
6 2
9 1
9 2
4 7
4 5
```
**Expand Multiple Columns**
In this example, the query unnests two array columns in parallel. Even though it does not include the `NULL_INPUT` option, the query still returns NULL for column `c` to correspond with column `b`.
```sql SQL theme={null}
SELECT UNNEST(b, c);
```
*Output*
```Text Text theme={null}
b_val c_val
------------
1 6
2 9
7 4
5 NULL
```
**Expand Multiple Array Columns**
This query unnests two array columns.
```sql SQL theme={null}
SELECT UNNEST(b, d);
```
*Output*
```Text Text theme={null}
b_val d_val
------------
1 NULL
2 NULL
7 3
5 NULL
```
**Expand Values of Arrays Within Arrays**
This example has two layers of `UNNEST` to capture values of arrays within arrays.
```sql SQL theme={null}
SELECT UNNEST(f_val) FROM (UNNEST(f));
```
*Output*
```Text Text theme={null}
f_val
------------
1
2
5
6
9
4
7
3
8
```
**Expand an Empty Array**
This example unnests an empty integer array.
```sql SQL theme={null}
SELECT UNNEST(INT[]());
```
*Output*
```Text Text theme={null}
col_val
------------
```
The query returns a column of type `INT` but no rows.
**Expand an Empty Array Column Without the** `NULL_INPUT` **Option**
This example selects the non-array column `a` and an empty array column. The query returns no rows because empty or `NULL` array values are not returned unless you specify the `NULL_INPUT` option.
```sql SQL theme={null}
SELECT a, UNNEST(INT[]());
```
*Output*
```Text Text theme={null}
a col_val
------------
```
**Expand a Column Without the** `NULL_INPUT` **Option**
This query does not include the `NULL_INPUT` option, which causes the result to omit the NULL array values in column `e`.
```sql SQL theme={null}
SELECT a, UNNEST(e);
```
*Output*
```Text Text theme={null}
a e_val
------------
1 8
2 8
```
**Expand a Column** **with the** `NULL_INPUT` **Option**
This query includes the `NULL_INPUT` option, which means that the query returns the NULL values in column `e`.
```sql SQL theme={null}
SELECT a, UNNEST(e) WITH NULL_INPUT;
```
*Output*
```Text Text theme={null}
a e_val
------------
1 8
1 NULL
2 8
2 NULL
```
**Expand Arrays with NULL Rows**
This example attempts to unnest two arrays, one of which is cast as NULL, while the other is empty.
In both cases, the query returns a column of type `INTEGER` with no rows because there are no values to unnest.
```sql SQL theme={null}
SELECT UNNEST(CAST(NULL AS INT[]);
SELECT UNNEST(INT[]());
```
*Output*
```Text Text theme={null}
col_val
------------
```
## Other Array Functions
| **Function** | **Syntax** | **Purpose** |
| ------------------------ | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Constructor | TYPE\[]\(e1, e2, …, en) | Construct an array of SQL type TYPE giving the elements. NULL is also supported as an element. |
| Constructor (2) | array\[e1, e2, …, en] | -compliant constructor. The type of the array is deduced from the elements. |
| array concatenation | array\_cat(array, array) | Concatenate 2 arrays into a new one. |
| array softmax | softmax(array) | Returns the softmax of the array. The array must be one-dimensional and contain float or double values. The system transfers NULL-valued indices as 0.0. |
| array cross entropy loss | cross\_entropy\_loss(array, array) | Returns the cross entropy loss of two arrays. Both arrays must be one-dimensional and contain float or double values. NULL values do not contribute to the sum. |
| array log loss | log\_loss(array, array) | Returns the log loss of two arrays. Both arrays must be one-dimensional and contain float or double values. NULL values do not contribute to the sum. |
| array logits loss | logits\_loss(array, array) | Returns the logits loss of two arrays. Both arrays must be one-dimensional and contain float or double values. NULL values do not contribute to the sum. |
| array hinge loss | hinge\_loss(array, array) | Returns the hinge loss of two arrays. Both arrays must be one-dimensional and contain float or double values. NULL values do not contribute to the sum. |
| array sum | array\_sum(array) | Returns the sum of the array. The array must be one-dimensional and contain numeric values. NULL values do not contribute to the sum. |
| array min/max | array\_min(array), array\_max(array) | Returns the corresponding minimum or maximum of the array. This function only considers the first dimension of the array. If the array contains only NULL values, then the function returns NULL. |
| array argmax | array\_argmax(array) | Returns the 1-based position (index) of the maximum element in an array. The first element has index 1.
This function only considers the first dimension of the array. If the array contains only NULL values, then the function returns NULL. |
| array argmin | array\_argmin(array) | Returns the 1-based position (index) of the minimum element in an array. The first element has index 1.
This function only considers the first dimension of the array. If the array contains only NULL values, then the function returns NULL. |
| array casting | cast\_to\_array(array, format) | Casts the elements of the array to another type, as specified by the format string. The format is: `'ARRAY(INT)'` for an `int` array, `'ARRAY(CHAR)'` for a `char` array, and so on. Currently, only numeric casts are supported. |
| scalar position | array\_position(array, scalar, pos = 1 ) | Returns the position of the first matching scalar in the array. pos indicates the position to start searching, if not specified it defaults to 1. |
| array elements positions | array\_positions(array, array ) | Same as array\_position(). But this looks for all elements stored in the right array and returns their respective positions in the left array. |
| array append | array\_append(array, value) | Add value to the back of an array |
| array prepend | array\_prepend(value, array) | Add value to the front of an array |
| array remove | array\_remove(array, value) | remove value from the array |
| array replace | array\_replace(array, old\_value, new\_value) | replace value by another in an array |
| convert array to string | char(array) | Converts array to its string representation. |
| convert array to string | array\_to\_string(array, delimiter \[, nullstr]) | Converts array to a list of elements separated by 'delimiter'. Nested arrays are flattened. NULL values are either ignored or replaced by *nullstr* if provided. |
| convert string to array | string\_to\_array(str, format) | Converts the string representation of an array (e.g., `'int[1,2,NULL]'`) into an array. The format string is the same as in cast\_to\_array. |
### Function Examples
| **Function** | **SQL statement** | **Result** |
| ------------------------ | ------------------------------------------------ | ----------------------------------- |
| type constructor | int\[]\(1,2) | int array with values 1 and 2 |
| constructor with no type | array\[1,2] | bigint array with values 1 and 2 |
| array\_cat | array\_cat(array\[2, 3], array\[4, 5]) | array\[2, 3, 4, 5] |
| array\_length | array\_length(array\[2, 3]) | 2 |
| cast\_to\_array | cast\_to\_array(array\[2.5, 3.4], 'ARRAY(INT)') | int\[]\(2,3) |
| array\_position | array\_position(array\[1, 2, 1], 1) | 1 |
| | array\_position(array\[1, 2, 3, 4, 1], 1, 3) | 5 |
| array\_positions | array\_positions(array\[1, 2, 3, 4, 1], 1) | int\[]\(1,5) |
| array\_append | array\_append(array\[1,2], 3) | array\[1,2,3] |
| array\_prepend | array\_prepend(0, array\[1,2]) | array\[0,1,2] |
| array\_remove | array\_remove(array\[1,2], 1) | array\[2] |
| array\_replace | array\_replace(array\[1,2,4],4,3) | array\[1,2,3] |
| softmax | softmax(float\[]\(2.0, 2.0, 2.0, NULL, 2.0)) | float\[0.25, 0.25, 0.25, 0.0, 0.25] |
| array\_sum | array\_sum(int\[]\(1, 2, 3)) | 6 |
| array\_min | array\_min(int\[]\(1, -2, 3)) | -2 |
| array\_argmax | array\_argmax(int\[]\(1, 3, 2)) | 2 |
| array\_argmin | array\_argmin(int\[]\(1, 3, 2)) | 1 |
| char(\) | char(array\[1,2]) | 'bigint\[1,2]' |
| array\_to\_string | array\_to\_string(int\[1,2,3,NULL,5], ',', '\*') | '1,2,3,\*,5' |
| string\_to\_array | string\_to\_array('int\[1,2]', 'ARRAY(INT)') | int\[]\(1,2) |
## Array Operators
Ocient array operators allow you to concatenate and check for containment or overlap of data. Also, you can retrieve specific elements or slices within arrays.
Do not use array operators, including `@>`, `<@`, and `&&`, to evaluate `NULL` values in arrays. For information on how to check for `NULL` values in arrays, see [Array NULL Handling](#array-null-handling).
### Contains Operator (`@>`)
The `@>` operator determines whether a left-side array contains a scalar value or array elements on the right side.
`@>` **Syntax**
```sql SQL theme={null}
array @> scalar_or_array
```
| **Argument** | **Data** **Type** | **Description** |
| ----------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `array` | `ARRAY` | An array column or expression. |
| `scalar_or_array` | `ARRAY` or any numeric, character, time, or geospatial data type. | A value or an array of values to check whether they are contained in the array. For data types, see [Understanding Data Types](/understanding-data-types). |
**Examples**
These examples use the `@>` operator to test whether the left-side array contains all the elements from the right-side array.
**Array Containment (True Case)**
This example returns `true` because all right-side elements are in the left-side array.
```sql SQL theme={null}
SELECT ARRAY[1, 4, 3] @> ARRAY[3, 1];
```
*Output:* `true`
**Array Containment (False Case)**
If the right-side array contains at least one value not present in the left-side array, the query returns `false`. In this example, the right-side array has one value, `5`, not present on the left side.
```sql SQL theme={null}
SELECT ARRAY[1, 4, 3] @> ARRAY[3, 1, 5];
```
*Output:* `false`
**Scalar Containment in an Array**
This example checks whether a single scalar value is in the left-side array.
```sql SQL theme={null}
SELECT ARRAY[3, 1, 3] @> 1;
```
*Output:* `true`
### Contained In Operator (`<@`)
The `<@` operator checks whether a right-side array contains all the elements on the left side.
**Syntax**
```sql SQL theme={null}
scalar_or_array <@ array
```
| **Argument** | **Data** **Type** | **Description** |
| ----------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `array` | `ARRAY` | An array column or expression. |
| `scalar_or_array` | `ARRAY` or any numeric, character, time, or geospatial data type. | A value or an array of values to check whether they are contained in the array. For data types, see [Understanding Data Types](/understanding-data-types). |
**Examples**
**Array Contained Within Another Array (True Case)**
This example returns `true` because all left-side elements are in the right-side array.
```sql SQL theme={null}
SELECT VARCHAR[]('apples', 'oranges') <@ VARCHAR[]('apples', 'oranges', 'bananas')
```
*Output:* `true`
**String Membership Check**
`<@` and other array operators can check whether individual strings are present in an array. The `'oranges'` string is present in the right-side array.
```sql SQL theme={null}
SELECT 'oranges' <@ VARCHAR[]('apples', 'oranges', 'bananas')
```
*Output:* `true`
### Overlap Operator (`&&`)
The overlap operator `&&` determines whether any elements between two arrays are common.
**Syntax**
```sql SQL theme={null}
array1 && array2
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ------------------------------------------------------------------------------------------ |
| `array1` | `ARRAY` | An array column or expression to check whether any of its values are shared with `array2`. |
| `array2` | `ARRAY` | An array column or expression to check whether any of its values are shared with `array1`. |
**Examples**
**Check Overlap Between Arrays (True Case)**
As long as at least one value is present in both arrays, the `&&` operator returns `true`. Both of these arrays contain the value `3`.
```sql SQL theme={null}
SELECT ARRAY[1 ,2, 3] && ARRAY[3 ,4, 5];
```
*Output:* `true`
**Check Overlap Between Arrays (False Case)**
Both of these arrays have no values in common, so the `&&` operator returns `false`.
```sql SQL theme={null}
SELECT ARRAY[1 ,2, 3] && ARRAY[4 ,5, 6];
```
*Output:* `false`
### Slice Operator (`:`)
The slice operator `:` returns a subarray ranging from a left index to a right index, both of which are optional to specify. If you exclude both indexes, the slice operator returns the full array.
**Syntax**
```sql SQL theme={null}
array[left_index:right_index]
```
| **Argument** | **Data** **Type** | **Description** |
| ------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `array` | `ARRAY` | An array column or expression. |
| `left_index` | `INT` | Optional.
A starting index for the slice operator to begin the subarray. Index values start at `1`.
If you do not specify a left index, or if this value is less than zero, then the slice starts at index `1`. |
| `right_index` | `INT` | Optional.
An ending index for the slice operator to end the subarray. Index values start at `1`.
If you do not specify a right index or if the value exceeds the array length, the right index defaults to the array length. |
The slice operator also follows these rules:
* Each index starts at `1`.
* If the array or either index value is NULL, the result of slicing is NULL.
* Ranges completely out of array bounds return an empty array. For example, `array[1, 2][4:5] = []`.
* Sequential slices slice each dimension of multidimensional arrays. For example, `ARRAY[ARRAY[1, 2, 3], ARRAY[4, 5, 6]][1:1][2:3] = ARRAY[ARRAY[2,3]]`.
* More than N sequential slices of an N-dimensional array, for example, three sequential slices on a two-dimensional array return an empty array. For example, `ARRAY[1, 2, 3][:][:] = []`.
* You cannot combine slicing with the access operator when slicing multidimensional arrays. Any access operator `[n]` converts to `[:n]`. For example, `Array_Val[4][1:6]` would be equivalent to `Array_Val[:4][1:6]`.
* Slicing an array of tuples such as `ARRAY[TUPLE<>(1,2), TUPLE<>(3,4)][1:1][2:3]` slices `[1:1]` on the array and `[2:3]` on the tuple elements within the sliced array, and returns the value `TUPLE<>[TUPLE<>(2)]`.
**Examples**
**Basic Array Slicing**
Slice an array with four numbers starting at index `2` and ending at index `3`.
```sql SQL theme={null}
SELECT ARRAY[1 ,2, 3, 4][2:3];
```
\*Output: \*`['2','3']`
**Array Slicing With No Right Index**
The query returns all values after the second value because it does not specify an ending index.
```sql SQL theme={null}
SELECT ARRAY[1 ,2, 3, 4][2:];
```
\*Output: \*`['2','3','4']`
**Array Slicing With No Left Index**
This query captures a subarray starting at the first index because it does not specify a starting value.
```sql SQL theme={null}
SELECT ARRAY[1 ,2, 3, 4][:3];
```
\*Output: \*`['1','2','3']`
## Array NULL Handling
Filtering with array functions can have different outcomes if they operate on an array containing NULL values or a NULL value of array type.
Array comparison operators, such as `@>`, `<@`, and `&&`, do not follow normal Boolean logic when evaluating NULL values. To evaluate arrays for NULL values, use the filter functions `FOR_ALL()` or `FOR_SOME()`. For details about these functions, see [Array Filters](/data-query-language-dql-statement-reference#array-filters).
**Examples**
**Evaluate a Single Array With No NULL Values**
This example evaluates to `false` because none of the array values are NULL.
```sql SQL theme={null}
SELECT FOR_SOME(ARRAY[1, 2, 3]) IS NULL;
```
\*Output: \*`false`
**Evaluate a Single Array With NULL Values**
This example evaluates to `true` because the array contains a NULL value.
```sql SQL theme={null}
SELECT FOR_SOME(ARRAY[1, 2, NULL]) IS NULL;
```
\*Output: \*`true`
**Select Only Arrays Containing NULL Values**
To further demonstrate array NULL behavior, these examples use this table loaded with a few array values, some of which are NULL or contain NULL values.
```sql SQL theme={null}
CREATE TABLE demo_array_table (
id INT,
tags VARCHAR[]
);
INSERT INTO demo_array_table (id, tags) VALUES
(1, VARCHAR[]('alpha', 'beta', 'gamma')), -- Regular array
(2, VARCHAR[]('delta', NULL, 'epsilon')), -- Array containing a NULL element
(3, NULL), -- Entirely NULL array
(4, VARCHAR[]()), -- Empty array
(5, VARCHAR[](NULL, NULL)); -- Array containing all NULL elements
```
In this example, the query uses a `FOR_SOME` function to filter the rows to return only arrays with NULL values. The output does not include the third row of the table because the row itself is NULL, and is not an array containing NULL values.
```sql SQL theme={null}
SELECT id, tags FROM demo_array_table
WHERE FOR_SOME(tags) IS NULL;
```
*Output*
```sql SQL theme={null}
| id | tags |
|----|----------------------------------|
| 2 | ['delta', NULL, 'epsilon'] |
| 5 | [NULL, NULL] |
```
**Select NULL Values or Arrays Containing NULL Values**
This example includes an additional filter to include any NULL rows and arrays with NULL values.
The example uses the `demo_array_table` table, which has values that are NULL or contain NULL values.
```sql SQL theme={null}
SELECT id, tags FROM demo_array_table
WHERE FOR_SOME(tags) IS NULL
OR tags IS NULL;
```
*Output*
```sql SQL theme={null}
| id | tags |
|----|------------------------------|
| 3 | NULL |
| 5 | [NULL, NULL] |
| 2 | ['delta', NULL, 'epsilon'] |
```
**Select Arrays Without NULL Values**
This example filters the rows using the `FOR_ALL` filter function to return only arrays with no NULL values. The output also contains rows with empty arrays.
The example uses the `demo_array_table` table, which has values that are NULL or contain NULL values.
```sql SQL theme={null}
SELECT id, tags FROM demo_array_table
WHERE FOR_ALL(tags) IS NOT NULL;
```
*Output*
```sql SQL theme={null}
| id | tags |
|----|-------------------------------|
| 4 | [] |
| 1 | ['alpha', 'beta', 'gamma'] |
```
**Select Only Non-Empty Arrays Without NULL Values**
To omit empty arrays, you can add a filter to check the array length. The `ARRAY_LENGTH` function removes any empty arrays.
This example uses the `demo_array_table` table, which has values that are NULL or contain NULL values.
```sql SQL theme={null}
SELECT id, tags FROM demo_array_table
WHERE FOR_ALL(tags) IS NOT NULL
AND ARRAY_LENGTH(tags) > 0;
```
*Output*
```sql SQL theme={null}
| id | tags |
|----|-------------------------------|
| 1 | ['alpha', 'beta', 'gamma'] |
```
## Multidimensional Arrays
Multidimensional arrays are supported. As seen in these examples, each dimension, or length, at each level does not have to be the same. NULL values are allowed at each dimension of an array.
**Multidimensional Examples**
| **Function** | **SQL statement** | **Result** |
| -------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------ |
| type constructor two-dimensional | `int[][](int[](1, NULL), array[1])` | two-dimensional `INT` array with values `[1, NULL]` and `[1]` |
| constructor with no type two-dimensional | `array[int[]\(1), array[int(2)]]` | two-dimensional `INT` array with values `[1]` and `[2]` |
| two-dimensional array with NULL values | `array[array[1, NULL], NULL]` | two-dimensional `BIGINT` array with values `[1, NULL]` and `NULL` |
| two-dimensional array with different lengths | `array[array[1], array[1,2], array[1,2,3]]` | two-dimensional `BIGINT` array with values `[1]`, `[1,2]`, and `[1,2,3]` |
## Related Links
[Matrix Functions and Operators](/matrix-functions-and-operators)
[Tuple Functions and Operators](/tuple-functions-and-operators)
[Math Functions and Operators](/math-functions-and-operators)
[Array Data Transformation Functions](/transform-data-in-data-pipelines#array-data-transformation-functions)
[Data Types](/data-types)
[Data Types for Data Pipelines](/data-types-for-data-pipelines)
[Query Ocient](/query-ocient)
# Array, Tuple, and Matrix Overview
Source: https://docs.ocient.com/array-tuple-and-matrix-overview
Overview of array, tuple, and matrix data structures in Ocient SQL, with guidance on constructing, indexing, and operating on nested or composite values.
Arrays, tuples, and matrix data types are complex data types in the System.
## Arrays
The array data type is a one-dimensional list of values with the same data type. This type enables the support of a one-to-many relationship without creating another table. You create secondary indexes on arrays, which index the elements of the array. For details about secondary indexes, see [Secondary Indexes](/secondary-indexes).
Key features:
* Variable size.
* Can contain many elements.
* Indexing into the array starts at `1`.
* Invalid access of the array returns NULL.
For semi-structured data in JSON format, you can express the JSON multi-value column in an array data type. Traditionally in the normalized relational data model, the database represents such data types as a separate table. Each row stores the value of the primary key of the record in the parent table. Therefore, the entity relationship between the tables is always one-to-many, which can result in billions of rows. The array data type eliminates the child tables, which helps reduce the storage footprint and avoids the additional JOIN operations.
**Examples**
Create a one-dimensional integer array `[1, 2, 3]` using the `sys.dummy` virtual table.
```sql SQL theme={null}
SELECT INT[](1,2,3)
FROM sys.dummy1;
```
*Output*
```none Text theme={null}
array_int(int((1)), int((2)), int((3)))
--------------------------------------------------------------------------------
[1,2,3]
Fetched 1 row
```
Create a two-dimensional integer array `[[1, 2, 3], [4, 5, 6]]`.
```sql SQL theme={null}
SELECT INT[][](INT[](1,2,3),INT[](4,5,6))
FROM sys.dummy1;
```
*Output*
```none Text theme={null}
array_array(int)(array_int(int((1)), int((2)), int((3))), array_int(int((4)), int((5)), int((6))))
---------------------------------------------------------------------------------------------------
[[1,2,3],[4,5,6]]
Fetched 1 row
```
You can get the same result by casting the array and integers explicitly.
```sql SQL theme={null}
SELECT INT[][](ARRAY[INT(1),INT(2),INT(3)],ARRAY[INT(4),INT(5),INT(6)])
FROM sys.dummy1;
```
For more examples, see [Array Functions and Operators](/array-functions-and-operators).
## Tuples
The tuple data type is a row. This type is a fixed-sized collection of heterogeneous values. Tuples support more complex recursive computational functions. The memory structure of the tuple is identical to the memory structure of the array type. The only difference is that each entry in a tuple can be any type, so the Ocient System can simultaneously store both fixed and variable-sized values in a tuple.
**Examples**
Create a tuple with fixed-size types. In this case, use three integers.
```sql SQL theme={null}
SELECT TUPLE(1,2,3)
FROM sys.dummy1;
```
*Output*
```none Text theme={null}
tuple((1), (2), (3))
--------------------------------------------------------------------------------
<<1, 2, 3>>
Fetched 1 row
```
You can get the same result by using the tuple type constructor.
```sql SQL theme={null}
SELECT TUPLE<>(1,2,3)
FROM sys.dummy1;
```
Create a tuple with variable-size types. In this case, use a one-dimensional and two-dimensional array.
```sql SQL theme={null}
SELECT TUPLE(ARRAY[INT(1),INT(2),INT(3)],
INT[][](ARRAY[INT(1),INT(2),INT(3)],ARRAY[INT(4),INT(5),INT(6)]))
FROM sys.dummy1;
```
*Output*
```none Text theme={null}
tuple(array_int(int((1)), int((2)), int((3))), array_array(int)(array_int(int((1)), int((2)), int((3))), array_int(int((4)), int((5)), int((6)))))
---------------------------------------------------------------------------------------------------------------------------------------------------
<<[1,2,3], [[1,2,3],[4,5,6]]>>
Fetched 1 row
```
Create a tuple with different types. In this case, an integer, string, and array of integers.
```sql SQL theme={null}
SELECT TUPLE<>(1, 'test_string', INT[](2,4,6))
FROM sys.dummy1;
```
*Output*
```none Text theme={null}
tuple(int((1)), ('test_string'), array_int(int((2)), int((4)), int((6))))
--------------------------------------------------------------------------------
<<1, test_string, [2,4,6]>>
Fetched 1 row
```
For more examples, see [Tuple Functions and Operators](/tuple-functions-and-operators).
## Matrices
A matrix is a fixed-size two-dimensional array of `DOUBLE` values. A matrix can be a row vector (1xN matrix) or column vector (Nx1 matrix).
matrices support machine learning model calculations. For details, see [Machine Learning in Ocient](/machine-learning-in-ocient).
**Examples**
Create a 1x4 matrix with numbers 1 through 4 using the `make_matrix` function that expects values in row-major order. The first two arguments indicate the dimensions of the matrix, and the remaining arguments specify the values for the matrix.
```sql SQL theme={null}
SELECT make_matrix_1x4(1,4,1,2,3,4)
FROM sys.dummy1;
```
*Output*
```none Text theme={null}
make_matrix_1x4((1), (4), (1), (2), (3), (4))
--------------------------------------------------------------------------------
[[1.0,2.0,3.0,4.0]]
Fetched 1 row
```
Create a 2x3 matrix with numbers 1 through 6.
```sql SQL theme={null}
SELECT make_matrix_2x3(2,3,1,2,3,4,5,6)
FROM sys.dummy1;
```
*Output*
```none Text theme={null}
make_matrix_2x3((2), (3), (1), (2), (3), (4), (5), (6))
--------------------------------------------------------------------------------
[[1.0,2.0,3.0],[4.0,5.0,6.0]]
Fetched 1 row
```
Create a row vector with four doubles.
```sql SQL theme={null}
SELECT _R{1,2,3,4}
FROM sys.dummy1;
```
*Output*
```none Text theme={null}
_r{1,2,3,4}
--------------------------------------------------------------------------------
[[1.0,2.0,3.0,4.0]]
Fetched 1 row
```
For more examples, see [Matrix Functions and Operators](/matrix-functions-and-operators).
## Related Links
[Array Functions and Operators](/array-functions-and-operators)
[Tuple Functions and Operators](/tuple-functions-and-operators)
[Matrix Functions and Operators](/matrix-functions-and-operators)
[Generate Tables Using sys.dummy](/generate-tables-using-sys-dummy)
# Attribute Functions
Source: https://docs.ocient.com/attribute-functions
Reference for OcientGeo attribute functions used to inspect, extract, and modify properties of geospatial geometries such as points, linestrings, and polygons.
attribute functions return descriptive information on the specified data set.
## ST\_COORDDIM
Alias for ST\_NDIMS or ST\_NDIMENSION.
Returns an `INTEGER` of the coordinate dimension of the specified geography.
**Syntax**
```sql SQL theme={null}
ST_COORDDIM(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------------------------- | ------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, or `POLYGON` | The geospatial object used to calculate the dimensions. |
**Example**
```sql SQL theme={null}
SELECT ST_COORDDIM(ST_POLYGON('POLYGON((1 1, 2 1, 2 2, 1 1))'));
```
*Output*: `2`
## ST\_DIMENSION
Returns an `INTEGER` that represents the dimension of the specified geography. This table describes the result values of the `ST_DIMENSION` function.
| **ST\_DIMENSION Result Value** | **Dimension Type** |
| ------------------------------ | --------------------- |
| `-1` | Empty geography value |
| `0` | `POINT` |
| `1` | `LINESTRING` |
| `2` | `POLYGON` |
The `ST_DIMENSION` function always returns `0` for non-empty `POINT` objects.
For non-empty `LINESTRING` and `POLYGON` objects, the `ST_DIMENSION` function returns the dimension value equal to the greatest dimension represented by their bounding points. For example, a `LINESTRING` or `POLYGON` object that contains only a single point returns `0`. Similarly, a `POLYGON` object can return `1` if it contains insufficient points to represent a closed polygon.
**Syntax**
```sql SQL theme={null}
ST_DIMENSION(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------------------------- | ------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, or `POLYGON` | The geospatial object used to calculate the dimensions. |
**Examples**
In this example, the function evaluates a `LINESTRING` with an empty `POINT` value.
```sql SQL theme={null}
SELECT ST_DIMENSION(ST_LINESTRING('POINT EMPTY'));
```
*Output*: `-1`
In this example, the function evaluates a `LINESTRING` with a single `POINT` value.
```sql SQL theme={null}
SELECT ST_DIMENSION(ST_LINESTRING('ST_POINT(0 0)'));
```
*Output*: `0`
This example evaluates an empty `LINESTRING`.
```sql SQL theme={null}
SELECT ST_DIMENSION(ST_LINESTRING('LINESTRING EMPTY'));
```
*Output*: `-1`
In this example, the function again evaluates a `LINESTRING` with a single `POINT` value.
```sql SQL theme={null}
SELECT ST_DIMENSION(ST_LINESTRING('LINESTRING(0 0)'));
```
*Output*: `0`
In this example, the function evaluates a `LINESTRING` with multiple `POINT` values.
```sql SQL theme={null}
SELECT ST_DIMENSION(ST_LINESTRING('LINESTRING(0 0, 1 1)'));
```
*Output*: `1`
This example evaluates an empty `POLYGON`.
```sql SQL theme={null}
SELECT ST_DIMENSION(ST_POLYGON('POLYGON EMPTY'));
```
*Output*: `-1`
This example evaluates a `POLYGON` with a single `POINT`.
```sql SQL theme={null}
SELECT ST_DIMENSION(ST_POLYGON('POLYGON((1 1))'));
```
*Output*: `0`
This example evaluates a `POLYGON` with two `POINT` values.
```sql SQL theme={null}
SELECT ST_DIMENSION(ST_POLYGON('POLYGON((0 0, 1 1))'));
```
*Output*: `1`
This example evaluates a `POLYGON` with multiple `POINT` values, enough to close the `POLYGON`.
```sql SQL theme={null}
SELECT ST_DIMENSION(ST_POLYGON('POLYGON((0 0, 1 0, 1 1, 0 0))'));
```
*Output*: `2`
## ST\_GEOMETRYTYPE
Returns a `STRING` that represents the geometry of the input geospatial value. Supported values are `ST_POINT`, `ST_LINESTRING`, and `ST_POLYGON`. This function enforces the same strict dimension types as the [ST\_DIMENSION](#st_dimension) function. If `geo` is NULL, then the function returns NULL.
**Syntax**
```sql SQL theme={null}
ST_GEOMETRYTYPE(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | -------------------------------- | ---------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, `POLYGON` | A geospatial value to be identified by its dimension type. |
**Example**
```sql SQL theme={null}
SELECT ST_GEOMETRYTYPE(ST_POINT(1, 2));
```
*Output*: `ST_POINT`
## ST\_ISEMPTY
Returns `TRUE` if the specified geography value is empty, such as `'POLYGON EMPTY'`. A NULL input value returns NULL.
**Syntax**
```sql SQL theme={null}
ST_ISEMPTY(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | -------------------------------- | ------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, `POLYGON` | A geospatial value to be examined if it is empty. |
**Example**
```sql SQL theme={null}
SELECT ST_ISEMPTY(ST_POLYGON('POLYGON EMPTY'));
```
*Output*: `TRUE`
## ST\_MEMSIZE
Returns an `INTEGER` representing the number of bytes in memory required to store the specified geography.
**Syntax**
```sql SQL theme={null}
ST_MEMSIZE(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | -------------------------------- | ----------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, `POLYGON` | A geospatial value to be measured by its data memory. |
**Example**
```sql SQL theme={null}
SELECT ST_MEMSIZE(ST_POINT(1,1));
```
*Output*: `16`
## ST\_NDIMS or ST\_NDIMENSION
Alias for [ST\_COORDDIM](#st_coorddim).
## ST\_NPOINTS or ST\_NUMPOINTS
Returns an `INTEGER` representing the number of `POINT` values in a specified geography.
If the specified value is a `POLYGON`, this function counts the number of `POINT` values in both the exterior and any holes.
**Syntax**
```sql SQL theme={null}
ST_NPOINTS(geo)
```
```sql SQL theme={null}
ST_NUMPOINTS(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | -------------------------------- | ------------------------------------------------------------------ |
| `geo` | `POINT`, `LINESTRING`, `POLYGON` | A geospatial value to be examined for its count of `POINT` values. |
**Example**
```sql SQL theme={null}
SELECT ST_NPOINTS(
ST_POLYGON(
'POLYGON((1 2, 1 3, 1 2))'));
```
*Output*: `3`
## ST\_SRID
Returns the EPSG code of the spatial reference identifier (SRID) of the input geography. All geographies are of type GCS WGS 84, which is identified by the value 4326. There is no way to set a different SRID.
**Syntax**
```sql SQL theme={null}
ST_SRID(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | -------------------------------- | ---------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, `POLYGON` | A geospatial value to be analyzed for its EPSG code. |
**Example**
```sql SQL theme={null}
SELECT ST_SRID(ST_MAKEPOINT(1.1, 3.11));
```
*Output*: `4326`
## ST\_X
Returns the x value, or longitude, of the specified `POINT`. The returned value is a `DOUBLE` type.
**Syntax**
```sql SQL theme={null}
ST_X(point)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ----------------------------------------------------------------- |
| `point` | `POINT` | A geospatial point to be analyzed for its x value, the longitude. |
**Example**
```sql SQL theme={null}
SELECT ST_X(ST_POINT(3, 5));
```
*Output*: `3`
## ST\_XMAX
Returns the maximum x value of the specified geography. The returned value is a `DOUBLE` type.
**Syntax**
```sql SQL theme={null}
ST_XMAX(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | -------------------------------- | --------------------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, `POLYGON` | One or more geospatial points to be analyzed for the maximum x value. |
**Example**
In this example, the `ST_XMAX` function returns `2` because it is the largest x value of the specified points.
```sql SQL theme={null}
SELECT ST_XMAX(
ST_POLYGON(ST_LINESTRING('LINESTRING(2 5, 1 2, 1 4, 0 3)')));
```
*Output*: `2`
## ST\_XMIN
Returns the minimum x value of the specified geography.
**Syntax**
```sql SQL theme={null}
ST_XMIN(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | -------------------------------- | --------------------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, `POLYGON` | One or more geospatial points to be analyzed for the minimum x value. |
**Example**
In this example, the `ST_XMIN` function returns `0` because it is the smallest x value of the specified points.
```sql SQL theme={null}
SELECT ST_XMIN(
ST_POLYGON(ST_LINESTRING('LINESTRING(2 5, 1 2, 1 4, 0 3)')));
```
*Output*: `0`
## ST\_Y
Returns the y value, or latitude, of the specified `POINT`. The returned value is a `DOUBLE` type.
**Syntax**
```sql SQL theme={null}
ST_Y(point)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ---------------------------------------------------------------- |
| `point` | `POINT` | A geospatial point to be analyzed for its y value, the latitude. |
**Example**
```sql SQL theme={null}
SELECT ST_Y(ST_POINT(3, 5));
```
*Output*: `5`
## ST\_YMAX
Returns the maximum y value of the specified geography.
**Syntax**
```sql SQL theme={null}
ST_YMAX(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | -------------------------------- | --------------------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, `POLYGON` | One or more geospatial points to be analyzed for the maximum y value. |
**Example**
In this example, the `ST_YMAX` function returns `5` because it is the largest y value of the specified points.
```sql SQL theme={null}
SELECT ST_YMAX(
ST_POLYGON(ST_LINESTRING('LINESTRING(2 5, 1 2, 1 4, 0 3)')));
```
*Output*: `5`
## ST\_YMIN
Returns the minimum y value of the specified geography.
**Syntax**
```sql SQL theme={null}
ST_YMIN(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | -------------------------------- | --------------------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, `POLYGON` | One or more geospatial points to be analyzed for the minimum y value. |
**Example**
In this example, the `ST_YMIN` function returns `2` because it is the smallest y value of the specified points.
```sql SQL theme={null}
SELECT ST_YMIN(
ST_POLYGON(ST_LINESTRING('LINESTRING(2 5, 1 2, 1 4, 0 3)')));
```
*Output*: `2`
## Related Links
[Geospatial Data Types](/data-types#geospatial-data-types)
[Linestring Constructors](/linestring-constructors)
[Point Constructors](/point-constructors)
[Polygon Constructors](/polygon-constructors)
# Authentication Methods
Source: https://docs.ocient.com/authentication-methods
Overview of authentication methods supported by Ocient, including database password, single sign-on (SSO), OpenID Connect, and token-based access.
offers two authentication methods to access the database: Password authentication and Single Sign On (SSO) authentication. You can use these independently or as an organization according to your security and access control needs. This section explains each authentication method and how it can be configured on Ocient.
## Password-Based Authentication
Users created using DCL are required to set a password that the system uses for authentication when connecting to the database.
Administrators can use [Database Password Security Settings](/database-password-security-settings) to manage settings such as minimum password length and password expiration policies.
### Fully Qualified User Name (FQUN)
To connect to the database, you must provide an FQUN. For database users, the FQUN has this form.
```Text Text theme={null}
@
```
For example, the FQUN of the user `alice`, a member of the database `example_database`.
```Text Text theme={null}
alice@example_database
```
### How To Connect using Password Authentication
Set the FQUN in the connection string along with the password of the user. For example, this code is the command `alice` uses to connect to `example_database` using the Ocient JDBC driver.
```Text Text theme={null}
connect to jdbc:ocient://:/example_database;user=alice@example_database;password=****;
```
The following Ocient driver properties must be set when connecting using password authentication:
* user — `alice@example_database`
* password — \`\`
## Single Sign On (SSO)
The Ocient System allows administrators to add a Single Sign-On integration, allowing users to authenticate using an external Identity Provider (idP). A database, including the `system` database, can have 0 or 1 SSO integrations.
The existence of an SSO integration has no effect on users who authenticate with the Password Authentication flow.
**Supported Protocols:**
The Ocient System supports the following SSO protocols:
| **Protocol** | **Description** |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [OpenID Connect](https://openid.net/) | OpenID Connect (OIDC) is a simple JSON-/REST-based identity protocol built on top of the OAuth 2.0 protocol. It enables client applications to rely on the authentication performed by an OpenID Connect Provider to verify the identity of a user. Clients can also obtain basic profile information about a user in an interoperable and REST-like manner from OpenID Connect Providers. |
## OpenID Connect
There are two flows that allow users to connect to the database using an external OpenID Connect Provider.
### Authorization Code Flow
This is the most commonly used authentication method and makes use of the [OAuth 2.0 Authorization Code Grant](https://www.oauth.com/oauth2-servers/server-side-apps/authorization-code/).
When you connect to the database, the Ocient driver directs you to the authorization endpoint of the OpenID Provider, where you log in with your SSO credentials. After the Provider authenticates you, it redirects you back to the database with a temporary code, which the database exchanges for an ID token, Access token, and optionally, a Refresh token.
See this image for a sequence diagram of the flow.
**Connect using the Authorization Code Flow**
The client handshake method must be set to SSO, and the connection username and password set to the empty string.
For example, this code is the command any user would use to connect to the `example_database` database using the Ocient JDBC driver.
```Text Text theme={null}
connect to jdbc:ocient://:/example_database;handshake=SSO;user=;password=;
```
These Ocient driver properties must be set when connecting using the Authorization Code flow:
* handshake — `SSO`
* user — ``
* password — ``
The `user` and `password` properties are required and must be set to the empty string.
### SSO Token Flow
Users can provide either an [ID Token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) or an [Access Token](https://datatracker.ietf.org/doc/html/rfc6749#section-1.4) issued by the OpenID Provider to connect to the database.
The provided ID or Access token must contain these claims:
* iss — The issuer must match the issuer contained in the discovery document of the OpenID Provider.
* aud — The token audience must contain the `client_id` used when configuring the OpenID Provider in the database.
Ocient recommends including the `email` scope in any token provided to Ocient. The system uses the value of the email claim to identify the user in the database audit trails.
Ocient supports these signing algorithms for ID Tokens:
* RSA 256
* RSA 384
* RSA 512
**Connect using the SSO Token Flow**
These Ocient driver properties must be set when connecting using an OpenID token:
* handshake — `SSO`
* user — `id_token` or `access_token`
* password — ``
The handshake must be set to SSO, with the username set to the token type and the password set to the token payload.
For example, this format is the JDBC command to connect to the `example_database` database using an ID Token.
```Text Text theme={null}
connect to jdbc:ocient://:/example_database;handshake=SSO;user=id_token;password=;
```
This format is the JDBC command to connect to `example_database` database using an Access Token.
```Text Text theme={null}
connect to jdbc:ocient://:/example_database;handshake=SSO;user=access_token;password=;
```
### Configure the OpenID Provider
Before users can authenticate using SSO, you must register the database with the OpenID Provider. This process varies depending on the provider, but typically, the steps for doing so are:
1. Create an application for the Ocient System in the Provider. Select the "Native Application" application type.
2. Enable the Authorization Code, Refresh Token, and Device Authorization grant types.
3. Grant permission to the appropriate users to use the newly created application.
4. Enter this Redirect URI.
| **Application** | **Redirect URI** |
| --------------- | ------------------------------------------------- |
| JDBC Driver | `http://localhost:7050/ocient/oauth2/v1/callback` |
| OpenAPI or UI | `https:///v1/callback` |
For the OpenAPI or UI application, the redirect URI must use `https` format.
The connectivity pool defines the OpenAPI or WebUI `advertized_ip` setting. For more information, see [CONNECTIVITY POOL](/cluster-and-node-management#connectivity-pool).
Record the token `issuer` and `client_id` of the newly created application. You need these values to configure the Ocient System.
### SSO Parameters
These SSO parameters are configurable by using DDL statements.
| **Name** | **Required** | **Value Type** | **Default Value** | **Description** |
| -------------------------------- | ------------ | ------------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `issuer` | Yes | string | None | The [complete URL](https://openid.net/specs/openid-connect-core-1_0.html#Terminology) for the OAuth 2.0 and OpenID Connect Authorization Server. This property value is the expected `\"iss\"` claim in access tokens validated by the database. |
| `client_id` | Yes | string | None | The [client identifier](https://openid.net/specs/openid-connect-core-1_0.html#Terminology) as registered with the OpenID Provider. |
| `client_secret` | Yes | string | None | The [client secret](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation) as registered with the OpenID Provider. This property is required for some SSO workflows. |
| `default_group` | Yes | string | None | The group users are assigned if no group is specified in the `group_claim_mappings` property for the OpenID Provider. |
| `redirect_host` | No | string | Depends on the connector (pyocient or JDBC). | Specifies the host name during SSO redirection. |
| `redirect_ssl` | No | Boolean | Depends on the connector (pyocient or JDBC). | Set to `true` to enable SSL callback during SSO redirection (i.e., redirect uses `https`). Set to `false` to disable (i.e., redirect uses `http`). |
| `disabled` | No | Boolean | `false` | Set to `true` to disable the OIDC integration for maintenance temporarily. ⚠️ If you set this property to `true`, all authentication requests using this connection fail. |
| `enable_id_token_authentication` | No | Boolean | `false` | Set this property to `true` if the identifier token also contains the authorization token. In most circumstances, this option is necessary only for machine-to-machine connections without user interaction, such as a server using a script to connect to an Ocient System. |
| `user_id_claims` | No | list of strings (e.g., value \[, ...] | \["email"] | Set the identifier token claims used to identify users in audit trails. If you do not set a value, the system uses the `"email"` claim if it is present, otherwise it uses `["iss", "sub"]`. |
| `additional_scopes` | No | list of strings (e.g., value \[, ...] | \[] | Specifies additional scopes to request when executing the Authorization Code Flow. |
| `additional_audiences` | No | list of strings (e.g., value \[, ...] | \[] | Specifies additional audiences to accept when validating tokens. This property is useful for authorization servers without the token exchange capability. Each additional audience is a case-sensitive URL from a provider, similar to the `issuer` value. |
| `groups_claim_ids` | No | list of strings (e.g., value \[, ...] | \[] | Specifies the token claims that can be used to map the user to a Database group. If you specify the `groups_claim_mappings` property, you must also specify the `groups_claim_ids` property. |
| `groups_claim_mappings` | No | map of strings (e.g., key = value \[, ...]) | Specifies mappings from the Provider group to the Database group. | |
| `roles_claim_ids` | No | list of strings (e.g., value \[, ...] | \[] | Specifies the token claims that can be used to map the user to a Database role. If you specify the `roles_claim_mappings` property, you must also specify the `roles_claim_ids` property. |
| `roles_claim_mappings` | No | map of strings (e.g., key = value \[, ...]) | Specifies mappings from the Provider role to the Database role. | |
| `allowed_groups` | No | list of strings (e.g., value \[, ...] | \[] | Specifies a list of external identity provider groups that are permitted to authenticate through this SSO integration. If you specify the `allowed_groups` property, only users who are members of the specified identify provider groups can access the Ocient System.
If this property is empty or you do not specify it, then group-based filtering is disabled, and the system allows all authenticated users from the provider unless they are explicitly blocked. Group names must match exactly as they appear in the claims of the identify provider group. |
| `allowed_roles` | No | list of strings (e.g., value \[, ...] | \[] | Defines a list of external identity provider roles that are authorized to access the Ocient System through this SSO integration. Only users assigned to the specified roles in the external provider can authenticate.
If this property is empty or you do not specify it, role-based access control is disabled for this integration. Role names must correspond exactly to the role claims provided by the identity provider in the authentication response. |
| `blocked_groups` | No | list of strings (e.g., value \[, ...] | \[] | Specifies a list of external identity provider groups that are explicitly denied access through this SSO integration. The system blocks users who are members of any specified group in the external identity provider from authenticating, regardless of other permissions they have. Setting this property takes precedence over the `allowed_groups` property if a user belongs to both an allowed group and a blocked group. Group names must match exactly as they appear in the claims of the identify provider group. |
| `blocked_roles` | No | list of strings (e.g., value \[, ...] | \[] | Defines a list of external identity provider roles that are explicitly prohibited from accessing the Ocient System through this SSO integration. The system denies access to users assigned to any of the specified roles, overriding any other access permissions. Setting this property takes precedence over the `allowed_roles` property in cases where a user is in both an allowed role and a blocked role. Role names must correspond exactly to the role claims of the identity provider group. |
| `allow_offline_access` | No | Boolean | `false` | When the `allow_offline_access` property is `true`, Ocient requests offline access from the OpenID Connect identity provider by including `access_type=offline` and `prompt=consent` in the authorization URL. |
After all parameters have been retrieved, a database administrator can execute a DDL SQL statement using this syntax.
```sql SQL theme={null} theme={null}
ALTER DATABASE database
{ SET | ALTER } SSO INTEGRATION sso_protocol [, ...]
::=
-- literal or string
property_name = value |
-- list
property_name = [ value [, ...] ] |
-- map
property_name = { key = value [, ...] } # map
```
```sql SQL theme={null} theme={null}
ALTER DATABASE example_database
SET SSO INTEGRATION oidc
issuer = "https://example.com",
client_id = "xxxxxx",
default_group = "default",
additional_scopes = [email, groups, profile, offline_access],
user_id_claims = [claim1, claim2],
groups_claim_ids = [claim3],
groups_claim_mappings = { idp_group1 = ocient_group1, idp_group2 = ocient_group2 };
```
* The user must be a database administrator (or have the "Security Administrator" role for the "system" database).
* The user must be connected to the database.
* Any String key or value can be placed between double quotations (e.g., `default_group` OR `"default_group"`).
* String values that contain characters other than `([a-zA-z] | [0-9] | '_')` must be placed between double quotations (e.g., `this.is.a.complex-$tring` ⇒ `"this.is.a.complex-$tring"`).
* The `NULL` value can be used to clear existing configurations of `LIST` or `MAP` properties (e.g., `user_claim_ids = NULL`).
To remove the connection, execute this SQL statement.
```sql SQL theme={null}
ALTER DATABASE example_database REMOVE SSO INTEGRATION;
```
The OpenID Connect protocol requires TLS for communication between the end user, the database, and the OpenID Provider. A valid TLS key and certificate pair must be configured on the SQL Nodes, which behave as a server during the Authorization Code Flow.
### Set Up Machine-To-Machine SSO Integration
You can use DDL SQL statements to add client credentials for SSO connection to individual databases or to a connectivity pool that operates across SQL Nodes.
These steps set up SSO client credentials on a database, but can also apply to connectivity pools.
**Create an SSO protocol.**
Use the [CREATE SSO INTEGRATION](/cluster-and-node-management#create-sso-integration) SQL statement to make an SSO integration protocol with your preferred configuration. This configuration must include these properties:
* The `enable_id_token_authentication` SSO property must be set to `true`.
* The `additional_audiences` SSO property must use the URL from the OIDC provider, similar to the `issuer` value.
```sql SQL theme={null}
CREATE SSO INTEGRATION sso_test PROTOCOL oidc
issuer = "https://accounts.google.com",
client_id = example_database_app_id,
default_group = example_database_group,
enable_id_token_authentication = true,
additional_audiences = ["https://accounts.google.com"];
```
**Assign the SSO protocol.**
Use the [ALTER DATABASE SET SSO INTEGRATION](/databases#alter-database-set-sso-integration) SQL statement to integrate the SSO protocol into a database. For connectivity pools, use the [ALTER CONNECTIVITY\_POOL SET SSO INTEGRATION](/cluster-and-node-management#alter-connectivity_pool-set-sso-integration) SQL statement.
```sql SQL theme={null}
ALTER DATABASE example_database
SET SSO INTEGRATION sso_test;
```
**Connect to your system.**
Use a JDBC connection string that includes the access token value ``. This string connects to the local host at port number `4050`, uses the SSO protocol, and with the username `id_token`.
```shell Shell theme={null}
CONNECT TO jdbc:ocient://localhost:4050/system;handshake=SSO;user=id_token;password=
```
### Set Up Cross-Database SSO Integration
Set up authentication using SSO integration across databases. Identify the database that has SSO integration using the `username@database` format, where `username` is the access or identifier token and `database` is the database for the SSO integration. Each SSO integration has a client identifier `client_id`. You must obtain the access token using the same client identifier used in the SSO integration for authentication.
When you authenticate using SSO integration as a user, the system assigns you to a group defined in the integration. Such users always have groups qualified with the SSO integration of the database. These groups have fully qualified names such as `sso_users@system`, where `sso_users` is the name of the group and `system` is the name of the database. You can use a fully qualified group name from any database. Without the `@database` qualification, the referenced group specifies the current database. To grant cross-database privileges to such groups, you must reference them using their fully qualified names. You can find a list of the groups the current user is a member of by using the [CURRENT\_GROUPS](/other-functions-and-expressions#current_groups) function.
To manage privileges and groups, use the `GRANT`, `REVOKE`, `ALTER GROUP`, and `DROP GROUP` SQL statements. For details about privileges, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
**Requirements**
* Configure the SSO integration in the source database.
* The SSO user must be a member of a group that has the USE privilege on the target database. If the SSO user is not a member of any groups, the default group for the SSO integration must have the USE privilege on the target database.
* The token (either an access or an identifier token) must be valid for the SSO integration in the source database.
**Create a Cross-Database SSO Integration**
These steps guide you through setting up a cross-database SSO integration.
Create a default group `sso_users`.
```sql SQL theme={null}
CREATE GROUP sso_users;
```
Create the SSO integration `test_sso` in the source database using the `CREATE SSO INTEGRATION` SQL statement. Specify your issuer and client identifier for the `issuer` and `client_id` parameters.
```sql SQL theme={null}
CREATE SSO INTEGRATION test_sso PROTOCOL OIDC
enable_id_token_authentication = true,
issuer = 'https://your-idp.com/oidc',
client_id = 'your_client_id',
default_group = sso_users,
additional_scopes = [profile, email, groups, offline_access],
protocol_version = 'v1',
groups_claim_ids = [groups];
```
Set the SSO integration as the default for the database `source_db`. This step is optional. To set up SSO integration for the `system` database, substitute `source_db` with `system`.
```sql SQL theme={null}
ALTER DATABASE source_db SET SSO INTEGRATION test_sso;
```
Grant cross-database privileges to the target database `target_db` for the default group `sso_users`.
```sql SQL theme={null}
GRANT USE ON DATABASE target_db TO GROUP sso_users;
```
Connect to the target database `target_db` at the local host with port number `4050` using the JDBC driver with an access token on the source database `access_token@source_db`. Specify a password token.
```none Text theme={null}
Properties props = new Properties();
props.setProperty("user", "access_token@source_db");
props.setProperty("password", token);
props.setProperty("handshake", "sso");
Connection conn = DriverManager.getConnection("jdbc:ocient://host:4050/target_db", props);
```
Or, connect using the device flow by using the name of the source database `@source_db`.
```none Text theme={null}
Properties props = new Properties();
props.setProperty("user", "@source_db");
props.setProperty("handshake", "sso");
props.setProperty("ssoOAuthFlow", "deviceGrant");
Connection conn = DriverManager.getConnection("jdbc:ocient://host:4050/target_db", props);
```
Verify your connection using these queries:
Check the current user using the [CURRENT\_USER](/other-functions-and-expressions#current_user) function.
```sql SQL theme={null}
SELECT CURRENT_USER();
```
Check the current groups using the CURRENT\_GROUPS function.
```sql SQL theme={null}
SELECT CURRENT_GROUPS();
```
Check the current database using the [CURRENT\_DATABASE](/other-functions-and-expressions#current_database) function.
```sql SQL theme={null}
SELECT CURRENT_DATABASE();
```
View session information using the `sys.sessions` system catalog table and the identifier of the current session by using the [CURRENT\_SESSION\_ID](/other-functions-and-expressions#current_session_id) function.
```sql SQL theme={null}
SELECT * FROM sys.sessions WHERE id = CURRENT_SESSION_ID();
```
You can also retrieve information about the defined groups using the `sys.groups` system catalog table.
**Driver Connection Properties**
These tables describe the connection properties you can specify.
**pyocient Parameters**
This table lists the DNS parameters that apply to SSO integration. For details, see [Ocient Python Module: pyocient](/ocient-python-module-pyocient).
| **Parameter** | **Description** | **Example** |
| ------------------ | -------------------------------------------- | ------------------------------------------ |
| `handshake` | Authentication method to use for connection. | `sso` |
| `ssoOAuthFlow` | Type of OAuth flow. | `deviceGrant` or `authenticationCode` |
| `identityprovider` | The name of the SSO integration. | `test_sso` |
**JDBC Driver Properties**
This table lists the JDBC connection properties that apply to SSO integration. For details, see [CONNECT](/commands-supported-by-the-ocient-jdbc-cli-program#connect).
| **Property** | **Description** | **Example** |
| ------------------ | -------------------------------------------- | ------------------------------------------ |
| `handshake` | Authentication method to use for connection. | `sso` |
| `ssoOAuthFlow` | Type of OAuth flow. | `deviceGrant` or `authenticationCode` |
| `identityprovider` | The name of the SSO integration. | `test_sso` |
### User Access Control and Workload Management with SSO
The database maintains an internal User Access Control model consisting of groups, roles, and service classes. The database relies on group or role membership to determine the privileges of a user or service class. The following integration properties allow administrators to grant SSO users membership to a Database group or role:
* The `groups_claim_ids` and `roles_claim_ids` properties define the token claims that specify the Provider-defined groups or roles of the user.
* The `groups_claim_mappings` and `roles_claim_mappings` properties define mappings between a Provider and Database groups or roles.
* The `additional_scopes` property should include any request scopes needed for the Provider to include the group or role claims in tokens it issues.
Because SSO users can map to multiple groups, when choosing which group to assign creator privileges, the system follows this criteria:
* Filter by authorization using only groups with CREATE privileges on the relevant schema or database.
* When multiple authorized groups exist at different levels, the system uses hierarchy precedence to ensure that privileges are assigned at the most specific scope. The enforced hierarchy is that schema-level group privileges take precedence over database-level group privileges.
* If multiple groups match at the same level, the system selects the group name by using alphabetical order.
For example, if an SSO user belongs to the `analytics_team` group (with CREATE privileges at the database level) and `finance_schema_admins` group (with CREATE privileges at the schema level), and creates a table in the `finance` schema, the system assigns creator privileges to `finance_schema_admins`.
For details about privileges, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
Consider an example where the Provider lists all groups the user belongs to in the token claim `"user_groups"` when the application requests the `"example_scope"` scope. In this scenario, the administrator wants to associate the Provider Group `"Example Provider Group"` with the Database Role `"example_database Analyst"`.
```sql SQL theme={null}
ALTER DATABASE example_database
ALTER SSO INTEGRATION oidc
/* Tell the Database to request the "profile", "email" and "offline_access" scopes */
additional_scopes = [ profile, email, offline_access ],
/* Tell the Database to look for the "user_groups" token claim to establish role membership */
roles_claim_ids = [ user_groups ],
/* Map provider group "Example Provider Group" to database role "example_database Analyst" */
roles_claim_mappings = { "Example Provider Group" = "example_database Analyst" };
```
By default, the database grants all users membership to the "Public Role" of the database for the current connection. Unlike other default roles, you can grant additional privileges to the "Public Role".
Additionally, database administrators can revoke access to users with membership to any of the specified Provider groups or roles. To revoke access, execute this statement.
```sql SQL theme={null}
ALTER DATABASE example_database
ALTER SSO INTEGRATION oidc
blocked_groups = [ [, ...] ],
blocked_roles = [ [, ...] ];
```
The user must have the ALTER privilege on all Ocient-defined groups or roles specified by `groups_claim_mappings`, `roles_claim_mappings`, `blocked_groups`, and `blocked_roles`.
### User Claim Identifiers (IDs)
By default, audit trails, including but not limited to system-level log messages, identify users connecting using SSO by the `email` claim of the ID Token. If the `email` claim is not present in the token, the identifier is `iss` and `sub` ID Token claims separated by `::`, for example: `"https://ocient.okta.com::00u5rslndgXm9Ey7y5d7"`.
To change the FQUN, alter the `user_claim_ids` SSO integration property.
For example, to change the FQUN to a combination of the `first_name` and `last_name` claim values, execute this SQL statement.
```sql SQL theme={null}
ALTER DATABASE example_database
ALTER SSO INTEGRATION oidc
user_claim_ids = [first_name, last_name, email];
```
After executing this statement, users are identified with the `::::` format. (For example: `John::Smith::jsmith@example.com`)
Updating the `user_claim_ids` property has no effect on users that are already connected to the database.
### System Catalog Tables
Properties that do not contain sensitive data can be viewed using the `sys.oidc_integrations` virtual table. In addition to the configurable properties, a `database_id` column is included in the schema.
To view the configuration for a specific database (if one exists), execute this SQL statement.
```sql SQL theme={null}
SELECT *
FROM sys.databases
JOIN sys.oidc_integrations
ON databases.id = oidc_integrations.database_id
WHERE databases.name = 'example_database';
```
The user must be a database administrator to view the OpenID Connect properties.
## Related Links
[Data Definition Language (DDL) Statement Reference](/data-definition-language-ddl-statement-reference)
[SQL Reference](/sql-reference)
[System Catalog](/system-catalog)
# Backup and Restore
Source: https://docs.ocient.com/backup-and-restore
Back up and restore Ocient databases using the BACKUP and RESTORE SQL statements to protect data, recover from failures, and migrate between environments.
can back up and restore a single node or a multi-node system. The backup and restore procedures can replace a node in an existing Ocient cluster due to an OS drive failure or hardware upgrade.
Exact backup and restore procedures depend on the disk layout of your Ocient nodes. Consult Ocient Support or the system administrator who installed your Ocient cluster to determine the best backup strategy for your deployment.
## Related Links
[Maintenance Overview](/maintenance-overview)
# Categorized SQL Functions List
Source: https://docs.ocient.com/categorized-sql-functions-list
Categorized reference of Ocient SQL functions grouped by purpose, including aggregate, conversion, date and time, math, string, spatial, and machine learning.
| **Function Name** | **Category Name** | **Function Description** |
| ----------------------------------------------------------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [ACCURACY\_SCORE](/aggregate-functions#accuracy_score) | Aggregate Functions | Returns the fraction of predictions that match the actual class labels. |
| [ANY\_VALUE](/aggregate-functions#any_value) | Aggregate Functions | Returns an arbitrary, non-NULL value from the input column. |
| [APPROX\_COUNT\_DISTINCT](/aggregate-functions#approx_count_distinct) | Aggregate Functions | Approximate distinct count by using hyper-log-log (95% confidence interval that the value is within 4.5%). |
| [APPROX\_SUM](/aggregate-functions#approx_sum) | Aggregate Functions | Allows the aggregation engine to use a faster, non-deterministic ordering to summate floating-point columns. |
| [ARRAY\_AGG](/aggregate-functions#array_agg) | Aggregate Functions | Returns an array containing every row from the expression. |
| [ARRAY\_CONCAT\_AGG](/aggregate-functions#array_concat_agg) | Aggregate Functions | Returns an array that concatenates arrays across rows. |
| [AVG](/aggregate-functions#avg) | Aggregate Functions | Average, or arithmetic mean, over the set. |
| [COEFFICIENT\_OF\_DETERMINATION](/aggregate-functions#coefficient_of_determination) | Aggregate Functions | Computes the coefficient of determination (R²) between actual and predicted values. |
| [CONFUSION\_MATRIX](/aggregate-functions#confusion_matrix) | Aggregate Functions | Returns a structured representation of the counts for every combination of actual and predicted class labels relative to a specified positive class. |
| [CORR](/aggregate-functions#corr) | Aggregate Functions | Alias for CORRELATION. |
| [CORRELATION](/aggregate-functions#correlation) | Aggregate Functions | Sample correlation. |
| [CORRELATIONP](/aggregate-functions#correlationp) | Aggregate Functions | Population correlation. |
| [COUNT](/aggregate-functions#count) | Aggregate Functions | Number of rows in the set. |
| [COVAR\_POP](/aggregate-functions#covar_pop) | Aggregate Functions | Alias for COVARIANCEP. |
| [COVAR\_SAMP](/aggregate-functions#covar_samp) | Aggregate Functions | Alias for COVARIANCE. |
| [COVARIANCE](/aggregate-functions#covariance) | Aggregate Functions | Sample covariance. |
| [COVARIANCEP](/aggregate-functions#covariancep) | Aggregate Functions | Population covariance. |
| [F1\_SCORE](/aggregate-functions#f1_score) | Aggregate Functions | Returns the harmonic mean of precision and recall for a specified positive class. |
| [KURTOSIS](/aggregate-functions#kurtosis) | Aggregate Functions | The sample over the set. |
| [KURTOSISP](/aggregate-functions#kurtosisp) | Aggregate Functions | The population over the set. |
| [MAX](/aggregate-functions#max) | Aggregate Functions | Maximum value in the specified column. |
| [MEAN\_ABSOLUTE\_ERROR](/aggregate-functions#mean_absolute_error) | Aggregate Functions | Returns the mean absolute error (MAE) between actual and predicted values. |
| [MEAN\_ABSOLUTE\_PERCENTAGE\_ERROR](/aggregate-functions#mean_absolute_percentage_error) | Aggregate Functions | Returns the mean absolute percentage error (MAPE) between actual and predicted values. |
| [MIN](/aggregate-functions#min) | Aggregate Functions | Minimum value in the specified column. |
| [PRECISION\_SCORE](/aggregate-functions#precision_score) | Aggregate Functions | Returns the precision score for a specified positive class. |
| [PRODUCT](/aggregate-functions#product) | Aggregate Functions | Product over the set. |
| [RECALL\_SCORE](/aggregate-functions#recall_score) | Aggregate Functions | Returns the recall score for a specified positive class. |
| [ROC\_AUC\_SCORE](/aggregate-functions#roc_auc_score) | Aggregate Functions | Returns the area under the receiver operating characteristic (ROC) curve (AUC). |
| [SKEW](/aggregate-functions#skew) | Aggregate Functions | The sample skewness over the set of values. |
| [SKEWP](/aggregate-functions#skewp) | Aggregate Functions | Computes the population skewness over the set of values. |
| [STDEV](/aggregate-functions#stdev) | Aggregate Functions | Sample standard deviation. |
| [STDDEV](/aggregate-functions#stddev) | Aggregate Functions | Alias for STDEV. |
| [STDDEV\_POP](/aggregate-functions#stddev_pop) | Aggregate Functions | Alias for STDEVP. |
| [STDDEV\_SAMP](/aggregate-functions#stddev_samp) | Aggregate Functions | Alias for STDEV. |
| [STDEVP](/aggregate-functions#stdevp) | Aggregate Functions | Population standard deviation. |
| [STRING\_AGG](/aggregate-functions#string_agg) | Aggregate Functions | Returns a string concatenated from every row from the expression. The delimiter argument is optional. |
| [SUM](/aggregate-functions#sum) | Aggregate Functions | Sum over the set. |
| [VAR\_POP](/aggregate-functions#var_pop) | Aggregate Functions | Alias for VARIANCEP. |
| [VAR\_SAMP](/aggregate-functions#var_samp) | Aggregate Functions | Alias for VARIANCE. |
| [VARIANCE](/aggregate-functions#variance) | Aggregate Functions | Sample variance. |
| [VARIANCEP](/aggregate-functions#variancep) | Aggregate Functions | Population variance. |
| [ARRAY\[\]](/array-functions-and-operators) | Array Functions | -compliant constructor. The type of the array is deduced from the elements. |
| [ARRAY\_APPEND](/array-functions-and-operators) | Array Functions | Add value to the back of an array. |
| [ARRAY\_ARGMAX](/array-functions-and-operators) | Array Functions | Returns the corresponding argmax of the array as a BIGINT index. |
| [ARRAY\_ARGMIN](/array-functions-and-operators) | Array Functions | Returns the corresponding argmin of the array as a BIGINT index. |
| [ARRAY\_CAT](/array-functions-and-operators) | Array Functions | Concatenate 2 arrays into a new one. |
| [ARRAY\_CAT\_DISTINCT](/array-functions-and-operators#array_cat_distinct) | Array Functions | Concatenates two or more arrays in the order of the input arguments. |
| [ARRAY\_DISTINCT](/array-functions-and-operators#array_distinct) | Array Functions | Removes duplicates from an array while preserving the first occurrence order. |
| [ARRAY\_LENGTH](/array-functions-and-operators) | Array Functions | Return the number of elements of a given array. |
| [ARRAY\_MAX](/array-functions-and-operators) | Array Functions | Returns the corresponding maximum of the array. |
| [ARRAY\_MIN](/array-functions-and-operators) | Array Functions | Returns the corresponding minimum of the array. |
| [ARRAY\_POSITION](/array-functions-and-operators) | Array Functions | Returns the position of the first matching scalar in the array. |
| [ARRAY\_POSITIONS](/array-functions-and-operators) | Array Functions | Returns all elements stored in the right array, and return their respective positions in the left array. |
| [ARRAY\_PREPEND](/array-functions-and-operators) | Array Functions | Add value to the front of an array. |
| [ARRAY\_REMOVE](/array-functions-and-operators) | Array Functions | Remove value from the array. |
| [ARRAY\_REPLACE](/array-functions-and-operators) | Array Functions | Replace value by another in an array. |
| [ARRAY\_SUM](/array-functions-and-operators) | Array Functions | Returns the sum of the array. The array must be one-dimensional and contain numeric values. NULL values do not contribute to the sum. |
| [ARRAY\_TO\_STRING](/array-functions-and-operators) | Array Functions | Converts array to a list of elements separated by 'delimiter'. |
| [CAST\_TO\_ARRAY](/array-functions-and-operators) | Array Functions | Casts the elements of the array to another type. |
| [CHAR](/array-functions-and-operators) | Array Functions | Converts array to its string representation. |
| [CROSS\_ENTROPY\_LOSS](/array-functions-and-operators) | Array Functions | Returns the cross entropy loss of two arrays. |
| [HINGE\_LOSS](/array-functions-and-operators) | Array Functions | Returns the hinge loss of two arrays. |
| [LOG\_LOSS](/array-functions-and-operators) | Array Functions | Returns the log loss of two arrays. |
| [LOGITS\_LOSS](/array-functions-and-operators) | Array Functions | Returns the logits loss of two arrays. |
| [SOFTMAX](/array-functions-and-operators) | Array Functions | Returns the softmax of the array. |
| [STRING\_TO\_ARRAY](/array-functions-and-operators) | Array Functions | Converts the string representation of an array (e.g., `'int[1,2,NULL]'`) into an array. |
| [TYPE\[\]](/array-functions-and-operators) | Array Functions | Construct an array of SQL type TYPE giving the elements. |
| [UNNEST](/array-functions-and-operators#unnest) | Array Functions | Expand each element in an input array out to an individual row. |
| [ASCII](/character-and-binary-functions#ascii) | Character and Binary Functions | Returns the ASCII code value of the leftmost character of the character value. |
| [BIT\_LENGTH](/character-and-binary-functions#bit_length) | Character and Binary Functions | Returns the length of the character value in bits. |
| [BTRIM](/character-and-binary-functions#btrim) | Character and Binary Functions | Alias for TRIM. |
| [CHAR\_LENGTH](/character-and-binary-functions#char_length) | Character and Binary Functions | Alias for LENGTH. |
| [CHARACTER\_LENGTH](/character-and-binary-functions#character_length) | Character and Binary Functions | Alias for LENGTH. |
| [CHR](/character-and-binary-functions#chr) | Character and Binary Functions | Converts an integer value to a string. |
| [CONCAT](/character-and-binary-functions#concat) | Character and Binary Functions | Concatenates two values, which must both be either binary, hash, or string data types. This function is equivalent to the \|\| operator. |
| [ENDSWITH](/character-and-binary-functions#endswith) | Character and Binary Functions | Returns true if x ends with y and false otherwise. |
| [INITCAP](/character-and-binary-functions#initcap) | Character and Binary Functions | For each word in the provided string, capitalize the first character if it is alphabetic. |
| [INSTR](/character-and-binary-functions#instr) | Character and Binary Functions | Returns the index position of the first occurrence where the character value char\_substring appears in the character value char by ignoring the case. |
| [JSON\_EXTRACT\_PATH\_TEXT](/character-and-binary-functions#json_extract_path_text) | Character and Binary Functions | Returns the value for the key-value pair referenced by a series of path elements in a JSON string. |
| [LCASE](/character-and-binary-functions#lcase) | Character and Binary Functions | Alias for LOWER. |
| [LEFT](/character-and-binary-functions#left) | Character and Binary Functions | Return the number of characters in the string equal to the value integer. If the integer is negative, the function returns all but the last integer characters. |
| [LENGTH](/character-and-binary-functions#length) | Character and Binary Functions | For character data types, this value is in terms of characters. For binary data types, this value is in terms of bytes. |
| [LOCATE](/character-and-binary-functions#locate) | Character and Binary Functions | Alias for POSITION. Returns the index position of the first occurrence of the character value substring in character value string. |
| [LOWER](/character-and-binary-functions#lower) | Character and Binary Functions | Alias for LCASE. Convert string to lowercase. |
| [LPAD](/character-and-binary-functions#lpad) | Character and Binary Functions | Pad the input text to the specified length with the pad string on the left side. |
| [LTRIM](/character-and-binary-functions#ltrim) | Character and Binary Functions | Removes leading blanks from the string value string. |
| [MD5](/character-and-binary-functions#md5) | Character and Binary Functions | Returns the hexadecimal string (all lowercase) representing the md5 hash of char. |
| [MID](/character-and-binary-functions#mid) | Character and Binary Functions | Alias for SUBSTRING. |
| [OCTET\_LENGTH](/character-and-binary-functions#octet_length) | Character and Binary Functions | Returns the length in bytes of a character or binary value. |
| [POSITION](/character-and-binary-functions#position) | Character and Binary Functions | Alias for LOCATE. |
| [REGEXP\_COUNT](/character-and-binary-functions#regexp_count) | Character and Binary Functions | Searches a string for all occurrences of a regular expression pattern. |
| [REGEXP\_INSTR](/character-and-binary-functions#regexp_instr) | Character and Binary Functions | Searches a string using a regular expression pattern and returns an integer representing the start position or end position of the substring that matches. |
| [REGEXP\_REPLACE](/character-and-binary-functions#regexp_replace) | Character and Binary Functions | Searches a string for all occurrences of a regular expression pattern. |
| [REGEXP\_SUBSTR](/character-and-binary-functions#regexp_substr) | Character and Binary Functions | Returns one substring from a string that matches a specified regular expression pattern. |
| [REPEAT](/character-and-binary-functions#repeat) | Character and Binary Functions | Repeats the character value char a number of times equal to num. |
| [REPLACE](/character-and-binary-functions#replace) | Character and Binary Functions | Replaces all occurrences of substr\_to\_remove in the character value string with substr\_to\_replace. |
| [REVERSE](/character-and-binary-functions#reverse) | Character and Binary Functions | Reverse the input string. |
| [RIGHT](/character-and-binary-functions#right) | Character and Binary Functions | Return the number of trailing characters in the string equal to the value integer. |
| [RPAD](/character-and-binary-functions#rpad) | Character and Binary Functions | Pad the input text to the specified length with the pad string on the right side. |
| [RSUBSTRING](/character-and-binary-functions#rsubstring) | Character and Binary Functions | Returns the substring from the right side of a string based on a specified length. |
| [RTRIM](/character-and-binary-functions#rtrim) | Character and Binary Functions | Removes leading blanks from the string value string. |
| [SHA1](/character-and-binary-functions#sha1) | Character and Binary Functions | Uses the \[SHA-1]\([https://en.wikipedia.org/wiki/SHA-1#:\~:text=In%20cryptography%2C%20SHA%2D1%20(,rendered%20as%2040%20hexadecimal%20digits](https://en.wikipedia.org/wiki/SHA-1#:~:text=In%20cryptography%2C%20SHA%2D1%20\(,rendered%20as%2040%20hexadecimal%20digits).) cryptographic hash function to convert a string into a 40-character string representing the hexadecimal value of a 160-bit checksum. |
| [SPACE](/character-and-binary-functions#space) | Character and Binary Functions | Returns a string of repeated spaces equal to the number value, repeat. |
| [SPLIT\_PART](/character-and-binary-functions#split_part) | Character and Binary Functions | Split the value string based on the delimiter value. The function returns a substring from the split operation based on the index value (starting from 1). |
| [SPLIT\_TO\_ARRAY](/character-and-binary-functions#split_to_array) | Character and Binary Functions | Splits a string into an array of substrings. |
| [STARTSWITH](/character-and-binary-functions#startswith) | Character and Binary Functions | Returns true if string starts with substring and false otherwise. |
| [STRPOS](/character-and-binary-functions#strpos) | Character and Binary Functions | Equivalent to using LOCATE as LOCATE(substring, string). Note the reversed argument order. |
| [SUBSTR](/character-and-binary-functions#substr) | Character and Binary Functions | Alias for SUBSTRING. |
| [SUBSTRING](/character-and-binary-functions#substring) | Character and Binary Functions | Returns the substring of a character or binary value. |
| [TO\_CHAR](/character-and-binary-functions#to_char) | Character and Binary Functions | Converts a numeric, date, or timestamp value into a CHAR date type. |
| [TRANSLATE](/character-and-binary-functions#translate) | Character and Binary Functions | Replaces specified characters in a provided string with a separate set of characters. |
| [TRIM](/character-and-binary-functions#trim) | Character and Binary Functions | Alias for BTRIM. Trim leading and trailing blanks from the string. |
| [UCASE](/character-and-binary-functions#ucase) | Character and Binary Functions | Alias for UPPER. |
| [UPPER](/character-and-binary-functions#upper) | Character and Binary Functions | Convert string to upper case. |
| [CASE](/other-functions-and-expressions#case) | Conditional Functions | CASE operates similarly to conditional scripting in other programming languages, allowing it to function like an if / then / else statement or as a switch statement. |
| [COALESCE](/other-functions-and-expressions#coalesce) | Conditional Functions | Evaluates to the first argument that is not NULL, or NULL if all arguments are NULL. |
| [GREATEST](/other-functions-and-expressions#greatest) | Conditional Functions | Returns the largest non-NULL value of all the arguments, or NULL if all the arguments are NULL. |
| [IF\_NULL](/other-functions-and-expressions#if_null) | Conditional Functions | Alias for COALESCE. |
| [LEAST](/other-functions-and-expressions#least) | Conditional Functions | Returns the smallest non-NULL value of all arguments, or NULL if all arguments are NULL. |
| [MURMUR3](/other-functions-and-expressions#murmur3) | Conditional Functions | [Returns a 32-bit MurmurHash3 hash of the input value as an INTEGER data type.](https://github.com/aappleby/smhasher/blob/master/README.md) |
| [NULL\_IF](/other-functions-and-expressions#null_if) | Conditional Functions | Returns the NULL value if two arguments are equal; otherwise, returns the first argument. |
| [ZN](/other-functions-and-expressions#zn) | Conditional Functions | If x is NULL, returns 0. Otherwise, returns x. |
| [LAG\_VECTORS](/data-preparation#lag_vectors) | Data Preparation | Groups lagged columns generated by the `MULTI_LAGS` or `MULTI_LAGS_ZEROFILL` functions into vector columns. |
| [LAGS](/data-preparation#lags) | Data Preparation | Generates a series of lagged columns for a single variable in one statement. |
| [LAGS\_ZEROFILL](/data-preparation#lags_zerofill) | Data Preparation | Generates lagged columns for a single variable and replaces NULL values with `0`. |
| [MULTI\_LAGS](/data-preparation#multi_lags) | Data Preparation | Generates lagged columns for multiple variables at once. |
| [MULTI\_LAGS\_ZEROFILL](/data-preparation#multi_lags_zerofill) | Data Preparation | Generates lagged columns for multiple variables and replaces NULL values with `0`. |
| [ADD\_MONTHS](/date-and-time-functions#add_months) | Date and Time Functions | Adds the specified number of months to the date. |
| [CENTURY](/date-and-time-functions#century) | Date and Time Functions | Returns the number of centuries. |
| [CURDATE](/date-and-time-functions#curdate) | Date and Time Functions | Alias for CURRENT\_DATE. |
| [CURRENT\_DATE](/date-and-time-functions#current_date) | Date and Time Functions | Returns the current date in the format YYYY-MM-DD. |
| [CURRENT\_TIME](/date-and-time-functions#current_time) | Date and Time Functions | Returns the current time as a TIME value (e.g., `hh:mm:ss.mm`). |
| [CURRENT\_TIMESTAMP](/date-and-time-functions#current_timestamp) | Date and Time Functions | Returns the current date and time as a TIMESTAMP value (e.g., YYYY-MM-DD hh🇲🇲ss.mmm). |
| [DATE\_PART](/date-and-time-functions#date_part) | Date and Time Functions | Alias for EXTRACT. |
| [DATE\_TRUNC](/date-and-time-functions#date_trunc) | Date and Time Functions | Returns the date or timestamp entered, truncated to the specified precision. |
| [DATEADD](/date-and-time-functions#dateadd) | Date and Time Functions | Adds a specified number value (as a signed integer) to a specified date part of an input date value, and then returns that modified value. |
| [DATEDIFF](/date-and-time-functions#datediff) | Date and Time Functions | This function returns an INT representing the difference between two date or time values in a specified date or time unit. |
| [DAY](/date-and-time-functions#day) | Date and Time Functions | Alias for DAY\_OF\_MONTH. |
| [DAY\_OF\_MONTH](/date-and-time-functions#day_of_month) | Date and Time Functions | Extracts the day-of-month portion of a timestamp or date as an integer. |
| [DAY\_OF\_WEEK](/date-and-time-functions#day_of_week) | Date and Time Functions | Returns an integer, in the range of 1 to 7, that represents the day of the week. |
| [DAY\_OF\_YEAR](/date-and-time-functions#day_of_year) | Date and Time Functions | Returns an integer in the range 1 to 366 that represents the day of the year. |
| [DECADE](/date-and-time-functions#decade) | Date and Time Functions | The decade is the year divided by 10. |
| [DOW](/date-and-time-functions#dow) | Date and Time Functions | Alias for DAY\_OF\_WEEK. |
| [DOY](/date-and-time-functions#doy) | Date and Time Functions | Alias for DAY\_OF\_YEAR. |
| [EOMONTH](/date-and-time-functions#eomonth) | Date and Time Functions | Returns the last day of the timestamp or date. |
| [EPOCH](/date-and-time-functions#epoch) | Date and Time Functions | The number of seconds after 1970-01-01 00:00:00 UTC. |
| [EXTRACT](/date-and-time-functions#extract) | Date and Time Functions | Extract a component from a timestamp or date. |
| [HOUR](/date-and-time-functions#hour) | Date and Time Functions | Extracts the hour portion of a timestamp as an integer. |
| [ISDATE](/date-and-time-functions#isdate) | Date and Time Functions | Returns TRUE if the input argument can be successfully cast to a date. |
| [ISODOW](/date-and-time-functions#isodow) | Date and Time Functions | Extracts the day of the week based on ISO 8601, which ranges from Monday (1) to Sunday (7). |
| [MAKEDATETIME](/date-and-time-functions#makedatetime) | Date and Time Functions | Returns a timestamp consisting of the specified date and time. |
| [MILLISECOND](/date-and-time-functions#millisecond) | Date and Time Functions | Extracts the millisecond portion of a timestamp as an integer. |
| [MINUTE](/date-and-time-functions#minute) | Date and Time Functions | Extracts the minute portion of a timestamp or date as an integer. |
| [MONTH](/date-and-time-functions#month) | Date and Time Functions | Extracts the month portion of a timestamp or date as an integer. |
| [MONTH\_NAME](/date-and-time-functions#month_name) | Date and Time Functions | Returns the calendar name in English of the month for the specified date. |
| [MONTHS\_BETWEEN](/date-and-time-functions#months_between) | Date and Time Functions | Returns the difference between the two dates or timestamps in months as a DOUBLE. |
| [MSECS](/date-and-time-functions#msecs) | Date and Time Functions | The seconds field, including fractional parts. The function multiplies the seconds part of the value by 1,000. |
| [NANOS\_TO\_TIMESTAMP](/date-and-time-functions#nanos_to_timestamp) | Date and Time Functions | Convert a number of nanoseconds into a timestamp equivalent to the duration after the epoch time. |
| [NEXT\_DAY](/date-and-time-functions#next_day) | Date and Time Functions | Returns the closest date after a specified date that lies on a specific day of the week. |
| [NOW](/date-and-time-functions#now) | Date and Time Functions | Alias for CURRENT\_TIMESTAMP. |
| [QUARTER](/date-and-time-functions#quarter) | Date and Time Functions | Returns an integer between 1 and 4 that represents the quarter of the year in which the specified date falls. |
| [ROUND](/date-and-time-functions#round) | Date and Time Functions | Returns the specified date or timestamp, rounded to the specified precision. |
| [SECOND](/date-and-time-functions#second) | Date and Time Functions | Extracts the seconds portion of a timestamp as an integer. |
| [TIMESTAMP\_TO\_NANOS](/date-and-time-functions#timestamp_to_nanos) | Date and Time Functions | Convert timestamp into nanoseconds after epoch as BIGINT. |
| [USECS](/date-and-time-functions#usecs) | Date and Time Functions | The seconds part of a time value, including fractional parts, returned as an integer. The function multiplies the seconds part of the value by 1,000,000. |
| [WEEK](/date-and-time-functions#week) | Date and Time Functions | Returns the ISO-8601 week number, as an integer, of the specified timestamp or date value. |
| [YEAR](/date-and-time-functions#year) | Date and Time Functions | Extracts the year portion of a timestamp or date as an integer. |
| [TO\_DATE](/formatting-functions#to_date) | Formatting Functions | Converts a character value with the specified format to a DATE type. |
| [TO\_NUMBER](/formatting-functions#to_number) | Formatting Functions | Converts a character value with the specified format to a DECIMAL type. |
| [TO\_TIMESTAMP](/formatting-functions#to_timestamp) | Formatting Functions | Converts a character value with the specified format to a TIMESTAMP type. |
| [ST\_COORDDIM](/attribute-functions#st_coorddim) | Geospatial Attribute Functions | Alias for ST\_NDIMS or ST\_NDIMENSION. Returns an INTEGER of the coordinate dimension of the specified geography. |
| [ST\_DIMENSION](/attribute-functions#st_dimension) | Geospatial Attribute Functions | Returns an INTEGER that represents the dimension of the specified geography. |
| [ST\_GEOMETRYTYPE](/attribute-functions#st_geometrytype) | Geospatial Attribute Functions | Returns a string representing the geometry type of the input value. |
| [ST\_ISEMPTY](/attribute-functions#st_isempty) | Geospatial Attribute Functions | Returns TRUE if the specified geography value is empty, such as 'POLYGON EMPTY'. |
| [ST\_MEMSIZE](/attribute-functions#st_memsize) | Geospatial Attribute Functions | Returns an INTEGER representing the number of bytes in memory required to store the specified geography. |
| [ST\_NDIMENSION](/attribute-functions#st_ndims-or-st_ndimension) | Geospatial Attribute Functions | Alias for ST\_COORDDIM. |
| [ST\_NDIMS](/attribute-functions) | Geospatial Attribute Functions | Alias for ST\_COORDDIM. |
| [ST\_NPOINTS](/attribute-functions#st_npoints-or-st_numpoints) | Geospatial Attribute Functions | Returns an INTEGER representing the number of POINT values in a specified geography. |
| [ST\_NUMPOINTS](/attribute-functions) | Geospatial Attribute Functions | Returns an INTEGER representing the number of POINT values in a specified geography. |
| [ST\_SRID](/attribute-functions#st_srid) | Geospatial Attribute Functions | Returns the EPSG code of the spatial reference identifier (SRID) of the input geography. |
| [ST\_X](/attribute-functions#st_x) | Geospatial Attribute Functions | Returns the x value of the specified POINT. |
| [ST\_XMAX](/attribute-functions#st_xmax) | Geospatial Attribute Functions | Returns the maximum x value of the specified geography. |
| [ST\_XMIN](/attribute-functions#st_xmin) | Geospatial Attribute Functions | Returns the minimum x value of the specified geography. |
| [ST\_Y](/attribute-functions#st_y) | Geospatial Attribute Functions | Returns the y value of the specified POINT. |
| [ST\_YMAX](/attribute-functions#st_ymax) | Geospatial Attribute Functions | Returns the maximum y value of specified geography. |
| [ST\_YMIN](/attribute-functions#st_ymin) | Geospatial Attribute Functions | Returns the minimum y value of specified geography. |
| [ST\_ASBINARY](/conversion-functions#st_asbinary) | Geospatial Conversion Functions | Returns the well-known binary (WKB) representation of the specified geography. Alias of ST\_ASWKB. |
| [ST\_ASEWKT](/conversion-functions#st_asewkt) | Geospatial Conversion Functions | Returns a string that represents geographic coordinates of a specified POINT in the specified format. |
| [ST\_ASGEOJSON](/conversion-functions#st_asgeojson) | Geospatial Conversion Functions | Alias of ST\_ASBINARY. |
| [ST\_ASLATLONTEXT](/conversion-functions#st_aslatlontext) | Geospatial Conversion Functions | [Returns the GeoJSON representation of the specified geography using the IETF standards.](https://datatracker.ietf.org/doc/html/rfc7946) |
| [ST\_ASTEXT](/conversion-functions#st_astext) | Geospatial Conversion Functions | Alias of ST\_ASTEXT. |
| [ST\_ASWKB](/conversion-functions#st_aswkb) | Geospatial Conversion Functions | Alias of ST\_ASTEXT. |
| [ST\_ASWKT](/conversion-functions#st_aswkt) | Geospatial Conversion Functions | Alias of ST\_ASWKT and ST\_EWKT. Returns the WKT representation of the specified geography. |
| [ST\_GEOHASH](/conversion-functions#st_geohash) | Geospatial Conversion Functions | Returns a string that represents the geohash of the input POINT. |
| [ST\_ADDPOINT](/linestring-functions#st_addpoint) | Geospatial Linestring Function | Adds a POINT to the specified LINESTRING at the specified 0-indexed location. |
| [ST\_ENDPOINT](/linestring-functions#st_endpoint) | Geospatial Linestring Function | Returns the endpoint of a specified LINESTRING. The returned value is a POINT. |
| [ST\_LINEFROMEWKT](/linestring-constructors#st_linefromewkt) | Geospatial Linestring Constructor | Creates a LINESTRING from the specified CHAR. |
| [ST\_LINEFROMGEOJSON](/linestring-constructors#st_linefromgeojson) | Geospatial Linestring Constructor | Creates a LINESTRING represented by the specified GeoJSON. |
| [ST\_LINEFROMTEXT](/linestring-constructors#st_linefromtext) | Geospatial Linestring Constructor | Creates a LINESTRING from a specified CHAR. The CHAR must be a LINESTRING value in WKT format. |
| [ST\_LINEFROMWKB](/linestring-constructors#st_linefromwkb) | Geospatial Linestring Constructor | Creates a LINESTRING from the specified BINARY. The BINARY value must be a LINESTRING in WKB format. |
| [ST\_LINEINTERPOLATEPOINT](/linestring-functions#st_lineinterpolatepoint) | Geospatial Linestring Function | Returns a POINT along a LINESTRING based on a specified fraction of its total length. |
| [ST\_LINELOCATEPOINT](/linestring-functions#st_linelocatepoint) | Geospatial Linestring Function | Similar to ST\_LINEINTERPOLATEPOINT, this function computes a fraction based on where a specified POINT is located along the length of a specified LINESTRING. |
| [ST\_LINESTRING](/linestring-constructors#st_linestring) | Geospatial Linestring Constructor | Creates a LINESTRING based on the specified inputs. |
| [ST\_LINESUBSTRING](/linestring-functions#st_linesubstring) | Geospatial Linestring Function | Returns a LINESTRING that is a substring of a specified line that starts and ends at the specified fractions of its total length. |
| [ST\_MAKELINE](/linestring-constructors#st_makeline) | Geospatial Linestring Constructor | Alias for ST\_LINESTRING. |
| [ST\_POINTN](/linestring-functions#st_pointn) | Geospatial Linestring Function | Returns the POINT value at a specified index of the specified LINESTRING. |
| [ST\_REMOVEPOINT](/linestring-functions#st_removepoint) | Geospatial Linestring Function | Removes a POINT value at a specified index from the specified line. |
| [ST\_SETPOINT](/linestring-functions#st_setpoint) | Geospatial Linestring Function | Replaces a POINT value in a specified LINESTRING at a specified index. The function returns the altered LINESTRING with the replaced point. |
| [ST\_STARTPOINT](/linestring-functions#st_startpoint) | Geospatial Linestring Function | Returns the starting POINT value of the line. |
| [ST\_CENTROID](/point-constructors#st_centroid) | Geospatial Point Constructors | The geographic center of mass is calculated by taking the average of all points on a three-dimensional sphere, projecting the resultant point onto the sphere, and converting it back to latitude and longitude coordinates. |
| [ST\_GEOGPOINT](/point-constructors#st_geogpoint) | Geospatial Point Constructors | Creates and returns a POLYGON geography with a single point, defined by the longitude and latitude specified for the function. |
| [ST\_MAKEPOINT](/point-constructors#st_makepoint) | Geospatial Point Constructors | Alias for ST\_POINT. |
| [ST\_POINT](/point-constructors#st_point) | Geospatial Point Constructors | Creates a POINT from the specified input arguments. |
| [ST\_POINTFROMEWKT](/point-constructors#st_pointfromewkt) | Geospatial Point Constructors | Alias for ST\_POINT. Creates a POINT using an EWKT-formatted CHAR as an input argument. |
| [ST\_POINTFROMGEOHASH](/point-constructors#st_pointfromgeohash) | Geospatial Point Constructors | Creates a POINT represented by the specified geohash. |
| [ST\_POINTFROMGEOJSON](/point-constructors#st_pointfromgeojson) | Geospatial Point Constructors | Creates a POINT represented by the specified GeoJSON value as an input argument. |
| [ST\_POINTFROMTEXT](/point-constructors#st_pointfromtext) | Geospatial Point Constructors | Alias for ST\_POINT(char). |
| [ST\_POINTFROMWKB](/point-constructors#st_pointfromwkb) | Geospatial Point Constructors | Alias for ST\_POINT(binary). |
| [ST\_FORCECCW](/polygon-constructors#st_forceccw) | Geospatial Polygon Constructors | Creates a standardized polygon from an existing one. defines standardized as the exterior being counterclockwise (CCW) and all holes being clockwise (CW) oriented. |
| [ST\_MAKEPOLYGON](/polygon-constructors#st_makepolygon) | Geospatial Polygon Constructors | Alias for ST\_POLYGON. |
| [ST\_POLYGON](/polygon-constructors#st_polygon) | Geospatial Polygon Constructors | Creates a POLYGON. |
| [ST\_POLYGONFROMEWKT](/polygon-constructors#st_polygonfromewkt) | Geospatial Polygon Constructors | Creates a POLYGON using an EWKT-formatted CHAR as an input argument. Alias for the ST\_POLYGON constructor. |
| [ST\_POLYGONFROMGEOJSON](/polygon-constructors#st_polygonfromgeojson) | Geospatial Polygon Constructors | Creates a POLYGON from the specified POINT, POINT array, LINESTRING, or POLYGON geography. |
| [ST\_POLYGONFROMTEXT](/polygon-constructors#st_polygonfromtext) | Geospatial Polygon Constructors | Alias for ST\_POLYGON(char). |
| [ST\_POLYGONFROMWKB](/polygon-constructors#st_polygonfromwkb) | Geospatial Polygon Constructors | Alias for ST\_POLYGON(binary). |
| [ST\_WHOLEEARTH](/polygon-constructors#st_wholeearth) | Geospatial Polygon Constructors | Returns the database internal representation of the whole earth polygon. |
| [ST\_ANGLE](/spatial-measurement#st_angle) | Geospatial Spatial Measurement | Calculates the angle between two lines. |
| [ST\_AREA](/spatial-measurement#st_area) | Geospatial Spatial Measurement | Returns the area of the specified geospatial object in the specified unit of measurement. |
| [ST\_AZIMUTH](/spatial-measurement#st_azimuth) | Geospatial Spatial Measurement | Returns the azimuth of the line from `point1` to `point2` in radians. |
| [ST\_DISTANCE](/spatial-measurement#st_distance) | Geospatial Spatial Measurement | Returns the minimum distance between the specified arguments. |
| [ST\_DISTANCESPHERE](/spatial-measurement#st_distancesphere) | Geospatial Spatial Measurement | Returns the minimum distance between the specified arguments using a spherical computation. |
| [ST\_DISTANCESPHEROID](/spatial-measurement#st_distancespheroid) | Geospatial Spatial Measurement | Returns the minimum distance between the specified arguments using a spheroid computation. |
| [ST\_EUCLIDEANDISTANCE3D](/spatial-measurement#st_euclideandistance3d) | Geospatial Spatial Measurement | Returns the minimum distance between two geospatial points with altitude values. |
| [ST\_HAUSDORFFDISTANCE](/spatial-measurement#st_hausdorffdistance) | Geospatial Spatial Measurement | Returns the Hausdorff distance between two geographies in a specified measurement. |
| [ST\_LENGTH](/spatial-measurement#st_length) | Geospatial Spatial Measurement | Returns the length of the specified line in the specified measurement unit. |
| [ST\_LENGTH2D](/spatial-measurement#st_length2d) | Geospatial Spatial Measurement | Alias for ST\_LENGTH. |
| [ST\_MAXDISTANCE](/spatial-measurement#st_maxdistance) | Geospatial Spatial Measurement | Returns maximum distance between the specified arguments. |
| [ST\_MINIMUMDISTANCETOSURFACE](/spatial-measurement#st_minimumdistancetosurface) | Geospatial Spatial Measurement | Calculates the shortest distance between any point along a Euclidean line segment in three-dimensional space and the surface of the Earth. |
| [ST\_PERIMETER](/spatial-measurement#st_perimeter) | Geospatial Spatial Measurement | Returns the length of the exterior (outer ring) of the POLYGON in the specified unit of measurement. |
| [ST\_PERIMETER2D](/spatial-measurement#st_perimeter2d) | Geospatial Spatial Measurement | Alias for ST\_PERIMETER. |
| [ST\_BOUNDINGDIAGONAL](/spatial-operators#st_boundingdiagonal) | Geospatial Spatial Operators | Returns the diagonal LINESTRING from the minimum point to the maximum point of the bounding box that ST\_ENVELOPE returns. |
| [ST\_BUFFER](/spatial-operators#st_buffer) | Geospatial Spatial Operators | Returns a geography that contains all points where the distance from the geography is less than or equal to the specified distance. |
| [ST\_CLOSESTPOINT](/spatial-operators#st_closestpoint) | Geospatial Spatial Operators | Returns the two-dimensional POINT of one specified geospatial object that is closest to a second specified geospatial object. |
| [ST\_CONVEXHULL](/spatial-operators#st_convexhull) | Geospatial Spatial Operators | The convex hull is the smallest convex geometry that encloses the input geometry. |
| [ST\_DIFFERENCEARRAY](/spatial-operators#st_differencearray) | Geospatial Spatial Operators | Returns an array containing any geospatial objects that are present in the first specified geospatial argument that are not found in the second geospatial argument. |
| [ST\_ENVELOPE](/spatial-operators#st_envelope) | Geospatial Spatial Operators | Returns a POLYGON that represents the minimum bounding box for the specified geography. |
| [ST\_EXPAND](/spatial-operators#st_expand) | Geospatial Spatial Operators | Returns the bounding box of a specified geospatial value, which is expanded by a specified length. |
| [ST\_EXTERIORRING](/spatial-operators#st_exteriorring) | Geospatial Spatial Operators | Returns a LINESTRING that represents the exterior ring of a provided POLYGON value. |
| [ST\_FLIPCOORDINATES](/spatial-operators#st_flipcoordinates) | Geospatial Spatial Operators | Returns a new geographic object with the X and Y coordinates switched using the specified argument. |
| [ST\_FORCE2D](/spatial-operators#st_force2d) | Geospatial Spatial Operators | Convert a geographic object into a two-dimensional geography. |
| [ST\_INTERIORRINGN](/spatial-operators#st_interiorringn) | Geospatial Spatial Operators | Returns a LINESTRING representing the interior ring of the specified POLYGON, which is specified by its index. (1-indexed) |
| [ST\_INTERSECTALL](/spatial-operators#st_intersectall) | Geospatial Spatial Operators | Returns the intersection of all geographies in the specified array. All geographies in the array must be the same type. |
| [ST\_INTERSECTIONARRAY](/spatial-operators#st_intersectionarray) | Geospatial Spatial Operators | Returns a geography that represents the point-set intersection of two geographies. |
| [ST\_LONGESTLINE](/spatial-operators#st_longestline) | Geospatial Spatial Operators | Returns the longest LINESTRING between two specified geospatial arguments. |
| [ST\_MAKEENVELOPE](/spatial-operators#st_makeenvelope) | Geospatial Spatial Operators | Returns a POLYGON with vertices that represent the minimum bounding box for the specified coordinates. |
| [ST\_MINIMUMBOUNDINGCIRCLE](/spatial-operators#st_minimumboundingcircle) | Geospatial Spatial Operators | Returns the smallest circle POLYGON that contains the specified geographic object. |
| [ST\_MULTIDIFFERENCEARRAY](/spatial-operators#st_multidifferencearray) | Geospatial Spatial Operators | Returns an array of geographies that represents the parts of the union of the geographies in the first array that do not intersect with the union of geographies in the second array. |
| [ST\_MULTIINTERSECTIONARRAY](/spatial-operators#st_multiintersectionarray) | Geospatial Spatial Operators | When you specify two arrays of geospatial objects, this function returns an array of any intersections. |
| [ST\_MULTISYMDIFFERENCEARRAY](/spatial-operators#st_multisymdifferencearray) | Geospatial Spatial Operators | When you specify two arrays of geospatial objects, this function returns an array of any geospatial values that do not intersect. |
| [ST\_MULTIUNIONARRAY](/spatial-operators#st_multiunionarray) | Geospatial Spatial Operators | When you specify two arrays of geospatial objects, this function returns one array that represents a union of all geographies in both arrays. |
| [ST\_NRINGS](/spatial-operators#st_nrings) | Geospatial Spatial Operators | Returns the number of rings of the specified POLYGON, including both interior and exterior rings. |
| [ST\_NUMINTERIORRING](/spatial-operators#st_numinteriorrings-or-st_numinteriorring) | Geospatial Spatial Operators | Returns the number of interior rings of the specified POLYGON. |
| [ST\_NUMINTERIORRINGS](/spatial-operators) | Geospatial Spatial Operators | Returns the number of interior rings of the specified POLYGON. |
| [ST\_POINTONSURFACE](/spatial-operators#st_pointonsurface) | Geospatial Spatial Operators | Returns a POINT guaranteed to intersect the specified geospatial object. |
| [ST\_PROJECT](/spatial-operators#st_project) | Geospatial Spatial Operators | Returns a POINT by projecting a distance and an azimuth value from the specified starting POINT value. |
| [ST\_REDUCEPRECISION](/spatial-operators#st_reduceprecision) | Geospatial Spatial Operators | Returns a new geospatial object with all POINT values rounded to the specified decimal precision. |
| [ST\_REMOVEREPEATEDPOINTS](/spatial-operators#st_removerepeatedpoints) | Geospatial Spatial Operators | Returns a new geospatial object with no repeated POINT values. |
| [ST\_REVERSE](/spatial-operators#st_reverse) | Geospatial Spatial Operators | Returns a new geospatial object with the vertexes reversed. |
| [ST\_SEGMENTIZE](/spatial-operators#st_segmentize) | Geospatial Spatial Operators | Returns a geospatial object that the function modifies to have no segment longer than the specified max\_segment\_length in meters. |
| [ST\_SHORTESTLINE](/spatial-operators#st_shortestline) | Geospatial Spatial Operators | Returns the shortest LINESTRING between two specified geospatial arguments. |
| [ST\_SIMPLIFY](/spatial-operators#st_simplify) | Geospatial Spatial Operators | Returns a simplified version of the specified geography, which is either a POINT or LINESTRING. |
| [ST\_SIMPLIFYARRAY](/spatial-operators#st_simplifyarray) | Geospatial Spatial Operators | Returns a POLYGON array that represents a simplified version of the specified geography, which is either a POINT, LINESTRING, or POLYGON. |
| [ST\_SNAPTOGRID](/spatial-operators#st_snaptogrid) | Geospatial Spatial Operators | Returns a new geography value with all POINT values rounded to the specified precisions. |
| [ST\_SYMDIFFERENCEARRAY](/spatial-operators#st_symdifferencearray) | Geospatial Spatial Operators | Returns a geographic array that contains the parts that are not common between two geographic objects, geo1 and geo2. |
| [ST\_UNIONARRAY](/spatial-operators#st_unionarray) | Geospatial Spatial Operators | Performs a union of the input geography values to produce a geographic array. |
| [ST\_CLUSTERDBSCAN](/spatial-relationships#st_clusterdbscan) | Geospatial Spatial Relationships | [Returns the cluster number for each input geography, based on a two-dimensional implementation of the density-based spatial clustering of applications with noise (DBSCAN) algorithm.](https://en.wikipedia.org/wiki/DBSCAN) |
| [ST\_CONTAINS](/spatial-relationships#st_contains) | Geospatial Spatial Relationships | Returns TRUE if the first geographic argument, geo1, contains the second geographic argument, geo2. |
| [ST\_CONTAINSPROPERLY](/spatial-relationships#st_containsproperly) | Geospatial Spatial Relationships | Returns true if geo2 lies entirely in the interior of geo1 and does not intersect or touch the boundary or exterior points. |
| [ST\_COVEREDBY](/spatial-relationships#st_coveredby) | Geospatial Spatial Relationships | Returns TRUE if no POINT in geo1 is outside of geo2. |
| [ST\_COVERS](/spatial-relationships#st_covers) | Geospatial Spatial Relationships | Returns TRUE if no POINT in geo2 is outside of geo1. |
| [ST\_CROSSES](/spatial-relationships#st_crosses) | Geospatial Spatial Relationships | Returns TRUE if two geospatial objects meet these criteria: The intersection of the geospatial interiors is not empty. The intersection is not equal to geo1 or geo2. Neither geospatial object is a single POINT. |
| [ST\_DISJOINT](/spatial-relationships#st_disjoint) | Geospatial Spatial Relationships | Returns true if the specified geographies have no intersection, including boundaries. Both geographic arguments can be different types. |
| [ST\_DWITHIN](/spatial-relationships#st_dwithin) | Geospatial Spatial Relationships | Returns TRUE if the geographies are within a specified distance in meters. |
| [ST\_EQUALS](/spatial-relationships#st_equals) | Geospatial Spatial Relationships | Returns TRUE if both geographies are spatially equal. |
| [ST\_INTERSECTS](/spatial-relationships#st_intersects) | Geospatial Spatial Relationships | Returns TRUE if the specified geographies have intersection, including boundaries. |
| [ST\_ISCCW](/spatial-relationships#st_isccw) | Geospatial Spatial Relationships | Alias for ST\_ISPOLYGONCCW. |
| [ST\_ISCLOSED](/spatial-relationships#st_isclosed) | Geospatial Spatial Relationships | Returns TRUE if an input POLYGON has an exterior that is counter-clockwise. |
| [ST\_ISPOLYGONCCW](/spatial-relationships#st_ispolygonccw) | Geospatial Spatial Relationships | Returns TRUE if an input LINESTRING has starting and ending points that are equal. |
| [ST\_ISPOLYGONCW](/spatial-relationships#st_ispolygoncw) | Geospatial Spatial Relationships | Returns TRUE if an input POLYGON has an exterior that is clockwise. |
| [ST\_ISRING](/spatial-relationships#st_isring) | Geospatial Spatial Relationships | Returns TRUE if the specified LINESTRING is closed and does not intersect itself. |
| [ST\_ISSIMPLE](/spatial-relationships#st_issimple) | Geospatial Spatial Relationships | For LINESTRING values, this function returns FALSE if any line segments intersect anywhere besides the endpoints. For POLYGON values, the function returns FALSE if either the exterior ring or any interior hole is not simple. |
| [ST\_ISVALID](/spatial-relationships#st_isvalid) | Geospatial Spatial Relationships | [Returns TRUE if the specified geospatial value is a well-formed and valid geography according to the OGC standards.](https://www.ogc.org/standard/sfa/) |
| [ST\_OVERLAPS](/spatial-relationships#st_overlaps) | Geospatial Spatial Relationships | Returns TRUE if both geographic arguments are of the same dimension and they intersect each other, but neither contains the other. |
| [ST\_POINTINSIDECIRCLE](/spatial-relationships#st_pointinsidecircle) | Geospatial Spatial Relationships | Returns TRUE if the geographic object is inside a circle that is centered at the specified point coordinates and with the specified radius. |
| [ST\_RELATE](/spatial-relationships#st_relate) | Geospatial Spatial Relationships | Returns the [DE-9IM](https://postgis.net/workshops/postgis-intro/de9im.html) intersection string that represents the nature of the intersection with the specified geographies. |
| [ST\_TOUCHES](/spatial-relationships#st_touches) | Geospatial Spatial Relationships | Returns TRUE if the only POINT values in common between the two geographic arguments lie in the union of their boundaries. |
| [ST\_WITHIN](/spatial-relationships#st_within) | Geospatial Spatial Relationships | Alias for ST\_CONTAINS. |
| [ST\_DISTANCE](/spatiotemporal-measurement#st_distance) | Geospatial Spatiotemporal Measurement | Returns the two-dimensional interpolated minimum simultaneous distance between two LINESTRING-TIMESTAMP array pairs in the specified unit of measurement. |
| [ST\_MAXDISTANCE](/spatiotemporal-measurement#st_maxdistance) | Geospatial Spatiotemporal Measurement | Returns the two-dimensional interpolated maximum cotemporal distance between two LINESTRING-TIMESTAMP array pairs in the specified unit of measurement. |
| [ST\_TOTALSECONDSININTERSECTION](/spatiotemporal-measurement#st_totalsecondsinintersection) | Geospatial Spatiotemporal Measurement | Returns the total number of seconds spent in the intersection result calculated by the spatiotemporal version of ST\_INTERSECTION. |
| [ST\_INTERSECTION](/spatiotemporal-operators#st_intersection) | Geospatial Spatiotemporal Operators | Returns a tuple that represents the intersection of a spatiotemporal LINESTRING with a static geography. |
| [ST\_LINEGETALLTIMESATPOINT](/spatiotemporal-operators#st_linegetalltimesatpoint) | Geospatial Spatiotemporal Operators | Returns a timestamp array of all times when the specified LINESTRING value intersects the specified POINT value. |
| [ST\_LINEGETPOINTATTIME](/spatiotemporal-operators#st_linegetpointattime) | Geospatial Spatiotemporal Operators | Returns a POINT within the bounds of the specified LINESTRING that corresponds to the interpolated point at the specified TIMESTAMP value. |
| [ST\_LINEGETTIMEATPOINT](/spatiotemporal-operators#st_linegettimeatpoint) | Geospatial Spatiotemporal Operators | Returns the interpolated time of the specified POINT on the specified LINESTRING that is paired with a TIMESTAMP ARRAY. |
| [ST\_LONGESTLINE](/spatiotemporal-operators#st_longestline) | Geospatial Spatiotemporal Operators | With the specified two LINESTRING-TIMESTAMP ARRAY pairs, this function returns a two-point LINESTRING that represents the maximum distance between points at a concurrent time. |
| [ST\_SHORTESTLINE](/spatiotemporal-operators#st_shortestline) | Geospatial Spatiotemporal Operators | When you specify two LINESTRING-TIMESTAMP ARRAY pairs, this function returns a LINESTRING with two points that represents the minimum distance between points at a concurrent time. |
| [HLL\_SKETCH\_CREATE](/hyperloglog-functions#hll_sketch_create) | HyperLogLog Functions | Creates an HLL sketch from the data on a specified aggregated column. Returns a HASH((2^log2k) + 8) data representation of the sketch that you can store in a separate column. |
| [HLL\_SKETCH\_GET\_ESTIMATE](/hyperloglog-functions#hll_sketch_get_estimate) | HyperLogLog Functions | The scalar function converts a sketch into a distinct count estimate of a sketch value. Returns the distinct count estimate as a BIGINT. |
| [HLL\_SKETCH\_GET\_ESTIMATE\_BOUND](/hyperloglog-functions#hll_sketch_get_estimate_bound) | HyperLogLog Functions | Takes a HLL\_SKETCH column or an integral log2k literal value and returns the resulting bounding 95-percent confidence interval error proportion as a DOUBLE. |
| [HLL\_SKETCH\_TO\_STRING](/hyperloglog-functions#hll_sketch_to_string) | HyperLogLog Functions | The HLL\_SKETCH\_TO\_STRING scalar function takes a HLL\_SKETCH column or value and returns a string summary of the sketch. |
| [HLL\_SKETCH\_UNION (aggregate function)](/hyperloglog-functions#hll_sketch_union-aggregate-function) | HyperLogLog Functions | Merges multiple sketches in a single column into a unified sketch. All sketches must have the same precision. This function is an aggregate function and operates on a column. |
| [HLL\_SKETCH\_UNION (scalar function)](/hyperloglog-functions#hll_sketch_union-scalar-function) | HyperLogLog Functions | Merges two sketches into a new combined sketch. This function is a scalar function and operates row-wise. The scalar function merges two sketch columns with heterogeneous precisions into a sketch with the lower of the two precisions. |
| [ABS](/math-functions-and-operators#abs) | Math Functions | Returns the absolute value of a specified floating-point number. |
| [ACOS](/math-functions-and-operators#acos) | Math Functions | Returns the inverse cosine of a specified floating-point number. |
| [ACOSH](/math-functions-and-operators#acosh) | Math Functions | Returns the hyperbolic arc-cosine of a specified floating-point number. |
| [ASIN](/math-functions-and-operators#asin) | Math Functions | Returns the inverse sine of a specified floating-point number. |
| [ASINH](/math-functions-and-operators#asinh) | Math Functions | Returns the hyperbolic arc-sine of a specified floating-point number. |
| [ATAN](/math-functions-and-operators#atan) | Math Functions | Returns the inverse tangent of a specified floating-point number. |
| [ATAN2](/math-functions-and-operators#atan2) | Math Functions | Returns the inverse tangent of two numeric, floating-point values. |
| [ATANH](/math-functions-and-operators#atanh) | Math Functions | Returns the hyperbolic arc-tangent of a specified floating-point number. |
| [BICDF](/math-functions-and-operators#bicdf) | Math Functions | The cumulative distribution function of the standard bivariate normal distribution. |
| [BIPDF](/math-functions-and-operators#bipdf) | Math Functions | The probability density function of the standard bivariate normal distribution. |
| [BITAND](/math-functions-and-operators#bitand) | Math Functions | Alias for the BITFUNC syntax `BITFUNC('AND', x, y)`. |
| [BITFUNC](/math-functions-and-operators#bitfunc) | Math Functions | Performs a variety of bit operations. Can be any of these string literals: `'AND'`, `'OR'`, or `'XOR'`. |
| [BITNOT](/math-functions-and-operators#bitnot) | Math Functions | Returns the bitwise negation of integral\_x. |
| [BITOR](/math-functions-and-operators#bitor) | Math Functions | Alias for the BITFUNC syntax BITFUNC('OR', x, y). |
| [BITXOR](/math-functions-and-operators#bitxor) | Math Functions | Alias for the BITFUNC syntax BITFUNC('XOR', x, y). |
| [BOOLAND](/math-functions-and-operators#booland) | Math Functions | Alias for the BOOLFUNC syntax BOOLFUNC('AND', x, y). |
| [BOOLFUNC](/math-functions-and-operators#boolfunc) | Math Functions | Performs a Boolean logical evaluation on arguments x and y. Can be any of these string literals: `'AND'`, `'OR'`, or `'XOR'`. |
| [BOOLNOT](/math-functions-and-operators#boolnot) | Math Functions | Returns the logical negation of the BOOLFUNC function. |
| [BOOLOR](/math-functions-and-operators#boolor) | Math Functions | Alias for the BOOLFUNC syntax BOOLFUNC('OR', x, y). |
| [BOOLXOR](/math-functions-and-operators#boolxor) | Math Functions | Alias for the BOOLFUNC syntax BOOLFUNC('XOR', x, y). |
| [CBRT](/math-functions-and-operators#cbrt) | Math Functions | Returns the cube root of the numeric value x. |
| [CDF](/math-functions-and-operators#cdf) | Math Functions | The cumulative distribution function of the standard normal distribution. Returns the probability that a random sample is less than or equal to the specified value. |
| [CEIL](/math-functions-and-operators#ceil) | Math Functions | Returns the nearest integer greater than or equal to x. |
| [CEILING](/math-functions-and-operators#ceiling) | Math Functions | Alias for CEIL. |
| [COS](/math-functions-and-operators#cos) | Math Functions | Returns the cosine of x. |
| [COSH](/math-functions-and-operators#cosh) | Math Functions | Returns the hyperbolic cosine of x. |
| [COT](/math-functions-and-operators#cot) | Math Functions | Returns the cotangent of x. |
| [DEGREES](/math-functions-and-operators#degrees) | Math Functions | Returns the corresponding angle in degrees for x in radians. |
| [DIV](/math-functions-and-operators#div) | Math Functions | Returns the result of x divided by y. If y is zero, returns NULL. |
| [ERF](/math-functions-and-operators#erf) | Math Functions | The error function is used for measurements that follow a normal distribution. |
| [ERFC](/math-functions-and-operators#erfc) | Math Functions | The complement of the error function. ERFC(x) = 1 - ERF(x). |
| [EXP](/math-functions-and-operators#exp) | Math Functions | Returns the exponential of x (e raised to the power of x). |
| [FLOOR](/math-functions-and-operators#floor) | Math Functions | Returns the nearest integer less than or equal to x. |
| [GAMMA](/math-functions-and-operators#gamma) | Math Functions | [Gamma function.](https://en.wikipedia.org/wiki/Gamma_function) |
| [HEXBINX](/math-functions-and-operators#hexbinx) | Math Functions | Returns the x-coordinate of the center of the nearest hexagonal bin to the point (x, y). |
| [HEXBINY](/math-functions-and-operators#hexbiny) | Math Functions | Returns the y-coordinate of the center of the nearest hexagonal bin to the point (x, y). |
| [IERF](/math-functions-and-operators#ierf) | Math Functions | The inverse of the ERF error function. |
| [IERFC](/math-functions-and-operators#ierfc) | Math Functions | The inverse of the complement of the error function. |
| [LEAKYRELU](/math-functions-and-operators#leakyrelu) | Math Functions | Returns the leaky rectified linear unit function of x. |
| [LEFT\_SHIFT](/math-functions-and-operators#left_shift) | Math Functions | Returns x shifted to the left by y bits. |
| [LN](/math-functions-and-operators#ln) | Math Functions | Returns the natural logarithm of x. |
| [LOG](/math-functions-and-operators#log) | Math Functions | Returns the base 10 logarithm of x. The optional base argument specifies the numeral system to use. If unspecified, the function defaults to base 10. |
| [LOG\_GAMMA](/math-functions-and-operators#log_gamma) | Math Functions | The natural logarithm of the absolute value of the gamma function. |
| [LOG2](/math-functions-and-operators#log2) | Math Functions | Returns the base 2 logarithm of x. |
| [MOD](/math-functions-and-operators#mod) | Math Functions | Returns the remainder from x divided by y. |
| [PI](/math-functions-and-operators#pi) | Math Functions | Returns the constant value of π. |
| [PMOD](/math-functions-and-operators#pmod) | Math Functions | Returns the smallest non-negative equivalence class of x % y. |
| [POWER](/math-functions-and-operators#power) | Math Functions | Returns x raised to the power of y. |
| [PROBIT](/math-functions-and-operators#probit) | Math Functions | The inverse of the cumulative distribution function. |
| [RADIANS](/math-functions-and-operators#radians) | Math Functions | Returns the corresponding angle in radians for x in degrees. |
| [RAND](/math-functions-and-operators#rand) | Math Functions | Takes no argument and returns a random DOUBLE value in the range \[0, 1). |
| [RELU](/math-functions-and-operators#relu) | Math Functions | Returns the rectified linear unit function of x. |
| [RIGHT\_SHIFT](/math-functions-and-operators#right_shift) | Math Functions | Returns x shifted to the right by y bits. |
| [ROUND](/math-functions-and-operators#round) | Math Functions | Returns x rounded to the nearest integer. |
| [SIGN](/math-functions-and-operators#sign) | Math Functions | Returns the positive (+1), zero (0), or negative (-1) sign of x. |
| [SIN](/math-functions-and-operators#sin) | Math Functions | Returns the sine of x. |
| [SINH](/math-functions-and-operators#sinh) | Math Functions | Returns the hyperbolic sine of x. |
| [SQRT](/math-functions-and-operators#sqrt) | Math Functions | Returns the square root of x. |
| [SQUARE](/math-functions-and-operators#square) | Math Functions | Returns the square of x. |
| [TAN](/math-functions-and-operators#tan) | Math Functions | Returns the tangent of x. |
| [TANH](/math-functions-and-operators#tanh) | Math Functions | Returns the hyperbolic tangent of x. |
| [TO\_BASE](/math-functions-and-operators#to_base) | Math Functions | Converts an integer value to its string representation in a specified base (radix). |
| [TRUNC](/math-functions-and-operators#trunc) | Math Functions | Returns x truncated to y decimal places. |
| [TRUNCATE](/math-functions-and-operators#truncate) | Math Functions | Alias for TRUNC. |
| [ABS](/matrix-functions-and-operators#matrix-functions) | Matrix Functions | Returns magnitude of one-dimensional matrix or vector. |
| [CROSS\_ENTROPY\_LOSS](/matrix-functions-and-operators) | Matrix Functions | Returns the cross entropy loss of two one-dimensional matrices or vectors. |
| [DET](/matrix-functions-and-operators) | Matrix Functions | Returns the determinant of the matrix as a double. |
| [DOT](/matrix-functions-and-operators) | Matrix Functions | Returns dot product of two one-dimensional matrices/vectors. |
| [EIGEN](/matrix-functions-and-operators) | Matrix Functions | Returns eigenvalues and eigenvalues of a square matrix as a vector of pairs. |
| [FROBENIUS](/matrix-functions-and-operators) | Matrix Functions | Returns the Frobenius norm of a matrix. |
| [HINGE\_LOSS](/matrix-functions-and-operators) | Matrix Functions | Returns the hinge loss of two one-dimensional matrices or vectors. |
| [IDENTITY\_MATRIX](/matrix-functions-and-operators) | Matrix Functions | Returns an identity matrix of the specified dimension. |
| [INVERSE](/matrix-functions-and-operators) | Matrix Functions | Returns inverse of a square, invertible matrix. |
| [LOG\_LOSS](/matrix-functions-and-operators) | Matrix Functions | Returns the log loss of two one-dimensional matrices or vectors. |
| [LOGITS\_LOSS](/matrix-functions-and-operators) | Matrix Functions | Returns the logits loss of two one-dimensional matrices or vectors. |
| [LUPQ\_DECOMP](/matrix-functions-and-operators) | Matrix Functions | Returns LUPQ decomposition of a square matrix A as a tuple of 4 matrices where PAQ = LU. |
| [MATRIX\_DIM](/matrix-functions-and-operators) | Matrix Functions | Returns the dimensions of the specified matrix as a tuple of (row, col) integers. |
| [MAKE\_MATRIX\_IXJ](/matrix-functions-and-operators) | Matrix Functions | Creates an `ixj` matrix with elements `e_00`, `…`, `e_ij`. |
| [MATRIX\_FROM\_TEXT](/matrix-functions-and-operators) | Matrix Functions | Creates a matrix from the specified string. |
| [MATRIX\_TRACE](/matrix-functions-and-operators) | Matrix Functions | Returns trace of a square matrix as a double. |
| [NULL\_MATRIX](/matrix-functions-and-operators) | Matrix Functions | Returns a NULL matrix of the specified (row, col) dimensions. |
| [QR\_DECOMP](/matrix-functions-and-operators) | Matrix Functions | Returns QR decomposition of a matrix as a tuple of 2 matrices. |
| [SOFTMAX](/matrix-functions-and-operators) | Matrix Functions | Returns the softmax of a one-dimensional matrix or vector. |
| [SVD\_DECOMP](/matrix-functions-and-operators) | Matrix Functions | Returns SVD decomposition of a matrix as a tuple of 3 matrices. |
| [TRANSPOSE](/matrix-functions-and-operators) | Matrix Functions | Returns transpose of the matrix. |
| [VECTOR\_ARGMAX](/matrix-functions-and-operators) | Matrix Functions | Returns the argmax of a one-dimensional matrix or vector. |
| [VECTOR\_ARGMIN](/matrix-functions-and-operators) | Matrix Functions | Returns the argmin of a one-dimensional matrix or vector. |
| [VECTOR\_MAX](/matrix-functions-and-operators) | Matrix Functions | Returns the maximum of elements in a one-dimensional matrix/vector. |
| [VECTOR\_MIN](/matrix-functions-and-operators) | Matrix Functions | Returns the minimum of elements in a one-dimensional matrix/vector. |
| [VECTOR\_SUM](/matrix-functions-and-operators) | Matrix Functions | Returns the sum of elements in a one-dimensional matrix/vector. |
| [ZERO\_MATRIX](/matrix-functions-and-operators) | Matrix Functions | Returns a zero matrix of the given (row, col) dimensions. |
| [IP](/network-type-functions#ip) | Network Type Functions | Casts an IP data type from an IPV4 data type expression. |
| [IPV4](/network-type-functions#ipv4) | Network Type Functions | Casts an IPV4 address from an IPV6 address. |
| [IS\_IPV4](/network-type-functions#is_ipv4) | Network Type Functions | Tests whether the database can convert the `IP` value to the `IPV4` data type. |
| [SUBNET](/network-type-functions#subnet) | Network Type Functions | Computes the prefix from an `IP` or `IPV4` value and the size of the prefix. |
| [CANCEL](/query-management#cancel) | Query Management | Cancels a running query based on its specific query identifier. |
| [KILL](/query-management#kill) | Query Management | Kills a running query identified by its UUID. |
| [BIGINT](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type `bigint`. |
| [BINARY](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses a hexadecimal string (such as 0x54ab) to create a binary value. Letters can be of either case. |
| [BOOLEAN](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses a string to create a Boolean value. The string must contain either true or false. It is case-insensitive. |
| [BYTE](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type byte. |
| [CHAR](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Creates a string version of the numeric value. |
| [DATE](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses a string in the form 'YYYY-MM-DD' to create a date. Extra characters are ignored. |
| [DAYS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type days to be used in date calculations. |
| [DECIMAL](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type decimal. |
| [DOUBLE](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type double. |
| [FLOAT](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type float. |
| [HASH](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Creates a fixed length binary value, with length ``, from a string, i.e. `0x1234abcd`. Zero extended if the string does not have enough bytes, truncated if it has too many. |
| [HOURS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type hours. |
| [INTEGER](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type integer. |
| [MICROSECONDS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type microseconds. |
| [MILLISECONDS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type milliseconds. |
| [MINUTES](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type minutes. |
| [MONTHS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type months to be used in date calculations. |
| [NANOSECONDS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type nanoseconds. |
| [SECONDS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type seconds. |
| [SMALLINT](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Casts the argument to a value of type `smallint`. |
| [TIME](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses the string to create a time value. The string must be in the form `'HH:MM[.SSSSSSSSS]'`. |
| [TIMESTAMP](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses a string and makes a timestamp value. The string must be in the format `'YYYY-MM-DD[ HH:MM][.SSSSSSSSS]'`. |
| [UUID](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Parses the string and makes a UUID value. The string must be a valid UUID. |
| [WEEKS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type weeks to be used in date calculations. |
| [YEARS](/scalar-data-conversion-functions) | Scalar Data Conversion Functions | Converts an integral value to an interval value of type years. |
| [ARRAY\_CAP](/transform-data-in-data-pipelines#array-data-transformation-functions) | Special Data Pipeline Transformation Functions | Restrict the length of an array to a maximum number of elements. |
| [ARRAY\_COMPACT](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Removes NULL values from the array. |
| [ARRAY\_CONTAINS](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Returns `true` if the array contains the specified value. |
| [ARRAY\_SORT](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Sort and return the input array based on the natural ordering of its elements or the specified Lambda function. |
| [CASE WHEN](/transform-data-in-data-pipelines#special-data-pipeline-transformation-functions) | Special Data Pipeline Transformation Functions | Returns the `result` value based on whether an expression is `true`. |
| [ELEMENT\_AT](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Returns the element value of the array or tuple at the specified index. |
| [EXPLODE\_OUTER](/special-data-pipeline-transformation-functions#explode_outer) | Special Data Pipeline Transformation Functions | Expands a one-dimensional or multidimensional array into its elements with one element per row of output from the system. |
| [FILTER](/special-data-pipeline-transformation-functions#filter) | Special Data Pipeline Transformation Functions | Filters elements in an array based on the logic in a lambda expression. |
| [FLATTEN](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Transforms an `N`-dimensional array into an `N-1`-dimensional array. |
| [IF](/transform-data-in-data-pipelines#logical-operations-transformation-functions) | Special Data Pipeline Transformation Functions | Returns `T` if the expression `X` evaluates to `true`, or the function returns `F` if `X` evaluates to `false`. |
| [LOOKUP](/load-data-from-external-sources-in-data-pipelines) | Special Data Pipeline Transformation Functions | Look up and load data in an external data source. |
| [MAP\_KEYS](/transform-data-in-data-pipelines#other-data-transformation-functions) | Special Data Pipeline Transformation Functions | Returns the keys in the specified JSON string. |
| [MAP\_VALUES](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Returns the values in the specified JSON string. |
| [METADATA](/load-metadata-and-file-based-partitioned-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Extracts the metadata value for the specified key from available metadata for the pipeline. |
| [PARSE\_DELIMITED\_ARRAY](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Converts a string of text data representing an array into a `CHAR[]`. |
| [REDUCE](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Applies a merge function to a starting value and all elements in the array, and then reduces the array to a single value. Optionally, specify a finish function for the returned single value. |
| [TO\_ARRAY\_LENGTH](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Create the specified number of copies of any JSON object in an array. |
| [TRANSFORM](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Transforms an array based on the logic in a lambda expression. |
| [WIDTH\_BUCKET](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Creates `N` equal-width buckets in the range `[min,max)` as a histogram. |
| [ZIP\_WITH](/transform-data-in-data-pipelines) | Special Data Pipeline Transformation Functions | Merges two or more input arrays, element-wise, into a single array using the trailing combining function. |
| [RECORD\_UUID](/lat-transformation-functions#record_uuid) | Other Transformation Functions | Returns string that represents a unique identifier for the record in a specified pipeline for a specified file\_group or topic. |
| [COMMIT](/other-functions-and-expressions#commit) | Other Functions and Expressions | Returns the most recent commit hash of the database to which the client is currently connected. |
| [RAND\_UUID](/other-functions-and-expressions#rand_uuid) | Other Functions and Expressions | Generates a random UUID value (version 4). |
| [TYPE\_STRIP](/other-functions-and-expressions#type_strip) | Other Functions and Expressions | Returns the SQL type of the specified value. |
| [UUID\_GENERATE](/other-functions-and-expressions#uuid_generate) | Other Functions and Expressions | Generates a random UUID value (version 4). |
| [CURRENT\_DATABASE](/other-functions-and-expressions#current_database) | System Functions | Alias for DATABASE. |
| [CURRENT\_GROUPS](/other-functions-and-expressions#current_groups) | System Functions | Returns the fully-qualified names of groups in the database. |
| [CURRENT\_NODE](/other-functions-and-expressions#current_node) | System Functions | Returns the name of the SQL Node where the current query executes. The name of the node corresponds to the name column in the `sys.nodes` system catalog table. |
| [CURRENT\_NODE\_ID](/other-functions-and-expressions#current_node_id) | System Functions | Returns the identifier of the SQL Node where the current query executes. |
| [CURRENT\_SCHEMA](/other-functions-and-expressions#current_schema) | System Functions | Returns the name of the current schema. |
| [CURRENT\_SESSION\_ID](/other-functions-and-expressions#current_session_id) | System Functions | Returns the Universally Unique IDentifier (UUID) of the current session. |
| [CURRENT\_SYSTEM](/other-functions-and-expressions#current_system) | System Functions | Returns the name of the system. |
| [CURRENT\_USER](/other-functions-and-expressions#current_user) | System Functions | Returns the user for the current connection. |
| [DATABASE](/other-functions-and-expressions#database) | System Functions | Returns the name of the database to which the client is currently connected. |
| [SHOW](/other-functions-and-expressions#show) | System Functions | The SHOW function enables you to explore the database and its metadata for user-defined items. |
| [VERSION](/other-functions-and-expressions#version) | System Functions | Returns the version of the database to which the client is currently connected. |
| [CONVERT\_LOCAL\_TIMESTAMP\_TO\_UTC](/time-zone-functions#convert_local_timestamp_to_utc) | Time Zone Functions | The function converts a timestamp in a specified local time zone to the UTC time zone. |
| [CONVERT\_UTC\_TIMESTAMP\_TO\_LOCAL](/time-zone-functions#convert_utc_timestamp_to_local) | Time Zone Functions | The function converts a timestamp from the UTC time zone to a specified local time zone. |
| [CAST\_TO\_TUPLE](/tuple-functions-and-operators) | Tuple Functions | Converts a tuple into another tuple of a different type. |
| [CHAR](/tuple-functions-and-operators) | Tuple Functions | Converts a tuple to its string representation. |
| [STRING\_TO\_TUPLE](/tuple-functions-and-operators) | Tuple Functions | Converts the string representation of a tuple (e.g 'tuple\<\>(1,2,NULL)') into a tuple. |
| [TUPLE()](/tuple-functions-and-operators) | Tuple Functions | Construct a tuple of specified elements. Types of the tuple are inferred from the inner elements. |
| [TUPLE\<\<>>](/tuple-functions-and-operators) | Tuple Functions | Construct a tuple of specified elements. NULL is also supported as an element. |
| [CUME\_DIST](/window-aggregate-functions#cume_dist) | Window Aggregate Functions | Returns a number 0 \< n 1 and can be used to calculate the percentage of values less than or equal to the current value in the group. |
| [DELTA](/window-aggregate-functions#delta) | Window Aggregate Functions | Computes the finite difference between successive values of expression under the specified ordering. This is a backwards difference, which means that, at degree one, the value for a given row is the difference between the value of expression for that row and the previous row. |
| [DENSE\_RANK](/window-aggregate-functions#dense_rank) | Window Aggregate Functions | Assigns a number to each row in the result set with equal values having the same number. There will be no gaps between ranks. |
| [DERIVATIVE](/window-aggregate-functions#derivative) | Window Aggregate Functions | Computes the difference quotient between successive values of expression with respect to expression2. |
| [FIRST\_VALUE](/window-aggregate-functions#first_value) | Window Aggregate Functions | Returns the first value in the ordered result set. |
| [LAG](/window-aggregate-functions#lag) | Window Aggregate Functions | Returns the row, which is the specified number backward from the current row. Default is 1 if offset is omitted. |
| [LAST\_VALUE](/window-aggregate-functions#last_value) | Window Aggregate Functions | Returns the last value in the ordered result set. |
| [LEAD](/window-aggregate-functions#lead) | Window Aggregate Functions | Returns the row, which is the specified number forward from the current row. Default is 1 if offset is omitted. |
| [NTH\_VALUE](/window-aggregate-functions#nth_value) | Window Aggregate Functions | Returns the nth value in the ordered result set. |
| [PERCENT\_RANK](/window-aggregate-functions#percent_rank) | Window Aggregate Functions | The value returned is 0 \< n ≤ 1 and can be used to calculate the percentage of values less than the current group, excluding the highest value. |
| [PERCENTILE](/window-aggregate-functions#percentile) | Window Aggregate Functions | Returns the value that corresponds to the specified percentile (0 ≤ n ≤ 1) within the group. |
| [RANK](/window-aggregate-functions#rank) | Window Aggregate Functions | Assigns a number to each row in the result set with equal values having the same number. There can be gaps between ranks. |
| [RATIO\_TO\_REPORT](/window-aggregate-functions#ratio_to_report) | Window Aggregate Functions | Computes the ratio of a value to the sum of the set of values. |
| [ROW\_NUMBER](/window-aggregate-functions#row_number) | Window Aggregate Functions | Assigns a unique number to each row in the result set. |
| [ZSCORE](/window-aggregate-functions#zscore) | Window Aggregate Functions | Zscore of the sample based on the `stddev()` function. |
| [ZSCOREP](/window-aggregate-functions#zscorep) | Window Aggregate Functions | Zscore of the sample based on the `stddevp()` function. |
# Character and Binary Functions
Source: https://docs.ocient.com/character-and-binary-functions
Reference for Ocient SQL character and binary functions for string manipulation, encoding, decoding, padding, regular expressions, and byte-level operations.
All string functions support Unicode characters. Functions that transform character case are locale-sensitive.
These functions support the UTF-8 format:
* RTRIM
* LTRIM
* LEFT
* RIGHT
* TRIM
* TRANSLATE
* RPAD
* LPAD
* SUBSTRING
Index position values for character and string functions begin at position `1`. For example, the `"H"` in the string `"Hello"` is at position `1`.
### ASCII
Returns the ASCII code value of the leftmost character of the character value.
The ASCII function only supports ASCII characters in the input argument.
**Syntax**
```sql SQL theme={null}
ASCII(char)
```
**Example**
```sql SQL theme={null}
SELECT ASCII('a');
```
\*Output: \*`97`
**Example**
```sql SQL theme={null}
SELECT ASCII('bc');
```
\*Output: \*`98`
### BIT\_LENGTH
Returns the length of the character value in bits.
**Syntax**
```sql SQL theme={null}
BIT_LENGTH(char)
```
**Example**
```sql SQL theme={null}
SELECT BIT_LENGTH('a');
```
\*Output: \*`8`
**Example**
```sql SQL theme={null}
SELECT BIT_LENGTH('ab');
```
\*Output: \*`16`
**Example**
```sql SQL theme={null}
SELECT BIT_LENGTH('ab4');
```
\*Output: \*`24`
### BTRIM
Alias for [TRIM](#trim).
### CHR
Converts an integer value to a string.
The value is first sign-extended to 8 bytes. Then, if it can be represented as 1 byte, a string is returned with that one byte.
Otherwise, a string is returned of length 2 bytes, 4 bytes, or 8 bytes with the bytes set to the big-endian representation of the integer, depending on how many high order zero bytes there are in the integer.
**Syntax**
```sql SQL theme={null}
CHR(integer)
```
**Example**
```sql SQL theme={null}
SELECT CHR(97);
```
\*Output: \*`a`
### CHAR\_LENGTH
Alias for [LENGTH](#length).
### CHARACTER\_LENGTH
Alias for [LENGTH](#length).
### CONCAT
Concatenates two or more values, all of which must be binary, hash, or string data types.
For strings, as long as one argument is a character value, the other arguments are implicitly cast to a character value.
**Syntax**
```sql SQL theme={null}
CONCAT(value1, value2 [, ...])
```
| **Arguments** | **Data** **Type** | **Description** |
| ------------------------ | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `value1, value2 [, ...]` | `BINARY`, `HASH`, or `CHAR` | Two or more values to concatenate. If any argument is a character value, the others are also cast to a character value. |
**Example**
```sql SQL theme={null}
SELECT CONCAT('ocient',' ','data', ' ', 'warehouse');
```
\*Output: \*`ocient data warehouse`
**Example**
```sql SQL theme={null}
SELECT 'ocient'||' data warehouse';
```
\*Output: \*`ocient data warehouse`
### ENDSWITH
Returns `true` if `x` ends with `y` and `false` otherwise.
**Syntax**
```sql SQL theme={null}
ENDSWITH(char1, char2)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | --------------------------------------------------------------------- |
| `char1` | `CHAR` | A string to evaluate for whether it ends with `char2`. |
| `char2` | `CHAR` | A string to evaluate for whether `char1` ends with it as a substring. |
**Example**
```sql SQL theme={null}
SELECT ENDSWITH('ocient data warehouse','warehouse');
```
\*Output: \*`true`
**Example**
```sql SQL theme={null}
SELECT ENDSWITH('ocient data warehouse','db');
```
\*Output: \*`false`
**Example**
```sql SQL theme={null}
SELECT ENDSWITH('tamaño','o');
```
\*Output: \*`true`
### INITCAP
For each word in the specified string, capitalize the first character if it is alphabetic. The system defines words as alphanumeric strings separated by non-alphanumeric characters. The system converts all other alphabetic characters to lowercase.
**Syntaxes**
```sql SQL theme={null}
INITCAP(char_string)
INITCAP(char_string, delimiter)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `char_string` | `CHAR` | A string to evaluate for initial capitalization. |
| `delimiter` | `CHAR` | Optional. One or more non-alphanumeric characters that specify the delimiter between words. The characters include all the ASCII printable non-alphanumeric characters except backquotes `` ` `` and equals `=`. Non-ASCII characters are not included. ℹ️If you specify alphabetic characters for the delimiter, the function converts them to lowercase. **Example** `sql SQL SELECT INITCAP('ocient'); ` \*Output: \*`Ocient` |
### INSTR
Returns the index position of the first occurrence where the character value `char_substring` appears in the character value `char` by ignoring the case.
**Syntax**
```sql SQL theme={null}
INSTR(char, char_substring)
```
| **Argument** | **Data** **Type** | **Description** |
| ---------------- | ----------------- | --------------------------------------------------------------------------------- |
| `char` | `CHAR` | A string to evaluate for the first index position where `char_substring` appears. |
| `char_substring` | `CHAR` | A string to evaluate for where it first appears in `char`. |
**Example**
```sql SQL theme={null}
SELECT INSTR('ocient dw dw', 'ocient');
```
\*Output: \*`1`
```sql SQL theme={null}
SELECT INSTR('ocient dw dw', 'dw');
```
\*Output: \*`8`
### JSON\_EXTRACT\_PATH\_TEXT
Returns the value for the key-value pair referenced by a series of path elements in a JSON string.
**Syntax**
```sql SQL theme={null}
JSON_EXTRACT_PATH_TEXT (
json_string, path [, path2 [, ...] ] [, null_if_invalid ] )
```
| **Argument** | **Data** **Type** | **Description** |
| ------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `json_string` | `CHAR` | A JSON string. |
| `path [, path2 [, ...] ]` | `CHAR` | One or more path elements in a JSON string. You must include at least one path element up to a maximum of five, meaning the function can extract from paths nested up to five levels deep in the JSON string. Path elements are case-sensitive. If a specified path element does not exist in the JSON string, the function returns `NULL`. |
| `null_if_invalid` | `BOOLEAN` | Optional. If you set this value to `TRUE`, the function returns `NULL` if the JSON string is invalid. If you set this value to `FALSE`, the function returns an error when the JSON string is invalid. The default value is `FALSE`. |
**Examples**
**Extract Values from Nested Paths**
This example extracts the value based on two specified paths in the JSON string, `n4` and `n6`.
```sql SQL theme={null}
SELECT JSON_EXTRACT_PATH_TEXT(
'{"n2":{"n3":1},"n4":{"n5":99,"n6":"circle"}}',
'n4', 'n6'
);
```
\*Output: \*`"circle"`
**Return NULL from Invalid JSON**
In this example, the query requests the same nested paths, but the JSON is invalid because all of the keys lack quotation marks.
The query returns `NULL` because the `null_if_invalid` argument equals `TRUE`.
```sql SQL theme={null}
SELECT JSON_EXTRACT_PATH_TEXT(
'{n2:{n3:1},n4:{n5:99,n6:"circle"}}',
'n4', 'n6',
TRUE
);
```
\*Output: \*`NULL`
### LCASE
Alias for [LOWER](#lower).
### LEFT
Return the number of characters in the string equal of the value `integer`. If `integer` is negative, the function returns all but the last `integer` characters.
**Syntax**
```sql SQL theme={null}
LEFT(char, integer)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `char` | `CHAR` | A string to be modified by returning the number of characters equal to `integer`. |
| `integer` | `INT` | The number of characters to return from the `char` string.
If `integer` is negative, the function returns all but the last `integer` characters. |
**Example**
```sql SQL theme={null}
SELECT LEFT('ocient data warehouse', 8);
```
\*Output: \*`ocient d`
**Example**
```sql SQL theme={null}
SELECT LEFT('ocient data warehouse', -3);
```
\*Output: \*`ocient data wareho`
### LENGTH
Alias for CHAR\_LENGTH and CHARACTER\_LENGTH.
Returns the length of the value. For character data types, this value is in terms of characters. For binary data types, this value is in terms of bytes.
**Syntax**
```sql SQL theme={null}
LENGTH(character_or_binary_value)
```
**Example**
```sql SQL theme={null}
SELECT LENGTH('ocient data warehouse');
```
\*Output: \*`21`
### LOCATE
Alias for POSITION.
Returns the index position of the first occurrence of the character value `substring` in the character value `string`.
Optionally, you can also include an additional value `offset` to offset the LOCATE function by the specified number of spaces.
Index positions begin at `1`.
**Syntax**
```sql SQL theme={null}
LOCATE(substring, string [, offset] )
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `substring` | `CHAR` | A substring to be found for its first position in string. |
| `string` | `CHAR` | A string to be evaluated for the first position of `substring`. |
| `offset` | `INT` | Optional. A number of index positions in `string` to offset the search for the `substring` value. This index position must be a positive integer, and it starts from the left of `string`. |
**Example**
```sql SQL theme={null}
SELECT LOCATE('ware', 'ocient data warehouse');
```
\*Output: \*`13`
**Example**
```sql SQL theme={null}
SELECT LOCATE('e', 'ocient');
```
\*Output: \*`4`
**Example**
In this example, the index starts at position 5. This means the function skips the initial `'e'` in the string. Instead, it returns the second `e` at index position 15.
```sql SQL theme={null}
SELECT LOCATE('e', 'ocient database', 5);
```
\*Output: \*`15`
### LOWER
Alias for LCASE.
Convert string to lowercase.
**Syntax**
```sql SQL theme={null}
LOWER(char)
```
**Example**
```sql SQL theme={null}
SELECT LOWER('Ocient');
```
\*Output: \*`ocient`
**Example**
```sql SQL theme={null}
SELECT LOWER('OCIENT');
```
\*Output: \*`ocient`
### LPAD
Pad the input text to the specified length with the pad string on the left side. If text is longer than length, it is truncated to `length` characters. If the argument pad is not provided, the space character is used.
**Syntax**
```sql SQL theme={null}
LPAD(string, length [, pad_character] )
```
| **Argument** | **Data** **Type** | **Description** |
| --------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | A string to be padded on its left side with additional characters, so that it equals the `length` value. |
| `length` | `INT` | The number of characters for `string` to total. If the `string` is already longer than `length`, the function truncates `string` to equal the `length` value. |
| `pad_character` | `CHAR` | Optional. A string of one or more characters to use to pad `string` to equal the `length` value. If not provided, `pad_character` uses a whitespace character to pad. |
**Example**
```sql SQL theme={null}
SELECT LPAD('ocient data warehouse',30,'ab');
```
\*Output: \*`ababababaocient data warehouse`
**Example**
```sql SQL theme={null}
SELECT LPAD('ocient data warehouse',6);
```
\*Output: \*`ocient`
### LTRIM
Removes leading blanks from the string value `string`.
Alternatively, you can specify a second string value `trim_character`. If you specify the `trim_character` value, the LTRIM function removes all leading instances of the `trim_character` value from the `string`.
**Syntax**
```sql SQL theme={null}
LTRIM(string [, trim_character] )
```
| **Argument** | **Data** **Type** | **Description** |
| ---------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | A string to be trimmed on its left side. |
| `trim_character` | `CHAR` | Optional. A string of one or more characters to be trimmed from the left side of `string`. Each character is trimmed individually, not as a cohesive substring. If you do not specify this argument, this value defaults to removing all whitespace from the left side of `string`. |
**Example**
```sql SQL theme={null}
SELECT LTRIM(' ocient');
```
\*Output: \*`ocient`
**Example**
```sql SQL theme={null}
SELECT LTRIM('aaaaaocient','a');
```
\*Output: \*`ocient`
**Example**
In this example, all characters `'abeo '` are removed from the left side of the string.
```sql SQL theme={null}
SELECT LTRIM('aaeabe ocient','abeo ');
```
\*Output: \*`cient`
### MD5
Returns the hexadecimal string (all lowercase) representing the md5 hash of `char`.
**Syntax**
```sql SQL theme={null}
MD5(char)
```
**Example**
```sql SQL theme={null}
SELECT md5('ocient');
```
\*Output: \*`438f03cf6e9ddf8793e02db25f2d2f88`
### MID
Alias for [SUBSTRING](#substring).
### OCTET\_LENGTH
Returns the length in bytes of a character or binary value.
**Syntax**
```sql SQL theme={null}
OCTET_LENGTH(value)
```
**Example**
```sql SQL theme={null}
SELECT OCTET_LENGTH('a');
```
\*Output: \*`1`
**Example**
```sql SQL theme={null}
SELECT OCTET_LENGTH('ocient');
```
\*Output: \*`6`
### POSITION
Alias for [LOCATE](#locate).
### REGEXP\_COUNT
Searches a string for all occurrences of a regular expression pattern. The function returns an integer representing the number of times the regular expression pattern occurs in the string.
**Syntax**
```sql SQL theme={null}
REGEXP_COUNT( string, pattern [, position [, parameters ] ] )
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `string` | `CHAR` | The string to search, specified as a character string. |
| `pattern` | `CHAR` | The regular expression pattern to use in the search, specified as a character string. |
| `position` | `INT` | Optional. The position, specified as a positive integer, that represents the position within the `string` string where to begin the search, based on the number of characters. If this integer exceeds the number of characters in `string`, then the function returns `0`. The default value is `1`. |
| `parameters` | `CHAR` | Optional. Parameters, specified as a character string, that contains one or more characters representing regular expression options for pattern matching. Supported options are: `c` — Perform case-sensitive matching. The System enables this type of matching by default. `i` — Perform case-insensitive matching. `p` — Interpret the pattern using the Perl Compatible Regular Expression (PCRE) dialect. For details, see [PCRE](https://www.boost.org/doc/libs/1_33_1/libs/regex/doc/syntax_perl.html#Perl). The Ocient System enables this interpretation by default. |
**Example**
This example searches the `'ABABDaSGRESaB'` string for the count of occurrences of the `'AB'` string by ignoring the case sensitivity. The search starts at position `1`.
```sql SQL theme={null}
SELECT REGEXP_COUNT('ABABDaSGRESaB', 'AB', 1, 'i');
```
\*Output: \*`3`
### REGEXP\_INSTR
Searches a string using a regular expression pattern and returns an integer representing the start position or end position of the substring that matches.
The function returns `0` if no match is found.
The `REGEXP_INSTR` function is similar to the [POSITION](#position) function, but it allows greater precision with regular expressions.
**Syntax**
```sql SQL theme={null}
REGEXP_INSTR( source_string, pattern [, position [, occurrence] [, option [, parameters ] ] ] ] )
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | The string to search, specified as a character string. Note that SQL escape sequences for string literals can override regular expression escape sequences. For details, see [String Literals and Escape Sequences](/data-query-language-dql-statement-reference#string-literals-and-escape-sequences). |
| `pattern` | `CHAR` | The regular expression pattern to use in the search, specified as a character string. |
| `position` | `INT` | Optional. A positive integer that represents the position within the `string` string where to begin the search, based on the number of characters. This value alters only the start position for the match, not the returned string position. If this integer exceeds the number of characters in `string`, then the function returns `0`. The default value is `1`. |
| `occurrence` | `INT` | Optional. A positive integer that represents the occurrence of a positive pattern match to return. The default value is `1`, which means the function returns the first substring that matches the regular expression pattern. |
| `option` | `INT` | Optional. An integer that specifies whether to return the position of the matching start position or the end position. Your choices are: \* `0`: Returns the start position of the match. \* `1`: Returns the end position of the match `+1`. The function treats any nonzero integer value as `1`. The default value is `0`. |
| `parameters` | `CHAR` | Optional. A string containing one or more characters that represents the regular expression options for pattern matching. Supported options are: `c` — Perform case-sensitive matching. The Ocient System enables this type of matching by default. `i` — Perform case-insensitive matching. `e` — Extract the substring using a regular expression subpattern. This subpattern is enclosed in parentheses in the regular expression. The function uses the full regular expression pattern for the match but returns only the first subpattern match. `p` — Interpret the pattern using the Perl Compatible Regular Expression (PCRE) dialect. For details, see [PCRE](https://www.boost.org/doc/libs/1_33_1/libs/regex/doc/syntax_perl.html#Perl). The Ocient System enables this interpretation by default. |
**Example**
The query searches the website URL for the substring preceded by the `#` character. The function includes optional arguments to start the search at position `9` and match the first occurrence. The last specified optional argument directs the function to return the ending position of the matching substring.
```sql SQL theme={null}
SELECT REGEXP_INSTR(
'https://docs.ocient.com/character-binary-functions#J28jB',
'#\w+',
9,
1,
1
);
```
\*Output: \*`57`
### REGEXP\_REPLACE
Searches a string for all occurrences of a regular expression pattern. The function replaces every match occurrence of the pattern with a new string.
The `REGEXP_REPLACE` function is similar to the [REPLACE](#replace) and [TRANSLATE](#translate) functions, but it allows greater precision with regular expressions.
**Syntax**
```sql SQL theme={null}
REGEXP_REPLACE( string, pattern [, replace_string [ , position [, parameters ] ] ] )
```
| **Argument** | **Data** **Type** | **Description** |
| ---------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | The string to search, specified as a character string. Note that SQL escape sequences for string literals can override regular expression escape sequences. For details, see [String Literals and Escape Sequences](/data-query-language-dql-statement-reference). |
| `pattern` | `CHAR` | The regular expression pattern to use in the search, specified as a character string. |
| `replace_string` | `CHAR` | Optional. A string to replace all occurrences of the regular expression pattern in `string`. This string can include references to capture groups in the regular expression `pattern`. To reference capture groups, use a `$` followed by the group number. For example, `$1` references the first capture group, and `$2` references the second. The default value is an empty string `''`. |
| `position` | `INT` | Optional. A positive integer that represents the position within the string to begin the search, based on the number of characters. If this integer exceeds the number of characters in `string`, then the function returns the original `string`. The default value is `1`. |
| `parameters` | `CHAR` | Optional. A string containing one or more characters representing regular expression options for pattern matching. Supported options are: `c` — Perform case-sensitive matching. The Ocient System enables this type of matching by default. `i` — Perform case-insensitive matching. `p` — Interpret the pattern using the Perl Compatible Regular Expression (PCRE) dialect. For details, see [PCRE](https://www.boost.org/doc/libs/1_33_1/libs/regex/doc/syntax_perl.html#Perl). The Ocient System enables this interpretation by default. |
**Examples**
**Replace Text Using a Substring**
The query replaces the matching substring `'#J28jB'` with the characters `'#0FqD_'`. The search begins at position `9`.
```sql SQL theme={null}
SELECT REGEXP_REPLACE(
'https://docs.ocient.com/character-binary-functions#J28jB',
'#\w+',
'#0FqD_',
9
);
```
\*Output: \*`/character-and-binary-functions`
**Replace Text Using Multiple Capture Groups**
This example uses three capture groups to take an unformatted phone number and convert it into the `(XXX) XXX-XXXX` format. The `replace_string` argument references each capture group as `$1`, `$2`, and `$3`.
```sql SQL theme={null}
SELECT REGEXP_REPLACE(
'5558675309',
'(\d{3})(\d{3})(\d{4})',
'($1) $2-$3'
);
```
\*Output: \*`(555) 867-5309`
### REGEXP\_SUBSTR
Returns one substring from a string that matches a specified regular expression pattern.
`REGEXP_SUBSTR` is similar to the [SUBSTR](#substr) function, but it allows greater precision with regular expressions.
If the pattern produces no matches, the function returns an empty string.
**Syntax**
```sql SQL theme={null}
REGEXP_SUBSTR( string, pattern [, position [, occurrence [, parameters ] ] ] )
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | The string to search, specified as a character string. Note that SQL escape sequences for string literals can override regular expression escape sequences. For details, see [String Literals and Escape Sequences](/data-query-language-dql-statement-reference). |
| `pattern` | `CHAR` | The regular expression pattern to use in the search, specified as a character string. |
| `position` | `INT` | Optional. A positive integer that represents the position within the string to begin the search, based on the number of characters. If this integer is greater than the number of characters in `string`, then the function returns the original `string`. The default value is `1`. |
| `occurrence` | `INT` | Optional. A positive integer that represents the occurrence of a positive pattern match to return. If this value exceeds the number of matches, then the function returns NULL. The default value is `1`, which means the function returns the first substring that matches the regular expression pattern. |
| `parameters` | `CHAR` | Optional. A string containing one or more characters representing regular expression options for pattern matching. Supported options are: `c` — Perform case-sensitive matching. The Ocient System enables this type of matching by default. `i` — Perform case-insensitive matching. `e` — Extract the substring using a regular expression subpattern. This subpattern is enclosed in parentheses in the regular expression. The function uses the full regular expression pattern for the match, but it returns only the first subpattern match. If there is no subexpression in the `pattern` argument, then the `e` parameter is ignored. `p` — Interpret the pattern using the Perl Compatible Regular Expression (PCRE) dialect. For details, see [PCRE](https://www.pcre.org/). The Ocient System enables this interpretation by default. |
**Example**
The query returns the first occurrence of the `#J28jB` string by using the regular expression pattern `'#\w+'`. The search starts at position `9`.
```sql SQL theme={null}
SELECT REGEXP_SUBSTR(
'https://docs.ocient.com/character-binary-functions#J28jB',
'#\w+',
9,
1
);
```
\*Output: \*`#J28jB`
### REPEAT
Repeats the `char` string `num` times without spaces.
**Syntax**
```sql SQL theme={null}
REPEAT(char, num)
```
**Example**
Repeat the `a` string five times.
```sql SQL theme={null}
SELECT REPEAT('a', 5);
```
\*Output: \*`aaaaa`
### REPLACE
Replaces all occurrences of `substr_to_remove` in the character value `string` with `substr_to_replace`.
**Syntax**
```sql SQL theme={null}
REPLACE(string, substr_to_remove, substr_to_replace)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `string` | `CHAR` | A string to alter by replacing all instances of `substr_to_remove` with `substr_to_replace`. |
| `substr_to_remove` | `CHAR` | A substring to remove from `string`, replacing all instances with the `substr_to_replace` value. If `substr_to_remove` is the empty string, the system returns `string`. |
| `substr_to_replace` | `CHAR` | A substring to replace all instances of `substr_to_remove`. |
**Example**
```sql SQL theme={null}
SELECT REPLACE('abcabcabcabc', 'ab', '$');
```
\*Output: \*`$c$c$c$c`
### REVERSE
Reverse the input string.
**Syntax**
```sql SQL theme={null}
REVERSE(char)
```
**Example**
```sql SQL theme={null}
SELECT REVERSE('abcd');
```
\*Output: \*`dcba`
### RIGHT
Return the number of trailing characters in the string equal to the value `integer`.
**Syntax**
```sql SQL theme={null}
RIGHT(char, integer)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `char` | `CHAR` | A string to evaluate to return the number of trailing characters equal to `integer`. |
| `integer` | `INT` | The number of characters of return from the end of the `char` string. If `integer` is negative, the function returns all but the first `integer` characters. |
**Example**
```sql SQL theme={null}
SELECT RIGHT('ocient data warehouse', 8);
```
\*Output: \*`arehouse`
**Example**
```sql SQL theme={null}
SELECT RIGHT('ocient data warehouse', -3);
```
\*Output: \*`ent data warehouse`
### RPAD
Pad the input text to the specified length with the pad string on the right side. If text is longer than length, it is truncated to `length` characters. If the argument pad is not provided, the space character is used.
**Syntax**
```sql SQL theme={null}
RPAD(character_value_text, integral_value_length [, character_value_pad] )
```
| **Argument** | **Data** **Type** | **Description** |
| --------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | A string to be padded on its right side with additional characters, so that it equals the `length` value. |
| `length` | `INT` | The number of characters for `string` to total. If the `string` is already longer than `length`, the function truncates `string` to equal the `length` value. |
| `pad_character` | `CHAR` | Optional. A string of one or more characters to use to pad `string` to equal the `length` value. If not provided, `pad_character` uses a whitespace character to pad. |
**Example**
```sql SQL theme={null}
SELECT RPAD('ocient data warehouse',30);
```
\*Output: \*`ocient data warehouse `
**Example**
```sql SQL theme={null}
SELECT RPAD('ocient data warehouse',30,'ab');
```
\*Output: \*`ocient data warehouseababababa`
### RSUBSTRING
Returns the substring from the right side of a string, based on a specified length.
**Syntax**
```sql SQL theme={null}
RSUBSTRING(string, integer)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ----------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | A string to be evaluated to return a substring based on the `integer` value. |
| `integer` | `INT` | The number of characters to return from the right side of the `string` value. This value must be positive. |
**Example**
```sql SQL theme={null}
SELECT RSUBSTRING('ocient data warehouse',14);
```
\*Output: \*`data warehouse`
### RTRIM
Removes trailing blanks from the string value `string`.
Alternatively, you can specify a second string value `trim_character`. If you specify the `trim_character` value, the RTRIM function removes all trailing instances of the `trim_character` value from the `string`.
**Syntax**
```sql SQL theme={null}
RTRIM(string [, trim_character] )
```
| **Argument** | **Data** **Type** | **Description** |
| ---------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `string` | `CHAR` | A string to be trimmed on its right side. |
| `trim_character` | `CHAR` | Optional. A string of one or more characters to be trimmed from the right side of `string`. Each character is trimmed individually, not as a cohesive substring. If you do not specify this argument, this value defaults to removing all whitespace from the right side of `string`. |
**Example**
```sql SQL theme={null}
SELECT RTRIM('ocient ');
```
\*Output: \*`ocient`
**Example**
```sql SQL theme={null}
SELECT RTRIM('ocientaaaaaa','a');
```
\*Output: \*`ocient`
### SHA1
Uses the \[SHA-1]\([https://en.wikipedia.org/wiki/SHA-1#:\~:text=In%20cryptography%2C%20SHA%2D1%20(,rendered%20as%2040%20hexadecimal%20digits](https://en.wikipedia.org/wiki/SHA-1#:~:text=In%20cryptography%2C%20SHA%2D1%20\(,rendered%20as%2040%20hexadecimal%20digits).) cryptographic hash function to convert a string into a 40-character string representing the hexadecimal value of a 160-bit checksum.
**Syntax**
```sql SQL theme={null}
SHA1(string)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ---------------------------------------------------------------- |
| `string` | `CHAR` | A string to convert using the SHA-1 cryptographic hash function. |
**Example**
```sql SQL theme={null}
SELECT SHA1('Ocient');
```
\*Output: \*`0c2a9a042b9f047f875c3414e7a4f4c53efbe082`
### SPACE
Returns a string of repeated spaces equal to the number value, `repeat`. You can join this to another string by using the [CONCAT](#concat) function.
**Syntax**
```sql SQL theme={null}
SPACE(repeat)
```
**Example**
```sql SQL theme={null}
SELECT CONCAT(SPACE(10),'end');
```
\*Output: \*` end`
### SPLIT\_PART
Split the value `string` based on the `delimiter` value. The function returns a substring from the split operation based on the `index` value (starting from 1).
**Syntax**
```sql SQL theme={null}
SPLIT_PART(string, delimiter, index)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ----------------------------------------------------------------------------- |
| `string` | `CHAR` | A string to be split based on the `delimiter` value. |
| `delimiter` | `CHAR` | The character to use as a delimiter in `string`. |
| `index` | `INT` | The index of the substring to return. The first index position starts at `1`. |
**Example**
```sql SQL theme={null}
SELECT SPLIT_PART('id|name|address','|',1);
```
\*Output: \*`id`
**Example**
```sql SQL theme={null}
SELECT SPLIT_PART('id|name|address','|',2);
```
\*Output: \*`name`
**Example**
```sql SQL theme={null}
SELECT SPLIT_PART('id,name,address',',',3);
```
\*Output: \*`address`
### SPLIT\_TO\_ARRAY
Splits a string into an array of substrings.
**Syntax**
```sql SQL theme={null}
SPLIT_TO_ARRAY(string, [ delimiter ])
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ------------------------------------------------------------------------------------------------ |
| `string` | `CHAR` | A string to split into an array of substrings. |
| `delimiter` | `CHAR` | Optional. The delimiter that divides the string. The default value is a comma (`,`). |
**Example**
This example specifies `|` as the delimiter to split the input string.
```sql SQL theme={null}
SELECT SPLIT_TO_ARRAY('AB|CD|EF', '|');
```
\*Output: \*`['AB','CD','EF']`
### STARTSWITH
Returns `true` if `string` starts with `substring` and `false` otherwise.
**Syntax**
```sql SQL theme={null}
STARTSWITH(string, substring)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ------------------------------------------------- |
| `string` | `CHAR` | A string to search. |
| `substring` | `CHAR` | A substring to find at the beginning of `string`. |
**Example**
```sql SQL theme={null}
SELECT STARTSWITH('ocient','o');
```
\*Output: \*`true`
**Example**
```sql SQL theme={null}
SELECT STARTSWITH('ocient','c');
```
\*Output: \*`false`
### STRPOS
Equivalent to using [LOCATE](#locate) as `LOCATE(substring, string)`. Note the reversed argument order.
**Syntax**
```sql SQL theme={null}
STRPOS(string, substring)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | --------------------------------------------------------------- |
| `string` | `CHAR` | A string to be evaluated for the first position of `substring`. |
| `substring` | `CHAR` | A substring to be found for its first position in `string`. |
**Example**
```sql SQL theme={null}
SELECT STRPOS('ocient data warehouse','house');
```
\*Output: \*`17`
### SUBSTR
Alias for [SUBSTRING](#substring).
### SUBSTRING
Alias for SUBSTR and MID.
Returns the substring of a character or binary value that starts with the position specified by the second argument and that ends with the position specified by one less than the sum of the second and third arguments. When the sum of the second and third arguments is less than two, the function returns the empty string.
**Syntax**
```sql SQL theme={null}
SUBSTRING(string, start_position [, length] )
```
| **Argument** | **Data** **Type** | **Description** |
| ---------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | A string to be truncated based on the `start_position` and `end_position` values. |
| `start_position` | `INT` | The starting position to return a substring. The first index position starts at `1`. |
| `length` | `INT` | Optional. The number of characters from the `start_position` to include in the returned substring. If unspecified, SUBSTRING returns all characters after the `start_position`. |
**Example**
```sql SQL theme={null}
SELECT SUBSTRING('ocient data warehouse',8);
```
\*Output: \*`data warehouse`
**Example**
```sql SQL theme={null}
SELECT SUBSTRING('ocient data warehouse',8,4);
```
\*Output: \*`data`
### TO\_CHAR
Converts a numeric, date, or timestamp value into a `CHAR` date type.
```sql SQL theme={null}
TO_CHAR(value, format)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `value` | `DATE`, `TIMESTAMP`, or all numeric types | A numeric, date, or timestamp value to be converted into a `CHAR` date type. |
| `format` | `CHAR` | The format used for the `CHAR` conversion. For information on data type formats, see the [Formatting Functions](/formatting-functions) page. |
**Example**
```sql SQL theme={null}
SELECT TO_CHAR(20200610132514/1000000,'9999-99-99');
```
\*Output: \*`2020-06-10`
**Example**
```sql SQL theme={null}
SELECT TO_CHAR(20200610132514%1000000,'99:99:99');
```
\*Output: \*`13:25:14`
### TRANSLATE
Replaces specified characters in a provided string with a separate set of characters.
Characters specified in the `char_to_remove` set are replaced with characters in the `char_to_replace` set based on the corresponding index position.
**Syntax**
```sql SQL theme={null}
TRANSLATE(string, char_to_remove, char_to_replace)
```
| **Argument** | **Data** **Type** | **Description** |
| ----------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | A string to have specific characters transposed based on the `char_to_remove` and `char_to_replace` values. |
| `char_to_remove` | `CHAR` | The characters to be removed from `string`. Characters specified in the `char_to_remove` set are replaced with characters in the `char_to_replace` set based on the corresponding index position. If `char_to_remove` is longer than `char_to_replace`, occurrences of the extra characters are removed. |
| `char_to_replace` | `CHAR` | The characters to replace the removed characters in `char_to_remove`. |
**Example**
```sql SQL theme={null}
SELECT TRANSLATE('abcdef','ace','ghi');
```
\*Output: \*`gbhdif`
### TRIM
Alias for BTRIM.
Trim leading and trailing space characters from the string.
Alternatively, you can specify a second string value `trim_char`. If a `trim_char` value is provided, the `TRIM` function removes all leading and trailing instances of the `trim_char` value from the string.
**Syntax**
```sql SQL theme={null}
TRIM(string [, trim_char] )
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `string` | `CHAR` | A string to be trimmed of leading and trailing space characters, or any other characters specified by the `trim_char` argument. |
| `trim_char` | `CHAR` | Optional. If specified, this removes an alternative substring from the start or end of the `string` value. |
**Example**
```sql SQL theme={null}
SELECT TRIM(' trimmed string ');
```
\*Output: \*`trimmed string`
**Example**
```sql SQL theme={null}
SELECT TRIM('aaaaaaaatrimmed stringaaaaaaaaa', 'a');
```
\*Output: \*`trimmed string`
### UCASE
Alias for [UPPER](#upper).
### UPPER
Alias for UCASE.
Convert string to upper case.
**Syntax**
```sql SQL theme={null}
UPPER(character_value)
```
**Example**
```sql SQL theme={null}
SELECT UPPER('ocient');
```
\*Output: \*`OCIENT`
### Concatenate Operator(`||`)
The `||` operator concatenates two strings. If you specify a NULL string, the result is NULL.
`||` **Syntax**
```sql SQL theme={null}
string1 || string2
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ---------------------------------------------- |
| `string1` | `CHAR` | A string to concatenate. |
| `string2` | `CHAR` | A string to concatenate with the first string. |
**Examples**
**Concatenate Two Strings**
Concatenate two strings.
```sql SQL theme={null}
SELECT 'hello ' || 'world';
```
Output: `'hello world'`
**Concatenate a NULL String**
Concatenate two strings, one of which is NULL.
```sql SQL theme={null}
SELECT NULL || 'world';
```
Output: `NULL`
## Related Links
[WHERE](/data-query-language-dql-statement-reference#where)
[Formatting Functions](/formatting-functions)
# Checking System After Configuration
Source: https://docs.ocient.com/checking-system-after-configuration
Verify that an Ocient System is healthy after configuration by checking node status, storage spaces, network connectivity, and core service operation.
The `postcheck` command helps capture critical node health states and metrics after the configuration process.
You can run the command as shown in this example. The flags included after the `precheck` command are optional. See [Flags for Command Execution](#flags-for-command-execution) for descriptions.
```shell Shell theme={null}
$ sudo /usr/local/bin/postcheck --dsn ocient://:@:/
```
This table describes each placeholder in the DSN:
| **Placeholder** | **Description** |
| --------------- | ------------------------------------------------------------------------------ |
| `` | The username for the Ocient database connection (for example, `admin@system`). |
| `` | The password associated with the specified user. |
| `` | The hostname or IP address of the SQL Node to connect to. |
| `` | The port number on which the SQL Node is listening. |
| `` | The name of the database to connect to. |
The command invokes a script from the command line on operating systems supported by Ocient. The script sends output to standard output (STDOUT) and standard error (STDERR) with the option to send a text file or a JSON file.
To specify the file option, use this flag: `--logfile-location ` where `` is the directory where the `postcheck` command creates the log file.
Before you begin, ensure that all steps in the [Ocient System Bootstrapping](/ocient-system-bootstrapping) process are complete.
## Prerequisites
The script requires and the Ocient JDBC JAR to run. In most cases, you should use this script on client servers rather than database nodes.
To get the post-check script onto a client, perform the `scp` operation on the wheel onto the server and run `python3 -m pip install --no-index /postcheck*.whl`, and replace `` with the path to the directory of the wheel file on your server.
## Flags for Command Execution
Use the `postcheck` command to run the script that checks the system configuration after you configure Ocient. You can execute the command using these flags.
| **Flag Name** | **Required** | **Values** | **Default** | **Description** | **Example** |
| ------------------ | ------------ | ----------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| --dsn | Yes | Many | Not applicable | Data source name (DSN). The script prompts for your credentials. | `--dsn ocient://host:port/path` connects you to the specified cluster where `host` is the host name, `port` is the port number, and `path` is the path on the host for the connection. |
| --logfile-location | No | Non-empty string | /var/opt/ocient/log | Name of directory that contains the log file created from the execution of the script. | `--logfile-location /user/query/logs` generates a log file in the `/user/query/logs` directory. If this directory does not exist, the command issues a warning. |
| --print-level | No | verbose or silent | verbose | Denotes the level of detail in the output. See the “Outputs” section. | `--print-level verbose` provides a detailed report with information about the checks that Ocient performs. `--print-level silent` provides the overall status from the check of the system. |
| --timeout | No | Any integer | 3 | Denotes the default timeout (in seconds) for running any command-line command in the script. In most cases, the default is enough, so you do not need to specify this setting. | `--timeout 4` runs checks with a timeout of 4 seconds for each command. |
| --jar-path | No | Non-empty string | /opt/ocient/current/ocient-jdbc4.jar | Denotes the path to the Ocient JDBC JAR. The default value is the usual location of the JAR file on an Ocient System. This path must be accurate for the postcheck command to run correctly. | `--jar-path /opt/ocient/test_dir/jdbc.jar` uses the JAR at `/opt/ocient/test_dir/jdbc.jar` to run JDBC commands for the `postcheck` command. |
| --json | No | Not applicable | False | If you specify the --json flag, the command prints output in JSON format to STDOUT. If you do not specify this flag, the command prints human-readable output to STDOUT. | `--json` prints output in JSON format to STDOUT. |
## Command Output
The command has two types of output, silent or verbose, which you can specify by using the `--print-level` flag at the command line.
**Silent**
The `silent` value for the `--print-level` flag only produces a status code. The code is 0 for success, 1 for error, and 2 for warning.
**Verbose**
The `verbose` value for the `--print-level` flag prints either human-readable output by default or output in JSON format (if you specify the `--json` flag). The output contains all status details.
This example shows human-readable output.
```Text Text theme={null}
Warnings:
- Foundation Nodes storage are non-uniform.
OS Configuration - OK
================
Huge Page Settings - OK
isolcpus settings - OK
Memory - OK
======
Foundation Nodes: 1024 GB
SQL Nodes: 1024 GB
Loader Nodes: 1536 GB
Total DRAM: 123120 GB
...
```
This example shows output in JSON format.
```json JSON theme={null}
{"status": 2,
"components": {
"firmware": {
"status": 0,
"message": "SUCCESS: NVMe drive firmware is consistent across nodes."
}
"symmetry": {
"status": 2,
"message": "WARNING: non-uniform configuration."
"storage": {
"status": 2,
"foundation": {
"status": 0,
"message": "SUCCESS: storage consistent across Foundation Nodes."
"foundation1": 16TB,
...
}
...
}
}
```
## Related Links
[Ocient System Bootstrapping](/ocient-system-bootstrapping)
[Ocient Application Configuration](/ocient-application-configuration)
# Checking System Configuration Before Bootstrapping
Source: https://docs.ocient.com/checking-system-configuration-before-bootstrapping
Validate Ocient System configuration before bootstrapping nodes, including hostnames, networking, disk layout, and configuration files to prevent setup errors.
The `precheck` command helps capture critical node health states and metrics before bootstrapping your installation.
You can run the command as shown in this example. The flags included after the `precheck` command are optional. See [Optional Flags for Command Execution](#optional-flags-for-command-execution) for descriptions.
```shell Shell theme={null}
$ sudo precheck --print-level verbose --node-type metadata --logfile-location /home/admin
```
The command invokes a script from the command line on operating systems supported by Ocient. The script sends output to standard output (STDOUT) and standard error (STDERR). To specify the file option, use this flag: `--logfile-location ` where `` is the directory where the `precheck` command creates the log file. Critically, this script captures information about huge page configuration.
## Optional Flags for Command Execution
Use the `precheck` command to run the script that checks the system configuration. You can execute the command using the optional flags shown in this table.
| **Flag Name** | **Values** | **Default** | **Description** | **Example** |
| ----------------------- | -------------------------------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| --logfile-location | Non-empty string | `/var/opt/ocient/log` | Name of the directory that contains the log file created from the execution of the script. | `--logfile-location /user/query/logs` generates a log file in the `/user/query/logs` directory. If this directory does not exist, the command issues a warning. |
| --print-level | verbose or silent | verbose | Denotes the level of detail in the output. See the “Outputs” section. | `--print-level verbose` provides a detailed report with information about the checks that Ocient performs. --print\_level silent provides the overall status from the check of the system. |
| --node-type | metadata, lts, streamloader, sql, or unknown | unknown | Denotes the current node type. If you do not specify this setting, the script tries to infer node type based on metrics it collects. | `--node-type lts` runs checks with values and constraints that pertain to an `lts` node. |
| --timeout | Any integer | 3 | Denotes the default timeout (in seconds) to run any command-line command in the script. In most cases, the default is enough, so you do not need to specify this setting. | `--timeout 4` runs checks with a timeout of 4 seconds for each command. |
| --nvme-driver-util-path | Non-empty string | /opt/ocient/scripts/nvme-driver-util.sh | Path to `nvme-driver-util` script that the precheck script uses. The default value is the location of the script on most installations, so in most cases, you do not need to specify this setting. | `--nvme-driver-util-path /opt/ocient/test_dir/nvme-driver-util.sh` uses `/opt/ocient/test_dir/nvme-driver-util.sh` as the path to the utility script. |
| --json | Not applicable | False | If you specify the `--json` flag, the command prints output in JSON format to STDOUT. If you do not specify this flag, the command prints human-readable output to STDOUT. | `--json` prints output in JSON format to STDOUT. |
## Command Output
The command has two types of output, silent or verbose, which you can specify by using the `--print-level` flag at the command line.
**Silent**
The `silent` value for the `--print-level` flag only produces a status code. The code is 0 for success, 1 for error, and 2 for warning.
**Verbose**
The `verbose` value for the `--print-level` flag prints either human-readable output by default or output in JSON format (if you specify the `--json` flag). The output contains all status details.
This example shows human-readable output.
```Text Text theme={null}
Warnings:
- isolcpus not configured - recommended for performance.
- No eligible NVMe payload drives found for node.
- bootstrap.conf file does not exist. Create a file at /var/opt/ocient/bootstrap.conf with the correct bootstrapping settings. If this is the initial node in the system set "initialSystem: true" in the bootstrap.conf file. If this is not the initial node, use the "adminHost" setting to specify the address of the initial node. To add custom settings, follow the instructions in Bootstrapping and Ocient System in the User Documentation.
- SELinux is enabled. This might prevent Ocient from functioning properly. Please disable or set to permissive mode.
Memory - OK
======
ramconfig - SUCCESS: RAM configuration is adequate.
Firmware and Hardware - ERROR
====================
nonbootdrives - WARNING: No eligible NVMe payload drives found for node
...
```
This example shows output in JSON format.
```json JSON theme={null}
{"status": 1,
"components": {
"enforce_status": {
"status": 2,
"message": "WARNING: SELinux is enabled. This might prevent Ocient from functioning properly. Please disable or set to permissive mode"
}
"bootstrap": {
"status": 2,
"message": "WARNING: bootstrap.conf file does not exist. Create a file at /var/opt/ocient/bootstrap.conf with the correct bootstrapping settings. If this is the initial node in the system set "initialSystem: true" in the bootstrap.conf file. If this is not the initial node, use the "adminHost" setting to specify the address of the initial node. To add custom settings, follow the instructions in Bootstrapping and Ocient System in the User Documentation."
}
...
}
}
```
## Related Links
[Ocient System Bootstrapping](/ocient-system-bootstrapping)
[Ocient Application Configuration](/ocient-application-configuration)
# Classification Analysis
Source: https://docs.ocient.com/classification-analysis
Use classification analysis techniques within Ocient with OcientML to categorize data, helping in decision-making and pattern identification.
Classification machine learning algorithms are available in . There are many different popular classification algorithms, which work in slightly different ways with different strengths and weaknesses. These tutorials and examples cover some basic rules for using classification algorithms and how you can take advantage of these models in .
It can be very challenging to anticipate which classification model is best suited for a data set. Often, it is best to experiment with multiple different models to see what happens.
## Logistic Regression
Despite its name, logistic regression is a classification algorithm, not a regression algorithm. Logistic regression is generally a good first step for trying out a classification model before moving on to more advanced options.
Logistic regression shares many restrictions with the support vector machines model. Both models require that all features are numeric. However, you can still use non-numeric data if you convert it using one-hot encoding. The class labels can be any data type.
Use one-hot encoding to convert non-numeric data into numeric form.
For example, if a feature is a color (such as red, green, or blue), then one-hot encoding can make three columns named `is_red`, `is_green`, and `is_blue`. For each row, set one color to the value `1` and the other colors to `0`.
This example uses the `lr_input` table, which represents the academic performance of students.
```sql SQL theme={null}
CREATE TABLE mldemo.lr_input AS (
SELECT hours_studied,
grade_in_prev_course,
CASE
WHEN RAND() > (1.0 - effective_score) THEN true
ELSE false
END AS got_top_marks
FROM
( SELECT hours_studied,
grade_in_pr ev_course,
(2 * grade_in_prev_course + hours_studied) / 10.0 AS effective_score
FROM
( SELECT mod(a.c1, 10) AS hours_studied,
mod(b.c1, 5) AS grade_in_prev_course
FROM sys.dummy100 a,
sys.dummy100 b
)
)
);
```
There are two features: the number of hours spent studying `hours_studied` and the grade in the previous course `grade_in_prev_course`. Both input features are numeric. There are also two classes: `true` and `false`. Class values do not need to be Boolean, and they can be any distinct values.
Students who have better grades in the previous course and spend more hours studying are more likely to have top marks in the course. However, this table also includes a randomness factor, which means that rows with the same features can have different classifications. This is normal in real-world data.
This example creates the logistic regression model on the table, including the `metrics` option. This option causes the model to calculate the percentage of samples that are correctly classified. The Ocient System puts this information into the system catalog tables.
```sql SQL theme={null}
CREATE MLMODEL lr1 TYPE LOGISTIC REGRESSION ON (
SELECT *
FROM mldemo.lr_input
) options('metrics'->'true');
```
This query selects the `machine_learning_models` and `logistic_regression_models` system catalog tables.
```sql SQL theme={null}
SELECT name,
on_select,
num_arguments,
zero_case,
one_case,
correctly_classified
FROM sys.machine_learning_models a,
sys.logistic_regression_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'lr1';
name on_select num_arguments zero_case one_case correctly_classified
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
lr1 select * from mldemo.lr_input 2 cast('true' as BOOLEAN) cast('false' as BOOLEAN) 0.8397
Fetched 1 row
```
The model captures the two values for the two target classes. The `correctly_classified` column shows the model has almost 84 percent accuracy from working on the training data. This level of accuracy is pretty good, especially for a model using training data with significant randomness.
This model can predict which classification is most likely if you provide the number of hours studied and grades in the previous course.
First, review the average hours spent studying for each classification.
```sql SQL theme={null}
SELECT avg(hours_studied)
FROM mldemo.lr_input
WHERE got_top_marks;
(sum(hours_studied)) /(null_if(double(count(hours_studied)), (0)))
------------------------------------------------------------------
5.231264244536801
Fetched 1 row
SELECT avg(hours_studied)
FROM mldemo.lr_input
WHERE NOT got_top_marks;
(sum(hours_studied)) /(null_if(double(count(hours_studied)), (0)))
------------------------------------------------------------------
2.3534041715859897
Fetched 1 row
```
As expected, the rows where `got_top_marks` is true have a higher average value for `hours_studied`. The same should be true with `grade_in_prev_course`.
```sql SQL theme={null}
SELECT AVG(grade_in_prev_course)
FROM mldemo.lr_input
WHERE got_top_marks;
(SUM(grade_in_prev_course)) /(NULL_IF(DOUBLE(COUNT(grade_in_prev_course)), (0)))
--------------------------------------------------------------------------------
2.3535326451266925
Fetched 1 row
SELECT avg(grade_in_prev_course)
FROM mldemo.lr_input
WHERE NOT got_top_marks;
(sum(grade_in_prev_course)) /(NULL_IF(DOUBLE(COUNT(grade_in_prev_course)), (0)))
--------------------------------------------------------------------------------
0.9622195985832349
Fetched 1 row
```
You can also query to find the rows that are anomalies. In most cases, students achieved top marks in their class despite having minimal study hours and low grades in their previous classes.
```sql SQL theme={null}
SELECT *
FROM mldemo.lr_input
WHERE got_top_marks != lr1(hours_studied, grade_in_prev_course)
LIMIT 10;
hours_studied grade_in_prev_course got_top_marks
-------------------------------------------------------
1 1 true
1 1 true
1 4 false
1 1 true
1 2 true
1 0 true
1 2 true
1 1 true
1 2 true
1 1 true
Fetched 10 rows
```
For details about using this model type, see [Logistic Regression](/classification-models#logistic-regression).
## Support Vector Machine
Support vector machine (SVM) tries to find a hyperplane to divide data into two classes with these objectives:
* The hyperplane has the maximum margin, meaning the most distance between the two classes.
* The model correctly classifies the highest percentage of data points.
By default, SVM models in Ocient try to balance these two objectives. You can increase the priority of either objective by using the `regularizationCoefficient` option.
For data sets with two features, the SVM hyperplane represents a straight line on a Cartesian graph.
For three features, the hyperplane represents a plane.
This example uses the SVM model on the same classification data set of student performance as used in the logistic regression section.
```sql SQL theme={null}
CREATE MLMODEL svm1 TYPE SUPPORT VECTOR MACHINE ON (
SELECT *
FROM mldemo.lr_input
) options('metrics'->'true');
Modified 0 rows
```
The `machine_learning_models` and `support_vector_machine_models` system catalog tables for SVM contain almost the same information as logistic regression.
```sql SQL theme={null}
SELECT name,
on_select,
num_arguments,
negative_case,
positive_case,
correctly_classified
FROM sys.machine_learning_models a,
sys.support_vector_machine_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'svm1';
name on_select num_arguments negative_case positive_case correctly_classified
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
svm1 select * from mldemo.lr_input 2 cast('false' as BOOLEAN) cast('true' as BOOLEAN) 0.8397
Fetched 1 row
```
The system catalog tables indicate the same percentage of correctly classified rows as the logistic regression model (about 84 percent).
The SVM model can increase the accuracy further by using a kernel. A kernel is a transformation to make data linearly separable. SVM in Ocient allows you to specify any kernel of your choice.
For example, suppose that a circle can separate two classes of data, dividing data points between those inside and outside the circle. The SVM model cannot find a line to divide the two classes very well, or this problem is not linearly separable. However, you can transform the data into three dimensions (three features) to make it linearly separable. This is the idea of a kernel.
You specify the kernel using the options `function1`, `function2`, `function3`, etc. Each function defines the formula for the kernel to create new features. Functions can use features from the original data set, represented by `x1`, `x2`, `x3`, etc.
To explain this, revisit the circle example. Suppose that the circle centered at the point `(2, 2)` is the class inside. Otherwise, the circle is the class outside. The data that is separable by a circle in two dimensions is linearly separable in three dimensions with the features `x1`, `x2`, `x1^2 + x2^2`.
This statement creates the data and the model.
```sql SQL theme={null}
CREATE TABLE mldemo.circle AS (
SELECT x,
y,
CASE
WHEN SQRT((x -2) ^ 2 + (y -2) ^ 2) <= 1 then 'INSIDE'
ELSE 'OUTSIDE'
END AS label
FROM (
SELECT RAND() * 10 as x,
RAND() * 10 as y
FROM sys.dummy10000
)
);
Modified 10000 rows
CREATE MLMODEL svm2 type SUPPORT VECTOR MACHINE ON (
SELECT x,
y,
label
FROM mldemo.circle
) options(
'metrics'->'true',
'function1'->'x1',
'function2'->'x2',
'function3'->'x1^2 + x2^2'
);
Modified 0 rows
```
The example includes three functions, meaning that the kernel increases from two to three dimensions. The kernel functions refer to the original feature values `x1` and `x2`. If you examine the `correctly_classified` value in the `machine_learning_models` and `support_vector_machine_models` system catalog tables, you can see a model that classifies nearly everything correctly.
```sql SQL theme={null}
SELECT NAME,
negative_case,
positive_case,
correctly_classified
FROM sys.machine_learning_models a,
sys.support_vector_machine_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'svm2';
name negative_case positive_case correctly_classified
-------------------------------------------------------------------------------------------------------------------------------------------------------------
svm2 cast('OUTSIDE' as CHAR) cast('INSIDE' as CHAR) 0.9913
Fetched 1 row
```
One advantage of SVM kernels is that they are automatic. The model saves all the kernel information and transforms the data as needed. Hence, you can execute this model to predict a new point without redefining the kernel. You can pass in the two features the model was built over, and a prediction comes out.
The [sys.machine\_learning\_model\_options](/system-catalog#sys-machine_learning_model_options) table is the location where the SVM model saves kernel information.
This table saves all the options that you specify. Some models also add additional keys to this dictionary to save certain information needed for when the model is executed.
```sql SQL theme={null}
SELECT svm2(2, 2);
COALESCE(('INSIDE'), (NULL));
---------------------------------------------
INSIDE
Fetched 1 row
```
For details about using this model type, see [Support Vector Machine](/classification-models#support-vector-machine).
## Binary Classification with Neural Networks
A neural network using the `FEEDFORWARD NETWORK` model type can perform binary classification. To use this model for classification, you must either convert labels to either `0` and `1` (using the `log_loss` option) or convert labels to `-1` and `1` (using the `hinge_loss` option). Both options can achieve the same result.
This model can handle more complex cases, but using a different model for linearly separable data might be easier. In other words, a neural network model is useful when data is difficult to separate linearly using a kernel.
This example shows a feedforward network model using the `log_loss` option. Note the `CASE` statement to convert labels to `0` or `1`.
```sql SQL theme={null}
CREATE MLMODEL logloss TYPE FEEDFORWARD NETWORK ON (
SELECT x,
y,
CASE
WHEN label = 'INSIDE' THEN 0
ELSE 1
END AS target
FROM mldemo.circle
) options(
'metrics'->'true',
'hiddenLayers'->'2',
'hiddenLayerSize'->'2',
'outputs'->'1',
'lossFunction'->'log_loss'
);
Modified 0 rows
```
This query finds that the classification accuracy is about 97 percent.
```sql SQL theme={null}
SELECT COUNT(*) / 10000.0
FROM (
SELECT x,
y,
label,
CASE
WHEN logloss(x, y) = 0 then 'INSIDE'
ELSE 'OUTSIDE'
END AS predicted
FROM mldemo.circle
)
WHERE label = predicted;
(_count(*)_0)/((10000.0))
--------------------------
0.9698
Fetched 1 row
```
To use the `hinge_loss` option, use `-1` and `1` in the `CASE` statement.
```sql SQL theme={null}
CREATE MLMODEL hingeloss TYPE FEEDFORWARD NETWORK ON (
SELECT x,
y,
CASE
WHEN label = 'INSIDE' THEN -1
ELSE 1
END AS target
FROM mldemo.circle
) options(
'metrics'->'true',
'hiddenLayers'->'2',
'hiddenLayerSize'->'2',
'outputs'->'1',
'lossFunction'->'hinge_loss'
);
Modified 0 rows
```
The accuracy of the `hinge_loss` version is exactly the same as the `log_loss` version.
```sql SQL theme={null}
SELECT count(*) / 10000.0
FROM (
SELECT x,
y,
label,
CASE
WHEN hingeloss(x, y) = -1 THEN 'INSIDE'
ELSE 'OUTSIDE'
END AS predicted
FROM mldemo.circle
)
WHERE label = predicted;
(_count(*)_0)/((10000.0))
--------------------------
0.9698
Fetched 1 row
```
For details about using this model type, see [Feedforward Neural Network](/other-models#feedforward-neural-network).
## K-Nearest Neighbors
K-nearest neighbors (KNN) can only use numeric features, but KNN handles multi-classification in the Ocient System. This algorithm can handle an arbitrary number of target classes.
One drawback with KNN is that it does not work at training time other than to take a snapshot of the training data. The algorithm operates on the data when you execute the model, so it can be a slow model for large data sets.
To demonstrate KNN functionality, this example uses a similar circle of size (2, 2) with some modifications to use more classes:
* Data within a unit circle of (2, 2) is classified as `INSIDE`.
* Data within a radius of 2 is classified as `MIDDLE`.
* Any other data is classified as `OUTSIDE`.
```sql SQL theme={null}
CREATE TABLE mldemo.circles as (
SELECT x, y,
CASE
WHEN SQRT((x -2) ^ 2 + (y -2) ^ 2) <= 1 THEN 'INSIDE'
WHEN SQRT((x -2) ^ 2 + (y -2) ^ 2) <= 2 THEN 'MIDDLE'
ELSE 'OUTSIDE'
END AS label
FROM (
SELECT RAND() * 10 as x,
RAND() * 10 as y
FROM sys.dummy10000
)
);
Modified 10000 rows
```
KNN works by finding the `k` nearest points to the one the model is trying to predict a classification for. `k` is an integer value that you must specify during model creation.
The model calculates distances using normal Euclidean distances. You can override the definition of distance by specifying a formula using the `distance` option.
After the model identifies the points, it computes a score for each class and returns the class with the highest score. The `weight` option can influence each score for the specified point. By default, the `weight` value is based on the inverse of the distance (`1.0/(d+0.1)`). In other words, a point closer to the point you are trying to predict has a larger influence on the output result than a point further away. Any point outside of the nearest `k` points has no influence.
This example uses three classes.
```sql SQL theme={null}
CREATE MLMODEL knn1 TYPE K NEAREST NEIGHBORS ON (
SELECT x,
y,
label
FROM mldemo.circles
) options('k'->'3');
Modified 0 rows
```
These queries test some values to see if the classifications are correct.
```sql SQL theme={null}
SELECT knn1(2, 2);
---------------------------------------------
INSIDE
Fetched 1 row
SELECT knn1(0.5, 2);
---------------------------------------------
MIDDLE
Fetched 1 row
SELECT knn1(5,5);
---------------------------------------------
OUTSIDE
Fetched 1 row
```
KNN models perform work when you execute the model, and the amount of work increases as the input data increases.
One solution to this is data reduction, which means finding a smaller subset of rows to build the KNN model over, enough to ensure that the accuracy of the model is still high. This method front-loads the work when you create the model so that it is much faster to execute on new data.
To use the data reduction feature, set the `dataReduction` option to `true`. By default, the execution stops when the database finds a model that is 90 percent accurate over the training data or when the reduced model increases to 1,000 rows of data. You can override these defaults by setting the `maxReducedRows` or `targetAccuracy` options.
Additionally, if you are using data reduction, you can ask the database to collect metrics on the percent of rows correctly classified by the model because this is much faster to do on the reduced data set.
This example builds another KNN model over the same data and uses data reduction to find a model that is at least 95 percent accurate.
```sql SQL theme={null}
CREATE MLMODEL knn2 TYPE K NEAREST NEIGHBORS ON (
SELECT x,
y,
label
FROM mldemo.circles
) options(
'k'->'3',
'dataReduction'->'true',
'metrics'->'true',
'targetAccuracy'->'0.95'
);
Modified 0 rows
```
Query the `machine_learning_models` and `k_nearest_neighbor_models` system catalog tables to see the snapshot table used for the model and its accuracy.
```sql SQL theme={null}
SELECT table_name,
correctly_classified
FROM sys.machine_learning_models a,
sys.k_nearest_neighbor_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'knn2';
table_name correctly_classified
-------------------------------------------------------------------
temp.knn86947930347148676 0.9541
Fetched 1 row
```
The model with data reduction correctly classifies about 95 percent of the training data. To see the size of the KNN model snapshot, you can query it by its table name.
```sql SQL theme={null}
SELECT COUNT(*) FROM temp.knn86947930347148676;
count(*)
--------------------
300
Fetched 1 row
```
The snapshot is only 300 rows. Without data reduction, the row count would be much larger by orders of magnitude.
For details about using this model type, see [K Nearest Neighbor Classification](/classification-models#k-nearest-neighbors-classification).
## Multi-Class Classification with Neural Networks
The `FEEDFORWARD NETWORK` model type can also perform multi-class classification when the feature classes are numeric. Multi-class classification works by using vectors, where each position in the vector indicates the score for that class. The [argmax](https://en.wikipedia.org/wiki/Arg_max) value of the score of each vector returns the class index.
Much of this example is similar to the previous [Binary Classification with Neural Networks](#binary-classification-with-neural-networks) tutorial, with these modifications to the model options:
* Set the `lossFunction` option to `cross_entropy`.
* Set the `outputs` option to specify the number of classes for the model to use (in this example: `3`).
* Set the `useSoftMax` option to `true`, which applies a [softmax](https://en.wikipedia.org/wiki/Softmax_function) function to the final vector.
When the loss function is `cross_entropy_loss` , the option `useSoftMax` defaults to `true`.
```sql SQL theme={null}
CREATE MLMODEL crossentropy TYPE FEEDFORWARD NETWORK ON (
SELECT x,
y,
CASE
WHEN label = 'INSIDE' THEN { { 1.0,
0.0,
0.0 } }
WHEN label = 'MIDDLE' THEN { { 0.0,
1.0,
0.0 } }
ELSE { { 0.0,
0.0,
1.0 } }
END AS TARGET
FROM mldemo.circles
) options(
'metrics'->'true',
'hiddenLayers'->'2',
'hiddenLayerSize'->'2',
'outputs'->'3',
'lossFunction'->'cross_entropy_loss',
'useSoftMax'->'true'
);
Modified 0 rows
```
Execute this model to return a vector.
```sql SQL theme={null}
SELECT crossentropy(5,5) AS predicted;
predicted
--------------------------------------------------------------------------------
[[1.3436428911280516E-7, 1.811726873154417E-7, 0.9999996844630236]]
Fetched 1 row
```
To get the classification, use the `VECTOR_ARGMAX` function to retrieve the index of the largest value. This function returns the 1‑based index of the largest value in the vector.
```sql SQL theme={null}
SELECT VECTOR_ARGMAX(crossentropy(5,5)) AS predicted;
predicted
--------------------
3
Fetched 1 row
```
This query finds the overall accuracy of the model.
```sql SQL theme={null}
SELECT count(*) / 10000.0
FROM mldemo.circles
WHERE (
label = 'INSIDE'
AND VECTOR_ARGMAX(crossentropy(x, y)) = 1
)
OR (
label = 'MIDDLE'
AND VECTOR_ARGMAX(crossentropy(x, y)) = 2
)
OR (
label = 'OUTSIDE'
AND VECTOR_ARGMAX(crossentropy(x, y)) = 3
);
(_count(*)_0)/((10000.0))
--------------------------
0.9298
Fetched 1 row
```
The model is about 93 percent effective. You can improve the accuracy by modifying the [Model Options](/other-models#model-options-2), including:
* `hiddenLayers`
* `hiddenLayerSize`
* `lossFuncNumSamples`
Increasing the resources of these options can improve accuracy, but could increase the time needed to train the model.
For details about using this model type, see [Feedforward Neural Network](/other-models).
## Multi-Class Classification with Support Vector Machines and Logistic Regression
Both logistic regression and SVM are binary classifiers, but you can use either to build a multi-class classifier to handle any number of classes. OcientML can perform this automatically with either model.
This example shows the `CREATE` statement for the SVM model, which uses the same data as the [K Nearest Neighbors](#k-nearest-neighbors) and [Multi-Class Classification with Neural Networks](#multi-class-classification-with-neural-networks) examples.
```sql SQL theme={null}
CREATE MLMODEL circ1 TYPE SUPPORT VECTOR MACHINE ON (
SELECT x,
y,
label
FROM mldemo.circles
) options(
'metrics'->'true',
'function1'->'x1',
'function2'->'x2',
'function3'->'x1^2 + x2^2'
);
Modified 0 rows
```
This statement uses the same kernel as the example for performing binary classification on [Support Vector Machines](#support-vector-machine).
This query checks the metrics in the `machine_learning_models` and `support_vector_machine_models` system catalog tables to see the accuracy.
```sql SQL theme={null}
SELECT correctly_classified
FROM sys.machine_learning_models a,
sys.support_vector_machine_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'circ1';
correctly_classified
----------------------
0.9579
Fetched 1 row
```
This model is slightly more accurate than the neural network classifier.
This example tries logistic regression.
```sql SQL theme={null}
CREATE mlmodel circ2 TYPE LOGISTIC REGRESSION ON (
SELECT x,
y,
label
FROM mldemo.circles
) options('metrics'->'true');
Modified 0 rows
SELECT correctly_classified
FROM sys.machine_learning_models a,
sys.logistic_regression_models b
WHERE a.id = b.machine_learning_model_id
AND NAME = 'circ2';
correctly_classified
----------------------
0.9028
Fetched 1 row
```
Logistic regression shows lower accuracy than the neural network model.
These classification models can handle non-numeric data.
## Naive Bayes
The first of these models is naive Bayes. This model can handle binary or multi-class classification and features of any data type.
By default, naive Bayes treats each feature as a discrete value. For example, if you assign features with values of `1`, `2`, `3`, and `4`, the model does not give any numeric significance to them. In this case, this model cannot predict the class for the sample with a feature value of `3.5` because that value is not explicitly assigned as a feature.
However, the naive Bayes model can define certain input features as continuous features. These should be numeric values. In this case, the naive Bayes model finds the best-fit normal distribution for that feature to do the probability calculations.
Naive Bayes models essentially use the probability rules of Bayes' Theorem to compute the most likely class based on the training data. The rules are only correct if the features are independent (uncorrelated). However, in practice, the models tend to work well with real-world data.
This example uses this simple table to demonstrate naive Bayes models.
```sql SQL theme={null}
SELECT * FROM mldemo.cars;
color type origin stolen
----------------------------------------------------------------------------------------------------------------------------------------------
yellow sports domestic false
yellow sports imported true
yellow suv imported false
red sports domestic false
yellow suv domestic false
red suv imported false
red sports domestic true
yellow suv imported true
red sports imported true
red sports domestic true
Fetched 10 rows
```
`color`, `type`, and `origin` are the input features, which are all strings. `true` and `false` are the class labels. In this case, all of the input features are discrete.
This example builds the naive Bayes model.
```sql SQL theme={null}
CREATE MLMODEL nb1 TYPE NAIVE BAYES ON (
SELECT color,
type,
origin,
stolen
FROM mldemo.cars
) options('metrics'->'true');
Modified 0 rows
```
This query examines the information in the `machine_learning_models` and `naive_bayes_models` system catalog tables for naive Bayes models.
```sql SQL theme={null}
SELECT NAME,
on_select,
num_arguments,
result_probability_table,
feature_result_matrix_table,
correctly_classified
FROM sys.machine_learning_models a,
sys.naive_bayes_models b
WHERE a.id = b.machine_le arning_model_id
AND NAME = 'nb1';
name on_select num_arguments result_probability_table feature_result_matrix_table correctly_classified
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
nb1 select color, "type", origin, stolen from user.nb_input 3 temp.rpt83581840700868656 temp.frm83581860860782808 0.8
Fetched 1 row
```
In the model, the `correctly_classified` value indicates the accuracy is 80 percent, meaning just two rows are classified incorrectly. The two table names in the `temp` schema hold all the necessary data for executing the model as a function.
This query calls the model to classify new data.
```sql SQL theme={null}
SELECT nb1('red', 'suv', 'domestic') AS prediction;
prediction
-----------
false
Fetched 1 row
```
Here is another example with a different data set to show how continuous features work with naive Bayes models.
```sql SQL theme={null}
SELECT * FROM mldemo.golf;
humidity play
--------------------------
70 false
75 true
86 true
95 false
80 true
85 false
96 true
90 true
91 false
90 false
70 true
70 true
80 true
65 true
Fetched 14 rows
```
In this case, the only input feature is a continuous feature, but you can have multiple continuous features, and you can have a mix of continuous and discrete features.
To build a naive Bayes model over this data, you must set which input features are continuous in the model.
```sql SQL theme={null}
CREATE MLMODEL nb2 TYPE NAIVE BAYES ON (
SELECT *
FROM mldemo.golf
) options('continuousFeatures'->'1', 'metrics'->'true');
Modified 0 rows
```
The `continuousFeatures` option is a comma-separated list (no spaces) of input column indexes that are continuous. Indexes start at 1.
This query checks the `correctly_classified` value in the `machine_learning_models` and `naive_bayes_models` system catalog tables.
```sql SQL theme={null}
SELECT correctly_classified
FROM sys.machine_learning_models a,
sys.naive_bayes_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'nb2';
correctly_classified
----------------------
0.7142857142857143
Fetched 1 row
```
Naive Bayes is a powerful classification algorithm, but it operates as a black box, making it hard to assess how it makes classification decisions.
For details, see [Naive Bayes Classification](/classification-models#naive-bayes-classification).
## Decision Trees
Unlike naive Bayes, the decision tree model allows you to see how the model works and makes its decisions.
A decision tree branches based on the value of a single feature, while the leaves of the tree are the output classes. For SQL syntax, this model uses multiple nested `CASE` statements. You can examine the whole nested `CASE` statement that defines the model, but it might be very long.
The decision tree model in Ocient has limited support for continuous features. The model finds the average value of the feature and allows a two-way branch based on whether the value is lower or higher than the average.
Creating a decision tree model is exactly like a naive Bayes model, except with a different type. Decision trees also use the `continuousFeatures` option, which works the same way.
These decision tree examples use the same data sets as the naive Bayes examples.
```sql SQL theme={null}
CREATE MLMODEL dt1 TYPE DECISION TREE ON (
SELECT color,
"type",
origin,
stolen
FROM mldemo.cars
) options('metrics'->'true');
Modified 0 rows
```
This query examines the `machine_learning_models` and `decision_tree_models` system catalog tables.
```sql SQL theme={null}
SELECT correctly_classified
FROM sys.machine_learning_models a,
sys.decision_tree_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'dt1';
correctly_classified
----------------------
0.8
Fetched 1 row
```
This model has the same 80 percent accuracy as the naive Bayes model.
This query examines the `CASE` statement that defines the model.
```sql SQL theme={null}
SELECT case_statement
FROM sys.machine_learning_models a,
sys.decision_tree_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'dt1';
case_statement
---------------------------------------------
CASE
WHEN x3 = cast('domestic' as CHAR) THEN CASE
WHEN x1 = cast('red' as CHAR) THEN CASE
WHEN x2 = cast('sports' as CHAR) THEN cast('true' as BOOLEAN)
ELSE cast('false' as BOOLEAN)
END
WHEN x1 = cast('yellow' as CHAR) THEN cast('false' as BOOLEAN)
ELSE cast('false' as BOOLEAN)
END
WHEN x3 = cast('imported' as CHAR) THEN CASE
WHEN x2 = cast('suv' as CHAR) THEN CASE
WHEN x1 = cast('red' as CHAR) THEN cast('false' as BOOLEAN)
WHEN x1 = cast('yellow' as CHAR) THEN cast('true' as BOOLEAN)
ELSE cast('false' as BOOLEAN)
END
WHEN x2 = cast('sports' as CHAR) THEN cast('true' as BOOLEAN)
ELSE cast('false' as BOOLEAN)
END
ELSE cast('false' as BOOLEAN)
END
Fetched 1 row
```
Like with the naive Bayes model, the decision tree model can predict new data.
```sql SQL theme={null}
SELECT dt1('red', 'suv', 'domestic') AS prediction;
prediction
-----------
false
Fetched 1 row
```
This example builds a model over the golfing data.
```sql SQL theme={null}
CREATE mlmodel dt2 TYPE DECISION TREE ON (
SELECT *
FROM mldemo.golf
) options('continuousFeatures'->'1', 'metrics'->'true');
Modified 0 rows
```
Review the `machine_learning_models` and `decision_tree_models` system catalog tables to see the accuracy of this model.
```sql SQL theme={null}
SELECT correctly_classified
FROM sys.machine_learning_models a,
sys.decision_tree_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'dt2';
correctly_classified
----------------------
0.7142857142857143
Fetched 1 row
```
Again, the decision tree shows similar accuracy to the naive Bayes model.
## Related Links
[Machine Learning Model Functions](/machine-learning-model-functions)
[Classification Models](/classification-models)
# Classification Models
Source: https://docs.ocient.com/classification-models
Train and use OcientML classification models such as decision trees, random forests, and naive Bayes in SQL to categorize data and detect patterns.
supports classification models that involve understanding and grouping large data sets into preset categories or subpopulations. With the help of pre-classified training data sets, machine learning classification models leverage various algorithms to classify future data sets into respective and relevant categories.
To create the model, use the `CREATE MLMODEL` syntax. For details, see [CREATE MLMODEL](/machine-learning-model-functions).
Model option names are case-sensitive.
## K-Nearest Neighbors Classification
Model Type: `K NEAREST NEIGHBORS`
K-nearest neighbors (KNN) is a classification algorithm, where the first `N - 1` inputs are the features, which must be numeric. The last input column is a label, which can be any data type.
There is no training step for KNN. Instead, when you create the model, the model saves a copy of all input data to a table, so that when the model is executed in a later SQL statement, a snapshot of the data the model is supposed to use is available. You can override both the weight function and the distance function.
The system validates the `weight` and `distance` options during prediction time. If the values are invalid, the model throws an error during this time.
### **Model Options**
#### Required
`k` — This option must be a positive integer that specifies how many closest points to use for classifying a new point.
#### Optional
`distance` — If you specify this option, the value must be a function in SQL syntax for calculating the distance between a point used for classification and points in the training data set. This function should use the variables x1, x2, … for the 1st, 2nd, … features in the training data set, and p1, p2, … for the features in the point for classification. If you do not specify this option, the option defaults to the Euclidean distance.
`metrics` — If you set this option to `true`, the model calculates the percentage of samples that are correctly classified by the model and saves this information in a catalog table. The default value is `false`.
`normalize` — If you set this option to `true`, the model automatically computes the mean and standard deviation of each feature and uses them to normalize the data during training. The default value is `true`.
`weight` — If you specify this option, the value must be a function in SQL syntax for calculating the weight of a neighbor. The function should use the variable d for distance. By default, the distance is set to 1.0/(d+0.1), thus avoiding division by zero on exact inputs and still allowing neighbors to have some influence.
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
### **Execute the Model**
Create a KNN model with `8` closest points for classification and distance function `power(x1 - p1, 2) + power(x2 - p2, 2) + power(x3 - p3, 2)`.
```sql SQL theme={null}
CREATE MLMODEL my_model
TYPE K NEAREST NEIGHBORS
ON (
SELECT
x1,
x2,
x3,
y1
FROM public.my_table
)
options(
'k' -> '8',
'distance' -> 'power(x1 - p1, 2) + power(x2 - p2, 2) + power(x3 - p3, 2)'
);
```
After you create the model, you can see its details by querying the `sys.machine_learning_models` and `sys.machine_learning_model_options` system catalog tables.
When you execute the model, the model executes with `N - 1` features as input and returns a label. The model chooses the label from the class with the highest score. The model scores classes by summing the weights from the nearest k points in the training data.
```sql SQL theme={null}
SELECT my_model(x1, x2, x3) FROM my_table;
```
After you execute a model, you can find the details about the execution results in the `sys.k_nearest_neighbors_models` system catalog table.
For details, see the description of the associated system catalog tables in the Machine Learning section in the [System Catalog](/system-catalog#page-title).
## Naive Bayes Classification
Model Type: `NAIVE BAYES`
Naive Bayes is a classification algorithm. The input is `N - 1` feature columns, and the last column is a label column. All columns can be any data type. The label column must be discrete. The feature columns can be discrete or continuous. When you use continuous feature columns, you must specify which columns are continuous (see options).
Naive Bayes works by assuming that all features are equally important in the classification and that there is no correlation between features. With those assumptions, the algorithm computes all frequency information and saves it in three tables that you create using SQL `SELECT` statements.
### **Model Options**
#### Optional
`metrics` — If you set this option to `true`, the model calculates the percentage of samples correctly classified by the model and saves this information in a catalog table. This option defaults to `false`.
`continuousFeatures` — If you specify this option, the value must be a comma-separated list of the feature indexes that are continuous numeric variables. Indexes start at 1.
`normalize` — If you set this option to `true`, the model automatically computes the mean and standard deviation of each feature and uses them to normalize the data during training. Defaults to `true`.
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
### **Execute the Model**
Create a Naive Bayes model with feature indexes `1,3`.
```sql SQL theme={null}
CREATE MLMODEL my_model
TYPE NAIVE BAYES
ON (
SELECT
x1,
x2,
x3,
y1
FROM public.my_table
)
options(
'continuousFeatures' -> '1,3'
);
```
After you create the model, you can see its details by querying the `sys.machine_learning_models` and `sys.machine_learning_model_options` system catalog tables.
When you execute the model, you specify `N - 1` feature input arguments, and the model returns the most likely class. The returned class is based on computing the class with the highest probability, given prior knowledge of the feature values. In other words, the class `y` has the highest value of `P(y | x1, x2, …, xn)`.
```sql SQL theme={null}
SELECT my_model(col1, col2, col3) FROM my_table;
```
After you execute a model, you can find the details about the execution results in the `sys.naive_bayes_models` system catalog table.
For details, see the description of the associated system catalog tables in the Machine Learning section in [System Catalog](/system-catalog).
## Decision Tree
Model Type: `DECISION TREE`
The decision tree is a classification model. The first `N - 1` input columns are features and can be any data type. All non-numeric features must be discrete and contain no more than the configured `distinctCountLimit` number of unique values. This limit is in place to prevent the internal model representation from growing too large. Numeric features are discrete by default and have the same limitation on the number of unique values, but they can be marked as continuous with the `continuousFeatures` option. For continuous features, the model builds the decision tree by dividing the values into two ranges instead of using discrete, unique values. The last input column is the label and can be any data type.
When you create the model, you specify all features first, and then specify the label as the last column in the result set.
You can use secondary indexes on discrete feature columns to greatly speed up the training of a decision tree model.
supports a similar tree model for regression. For details, see [Regression Tree](/regression-models#regression-tree).
### **Model Options**
#### Optional
`continuousFeatures` — If you set this option, the value must be a comma-separated list of the feature indexes that are continuous numeric variables. Indexes start with 1. In the default state, the model considers no features as continuous.
`distinctCountLimit` — If you set this option, the value must be a positive integer. This value sets the limit for how many distinct values a non-continuous feature and the label can contain. This option defaults to 256.
`doPrune` — If you set this option to `true`, the model uses Pessimistic Error Pruning (PEP) to prune the tree after training. This option defaults to `false`.
`featureArrayElements` — If you set this option, the value must be a comma-separated list of the feature indexes. If you set the `featureArray` option to `true`, this list determines the elements of the arrays to use for training. By default, the model uses all elements.
`maxCellsToFetch` — If you set this option, the value must be a positive integer. Controls the chunking behavior when fetching feature values during model training. The limit represents the maximum number of data cells (calculated as number of columns × number of rows) that can be fetched in a single operation, not a byte limit. When the expected data size exceeds this threshold, the algorithm switches to database-based processing using SQL queries instead of in-memory processing. This value defaults to 33,554,432 cells (calculated as 32 \* 1024 \* 1024).
`maxDepth` — If you set this option, the value must be a positive integer. This value sets the maximum allowable depth of the decision tree (the maximum number of features to split on). The default is unspecified, which means there is no maximum depth.
`maxRows` — If you set this option, the value must be a positive integer. This option limits the number of rows used for model training by creating a snapshot table with only the specified number of rows from the input query. This option cannot be used with `noSnapshot -> true` (attempting to set both results in an `invalid argument` error during model creation). When this option is unspecified, the model trains using all rows from the input query.
`maxThreads` — If you set this option, the value must be a positive integer. This value indicates the maximum number of parallel threads to use while the model trains. The default value is 2.
`metrics` — If you set this option to `true`, the model also calculates the percentage of samples correctly classified by the model and saves this information in a catalog table. This option defaults to `false`.
`noSnapshot` — If you set this option to `true`, the database does not create an intermediate table that stores the result of the specified SQL statement, which the model uses for training. This option defaults to `false`. In this case, the database creates and uses the intermediate table. Setting this option to `true` is useful when the training set is fixed. If the training set is a table with modifications, set this option to `false` as the decision tree trainer uses different data sets in different parts of the tree. Likewise, if the training set consists of a query that returns 100 rows, then set this option to `false` because there is no guarantee that running that query twice generates the same 100 rows each time.
`numSplits` — If you set this option, the value must be an integer greater than 1. This value sets the maximum number of binary branches a continuous feature can consider. The default value is 32.
`ROCNumSamples` — If you set the option, you must also set the `metrics` option. This positive integer indicates the number of samples for the model to use for the area under the ROC curve. The default value is 10.
`skipLimitCheck` — If you set this option to `true`, the model skips cardinality checks that throw errors when columns have too many values. The limit that this option checks is the same one that is specified by the `distinctCountLimit` option. This option defaults to `false`.
`weighted` — If you set this option, the model considers weights for labels. If you set this option value to `true`, you must specify an additional column as a `double` in the training data for label weights. Rows with the same labels must have the same weights. If you set this value to `auto`, the model calculates weights automatically by weighting each label according to the ratio of the count of the most frequent label to the count of the specified label. As a result, the most frequent label has a weight of `1.0`, and the other label weights are higher. This option defaults to `false`, which means all labels have equal weight.
`splitMetric` — Controls which function is used to evaluate the quality of a split during tree construction. Supported options are:
* `gini_impurity` (default) — Measures impurity based on class distributions.
* `weighted_f1` — Uses class-frequency–weighted F1 score to guide splits.
`enableResplits` — A Boolean value that determines if the tree can reuse the same continuous feature multiple times along a single branch (e.g., split on `x1 < 7` and later `x1 < 3`). This can capture more complex, range-specific relationships. If unspecified, this value defaults to true, meaning continuous features remain available for additional splits after use, allowing the tree to create more complex decision boundaries. When set to false, the model marks continuous features as exhausted after their first use, and they cannot be used again in subsequent splits in the same tree.
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
### **Execute the Model**
Create a decision tree model with feature indexes `1,3`.
```sql SQL theme={null}
CREATE MLMODEL my_model
TYPE DECISION TREE ON (
SELECT
c1,
c2,
c3,
y1
FROM public.my_table
)
options(
'continuousFeatures' -> '1,3'
);
```
After you create the model, you can see its details by querying the `sys.machine_learning_models` and `sys.machine_learning_model_options` system catalog tables.
When you execute the model, you must specify the `N - 1` features as parameters. The model returns the expected label.
```sql SQL theme={null}
SELECT my_model(col1, col2, col3) FROM my_table;
```
After you execute a model, you can find the details about the execution results in the `sys.decision_tree_models` system catalog table.
For details, see the description of the associated system catalog tables in the Machine Learning section in [System Catalog](/system-catalog).
## Random Forest
Model Type: `RANDOM FOREST`
Random forest is a classification model consisting of multiple decision trees. The result consists of the most common label among the tree results and an array of pairs of labels and their frequencies, sorted in descending order by frequency.
The model breaks ties in various ways depending on the type of label. For strings, the model uses lexicographic order (reverse of the usual alphabetic order), so `C` comes before `A`, for example. For Booleans, the model chooses `true` before `false`. For numeric types, the model chooses the largest number first.
When you call the model to make classification predictions, you can optionally use soft voting by adding an extra Boolean argument to the statement, e.g., `house(x, y, true)`. This extra argument must be a Boolean literal, either `true` (soft voting) or `false` (hard voting). If you do not specify this value, the default value is `false` (hard voting).
In soft voting, each decision tree reports a list of possible results and their confidence factors. The random forest model adds the confidence factors from the decision trees and normalizes them to add up to 1.0. The model sorts the results by descending confidence, then by descending values.
In hard voting, the model does not account for confidence factors. Each decision tree makes its own class prediction as a vote. The model selects the prediction with the most votes from the trees.
### **Model Options**
#### Required
`numChildren` — Number of child decision trees.
#### Optional
`bootstrap` — If you set this option to `true`, the model uses bootstrap sampling with replacement, meaning each tree in the random forest is trained on a random subset of the data (either the `rowsPerChild` or `fractionSelected` value sets the exact number of rows), and the same row can appear multiple times in each tree. If you set this option to `false`, this option does not use replacement, meaning each row can appear at most once per tree. The default value is `false`.
`continuousFeatures` — If you set this option, the value must be a comma-separated list of the feature indexes that are continuous numeric variables. Indexes start with 1.
`distinctCountLimit` — If you set this option, the value must be a positive integer. This value limits how many distinct values a non-continuous feature and the label can contain. The default value is 256.
`featureSubsetStrategy` — If you set this option, the model passes this option directly to the child decision trees to specify how many features each tree should consider at each split from the still-available features. When this value is higher, the model has higher accuracy and lower variance, but it takes longer to train.
You can specify this option either as an integer (e.g., `4`, meaning consider up to four features at each split) or one of three string values:
* `all` — Each tree checks every feature.
* `sqrt` — Each tree checks up to the square root of the total number of features.
* `one-third` — Each tree checks up to one-third of the total number of features.
The default value is `all`.
`fractionSelected` — The proportion of rows the model uses to train each decision tree. The value is a `double` that must be in the interval (0, 1]. You cannot set this option if you also set the `rowsPerChild` option to a positive value. The default behavior is that the model uses all available rows.
`inputsPerChild` — Number of features used to create each child decision tree. The default value is the number of features you specify for the forest divided by 3 and rounded up.
`maxCellsToFetch` — If you set this option, the value must be a positive integer. Controls the chunking behavior when fetching feature values during model training. The limit represents the maximum number of data cells (calculated as number of columns × number of rows) that can be fetched in a single operation, not a byte limit. When the expected data size exceeds this threshold, the algorithm switches to database-based processing using SQL queries instead of in-memory processing. This value defaults to 33,554,432 cells (calculated as 32 \* 1024 \* 1024).
`maxChildThreads` — An integer representing the maximum number of threads each child decision tree can use. If you do not specify this option, each child decision tree uses at most one thread, the default for decision trees.
`maxDepth` — If you set this option, the value must be a positive integer. This value sets the maximum allowable depth of the decision tree. The default value is 3.
`maxThreads` — The maximum number of parallel threads to use while the model trains decision trees. This value must be a positive integer. The default value is 16.
`metrics` — If you set this option to `true`, the model also calculates the percentage of samples that are correctly classified by the model for the random forest and saves this information in a catalog table. This option is always set to `false` for the child trees.
`noSnapshot` — If you set this option to `true`, the data source must not change. In this case, the database does not create an intermediate table that stores the result of the specified SQL statement, which the model uses for training a random forest. Child decision trees always have this option set to `true`, so the database does not create a separate intermediate table for each decision tree. The default value is `false`. Setting this option to `true` is useful when the training set is fixed. If the training set is a table with modifications, set this option to `false` as the decision tree trainer uses different data sets in different parts of the tree. Likewise, if the training set consists of a query that returns 100 rows, then set this option to `false` because there is no guarantee that running that query twice generates the same 100 rows each time.
`requiredFeatures` — A comma-separated list of integers as strings representing specific features where the first feature has the value `1`. The model uses these features in every decision tree in the forest. The default behavior is that the decision tree in the forest can train on any feature that is in the list.
`rowsPerChild` — If you set this option to a positive integer, the number represents the number of rows (from a random sample) to use for each decision tree. If you set this option to 0, each child uses all available rows. The default value is 0. You cannot set this option to a positive value if you also set the `fractionSelected` option.
`skipLimitCheck` — If you set this option to `true`, the model skips cardinality checks that throw errors when columns have too many values. The limit that this option checks is the same one that is specified by the `distinctCountLimit` option. The default value is `false`.
`weighted` — If you set this option, the model considers weights for labels. If you set this option value to `true`, you must specify an additional column as a `double` in the training data for label weights. Rows with the same labels must have the same weights. If you set this value to `auto`, the model calculates weights automatically by weighting each label according to the ratio of the count of the most frequent label to the count of the specified label. As a result, the most frequent label has a weight of `1.0`, and the other label weights are higher. This option defaults to `false`, which means all labels have equal weight.
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
### **Execute the Model**
Create a random forest model with four child decision trees and two features randomly chosen by the model for each tree. The `training_table` table contains the training data set. Collect metrics for the model execution by setting the `metrics` option to `true`.
```sql SQL theme={null}
CREATE MLMODEL test_model
TYPE RANDOM FOREST
ON (
SELECT *
FROM public.training_table
)
options(
'numChildren' -> '4',
'inputsPerChild' -> '2'
);
```
After you create the model, you can see its details by querying the `sys.machine_learning_models`, `sys.machine_learning_model_options`, and `sys.random_forest_models` system catalog tables.
Execute this model using three columns `a`, `b`, and `c`, from `large_table` table that contains the whole data set.
```sql SQL theme={null}
SELECT test_model(a, b, c) FROM large_table;
```
Optionally, you can execute the model using soft voting by including an extra Boolean argument.
```sql SQL theme={null}
SELECT test_model(a, b, c, true) FROM large_table;
```
The output of the model is a tuple containing the most common label as the first element. The second element is an array of tuples, where the first element is the label and the second is the frequency. The model sorts the array by frequency from highest to lowest, where the sum of frequencies is 1. When two labels have the same frequency, the model breaks the tie according to lexicographic order.
To retrieve the most common label, use `[]` with an index of 1, `[1]`, for example, `test_model(a,b,c)[1]`.
After you execute a model, you can find the results in the output of the model function execution.
For details, see the description of the associated system catalog tables in the Machine Learning section in [System Catalog](/system-catalog).
## Logistic Regression
Model Type: `LOGISTIC REGRESSION`
This model fits a logistic curve to the data across any number of classes greater than one.
The first `N - 1` inputs are features and must be numeric. Features can be one-hot encoded. The last input column is the class or label. You must have at least one non-NULL label in the result set for model creation. The model best fits the logistic curve using a negative log likelihood loss function. The model uses an algorithm that is a combination of particle swarm optimization, line search, and genetic algorithms to find the best-fit parameters.
### **Model Options**
#### Optional
`metrics` — If you set this option to `true`, the model calculates the percentage of samples that are correctly classified by the model and saves this information in the `sys.logistic_regression_models` system catalog table. This option defaults to `false`.
`normalize` — If you set this option to `true`, the model uses auto-scaling to compute the mean and standard deviation of each input feature to normalize data during training, making training more numerically stable. The model then unscales parameters so the persisted model operates in the original units. This option defaults to `true`.
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`numEpochs` — An `INTEGER` value representing the maximum number of epochs, or full passes during training through the entire data set. This value must be positive.
If you do not specify this value, the default is 20.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
### **Execute the Model**
Create a logistic regression model. Collect metrics for the model execution by setting the `metrics` option to `true`.
```sql SQL theme={null}
CREATE MLMODEL my_model
TYPE LOGISTIC REGRESSION
ON (
SELECT
x1,
x2,
x3,
y1
FROM public.my_table
)
options(
'metrics' -> 'true'
);
```
After you create the model, you can see its details by querying the `sys.machine_learning_models` and `sys.machine_learning_model_options` system catalog tables.
When you execute this model after training, you must specify the features as input and the label as the output. The label can be any data type.
```sql SQL theme={null}
SELECT my_model(col1, col2, col3) FROM my_table;
```
After you execute a model, you can find the details about the execution results in the `sys.logistic_regression_models` system catalog table.
For details, see the description of the associated system catalog tables in the Machine Learning section in the [System Catalog](/system-catalog).
## Support Vector Machine
Model Type: `SUPPORT VECTOR MACHINE`
Support Vector Machine (SVM) essentially finds a hypersurface (the hypersurface is a curve in 2-dimensional space) that correctly splits the data into any number of classes greater than one and maximizes the margin around the hypersurface. By default, SVM finds a hyperplane to split the data (the hyperplane is a straight line in 2-dimensional space). SVM uses a hinge loss function to balance the two objectives of finding a hyperplane with a wide margin while minimizing the number of incorrectly classified points.
The first `N - 1` input columns are the features and must be numeric. The last column is the label and can be any arbitrary type. You must have at least one non-NULL label in the result set for model creation.
### **Model Options**
#### Optional
`metrics` — If you set this option to true, the model also calculates the percentage of samples that are correctly classified by the model and saves this information in a catalog table. This option defaults to false.
`regularizationCoefficient` — If you specify this option, the value must be a valid floating-point number. This option is used to control the balance of finding a wide margin and minimizing incorrectly classified points in the loss function. When this value is larger (and positive), it makes having a wide margin around the hypersurface more important relative to the incorrectly classified points. Because of how Ocient implements SVM, the values for this parameter are likely different from the values used in other common SVM implementations. This option defaults to 1.0 / 1000000.0.
`functionN` — By default, SVM uses a linear kernel. If you use a different kernel, you must provide a list of functions that are summed together, just like with linear combination regression. You must specify the first function using a key named 'function1'. Subsequent functions must use keys with names that use subsequent values of N. You must specify functions in SQL syntax and use the variables x1, x2, …, xn to refer to the 1st, 2nd, and nth independent variables, respectively. You can specify the default linear kernel as: 'function1' → 'x1', 'function2' → 'x2', and so on. The model always adds a constant term equivalent to 'functionN' → '1.0' that you do not need to specify explicitly.
`normalize` — If you set this option to `true`, the model automatically computes the mean and standard deviation of each feature and uses them to normalize the data during training. Defaults to `true`.
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`numEpochs` — An `INTEGER` value representing the maximum number of epochs, or full passes during training through the entire data set. This value must be positive.
If you do not specify this value, the default is 200.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
### **Execute the Model**
Create a support vector machine model.
```sql SQL theme={null}
CREATE MLMODEL my_model
TYPE SUPPORT VECTOR MACHINE ON (
SELECT
c1,
c2,
c3,
y1
FROM public.my_table
);
```
After you create the model, you can see its details by querying the `sys.machine_learning_models` and `sys.machine_learning_model_options` system catalog tables.
When you execute the model, the `N - 1` features must be passed as parameters. The model returns the expected label.
```sql SQL theme={null}
SELECT my_model(col1, col2, col3) FROM my_table;
```
After you execute a model, you can find the details about the execution results in the `sys.support_vector_machine_models` system catalog table.
For details, see the description of the associated system catalog tables in the Machine Learning section in the [System Catalog](/system-catalog).
## Gradient Boosted Trees
Model Type: `GRADIENT BOOSTED TREES`
Gradient Boosted Trees (GBT) is an ensemble machine learning algorithm that builds a sequence of decision trees where each new tree is trained to correct the prediction errors of the previous trees. Unlike the Random Forest model, which creates trees independently in parallel, GBT uses a sequential approach based on gradient descent optimization, where each tree learns to predict the residual errors (gradients) of the current ensemble. This iterative error-correction process allows the model to capture complex, non-linear patterns by progressively refining predictions through multiple weak learners.
The algorithm supports both regression and classification tasks through different loss functions (use the `lossFunction` option to toggle whether the model performs regression or classification tasks). For regression with squared error loss, trees directly predict residual errors, while classification with logistic loss maintains raw scores transformed through sigmoid or softmax functions.
### Model Options
#### Required
`numChildren` — An INTEGER value representing the total number of trees to build sequentially. Each tree learns to correct the errors of the previous trees.
`learningRate` — A DECIMAL value between 0.0 and 1.0 that tunes how much the model learns from each successive child.
#### Optional
`lossFunction` — A string value that determines how the model calculates prediction errors and what type of problem it solves. Accepted values include:
* `'squared_error'` — Configures the model for regression tasks. Calculates errors as the squared difference between predicted and actual values. Use this for predicting continuous numeric values (e.g., prices, temperatures, quantities). The target column must contain numeric values. This is the default value.
* `'log_loss'` — Configures the model for classification tasks. This model uses logistic loss to calculate prediction errors for probability-based predictions.
`fractionSelected` — A DECIMAL value greater than 0.0 and less than or equal to 1.0 that specifies what fraction of the training rows to randomly select for each boosting iteration. When you specify a value, the algorithm uses `CEIL(fractionSelected * totalRows)` per iteration. If you do not specify this value, the model uses all rows in their original order.
`inputsPerChild` — An INTEGER greater than or equal to 1 that specifies the number of input features each boosting tree should use. This value cannot exceed the number of input features available in the data set. When you specify this value, the algorithm deterministically cycles through pre-enumerated feature subsets to ensure each tree uses exactly this many features. When you do not specify this value, the model uses all available features for each tree.
`maxDepth` — A positive INTEGER value that represents the maximum allowable depth of the decision trees. The default value is 3.
`maxThreads` — A positive INTEGER value that sets the maximum number of parallel threads to use for training each child decision tree. Parallel threads do not affect the sequential method of training each tree. The default value is 16.
`enableResplits` — A Boolean value that determines if the tree can reuse the same continuous feature multiple times along a single branch (e.g., split on `x1 < 7` and later `x1 < 3`). This action can capture more complex, range-specific relationships. If you do not specify this value, the default value is `true`, meaning continuous features remain available for additional splits after use, which allows the tree to create more complex decision boundaries. When you set this value to `false`, the model marks continuous features as exhausted after their first use, and the model cannot use these features again in subsequent splits in the same tree.
`resplitDepth` — An INTEGER value that sets the maximum depth at which tree nodes can be re-split during optimization. Controls how deep the algorithm searches for better split points. If you do not specify this value, the default value is 6.
`resplitThreshold` — A DECIMAL value that sets the minimum improvement threshold required to trigger a re-split operation. Lower values (e.g., 0.01) allow more aggressive re-splitting but can increase training time. Higher values (e.g., 1.0) require larger improvements to trigger re-splits. If you do not specify this value, the default value is 0.1.
`maxCellsToFetch` — An INTEGER value that determines the memory threshold to switch from training with system memory to training with SQL queries in the database. In-memory training is generally faster, but is limited by the available SQL Node memory. If the size of a training data subset exceeds this value, then the system performs training operations using SQL queries. The default value is 33,554,432 (calculated as `32 * 1024 * 1024`).
`metrics` — A Boolean value. If you set this value to `true`, the system calculates and stores final model metrics (`R²/RMSE` for regression or `Accuracy/LogLoss` for classification) on the training data.
`featureArray` — A Boolean value. If you set this value to `true`, the model expects all input features to be in a single ARRAY column instead of separate columns.
`continuousFeatures` — A set of INTEGER values that specify the input feature columns that the model should treat as continuous numeric variables for optimal tree splitting. The value must be a comma-separated list of feature column indexes (starting with 1) that correspond to numeric columns in your `SELECT` SQL statement, excluding the target column. For example, `'continuousFeatures' -> '1,2'` would treat the first and second columns of your `SELECT` statement as continuous. If you do not specify this value, the model treats all features as categorical, which can impair results for numeric columns like prices, measurements, or scores.
### Execute the Model
This example creates a Gradient Boosted Trees classifier to predict whether a customer stops using a service. The model trains on four input features (`tenure_months`, `monthly_charges`, `total_charges`, `support_tickets`) to predict the target variable (`churn_label`), filtering out any records with missing labels to ensure clean training.
The model uses these options:
* `'numChildren' -> '100'` — Builds a sequence of 100 weak learners (regression trees). Each tree learns to correct the classification residuals (logistic loss) of all previous trees. A higher value can capture complex patterns, and you should pair it with an appropriate learning rate.
* `'learningRate' -> '0.1'` — Scales the contribution of each new tree by 10 percent, balancing convergence speed and generalization. This value represents a small learning rate, making training more conservative and stable.
* `'lossFunction' -> 'log_loss'` — Configures the model for classification through logistic loss. If you do not specify this value, the default value is `'squared_error'` (regression), so explicitly setting `'log_loss'` is mandatory for classifiers.
```sql SQL theme={null}
CREATE MLMODEL churn_gbt_classifier
TYPE GRADIENT BOOSTED TREES
ON (
SELECT
tenure_months,
monthly_charges,
total_charges,
support_tickets,
churn_label
FROM customer_training
WHERE churn_label IS NOT NULL
)
OPTIONS (
'numChildren' -> '100',
'learningRate' -> '0.1',
'lossFunction' -> 'log_loss'
);
```
Call the trained model in a `SELECT` query, passing in the feature columns as arguments.
```sql SQL theme={null}
SELECT
customer_id,
churn_gbt_classifier(
tenure_months,
monthly_charges,
total_charges,
support_tickets
)[1] AS predicted_label,
churn_gbt_classifier(
tenure_months,
monthly_charges,
total_charges,
support_tickets
)[2] AS class_probabilities
FROM customer_scoring
WHERE tenure_months IS NOT NULL
AND monthly_charges IS NOT NULL
AND total_charges IS NOT NULL
AND support_tickets IS NOT NULL;
```
For classification, the model returns a tuple of:
* `element [1]` — The predicted class label
* `element [2]` — An array of (`class_label`, `probability`) pairs
For the output of the model, see the `sys.gradient_boosted_trees_models` system catalog table.
## Related Links
[Clustering and Dimension Reduction Models](/clustering-and-dimension-reduction-models)
[Other Models](/other-models)
[Machine Learning Models](/machine-learning-models)
#
# Cluster and Node Management
Source: https://docs.ocient.com/cluster-and-node-management
Manage clusters and nodes in an Ocient System, including adding, removing, restarting, monitoring, and replacing storage, foundation, and SQL nodes.
Cluster and Node Management commands allow administrators to manage storage clusters, create and manage storage spaces, create and manage nodes, and apply configuration changes to nodes, clusters, or the overall system.
## CLUSTER
### CREATE CLUSTER
`CREATE CLUSTER` creates a new cluster in the current database. The cluster name must be distinct from the name of any existing tables in the database.
To create a cluster, the logged-in user must be a system-level user.
For details about creating clusters, see [Ocient Application Configuration](/ocient-application-configuration).
For Foundation clusters, if the system is configured with a single-cluster configuration, when you add a second Foundation cluster, the system automatically changes to a multi-cluster configuration. This change is irreversible and requires a full system restart to fully take effect.
**Syntax**
```sql SQL theme={null}
CREATE CLUSTER [ IF NOT EXISTS ] cluster_name ::=
TYPE [=] foundation
| PARTICIPANTS [=] (node_name1, node_name2, ...)
| STORAGESPACE [=] storage_space_name
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------- | ----------------- | -------------------------------------- |
| `cluster_name` | string | The name of the new cluster to create. |
#### Define Clusters ( `` )
You must include these configuration settings when you create a new cluster.
| **Configuration** | **Data Type** | **Description** |
| ----------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `TYPE` | string | The supported value is: `foundation` — Processes query operators and handles storage on the system. |
| `PARTICIPANTS` | string | A list of one or more node names included in the new cluster. The number of participant nodes in a cluster must be equal to or greater than the storage-space width. For details, see [CREATE STORAGESPACE](#create-storagespace). Adding more than the minimum number of participants to a cluster overprovisions the cluster and allows replacing or dropping participant nodes. Nodes cannot be assigned as participants to multiple clusters. |
| `STORAGESPACE` | string | The name of the storage space for the cluster. |
**Examples**
This example creates a Foundation cluster named `lts_cluster0` using the storage space named `my_storage_space` with three participant nodes.
```sql SQL theme={null}
CREATE CLUSTER lts_cluster0
TYPE=foundation
PARTICIPANTS=(node1,node2,node3)
STORAGESPACE=my_storage_space;
```
### DROP CLUSTER
`DROP CLUSTER` removes an existing cluster from the system.
To remove a cluster, you must be a system-level user.
**Syntax**
```sql SQL theme={null}
DROP CLUSTER [ IF EXISTS ] cluster_name
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------- | ----------------- | -------------------------------------------- |
| `cluster_name` | string | The name of the specified cluster to remove. |
**Example**
This example removes an existing cluster named `lts_cluster0`.
```sql SQL theme={null}
DROP CLUSTER lts_cluster0;
```
### ALTER CLUSTER
#### ALTER CLUSTER ADD PARTICIPANTS
`ALTER CLUSTER ADD PARTICIPANTS` adds the specified nodes to an existing cluster in the system. This operation can overprovision the storage space if necessary.
For the system to recognize newly added nodes, you must restart the cluster. To do this, you can follow the steps in [Add Foundation Nodes](/expand-and-rebalance-system#add-foundation-nodes).
**Syntax**
```sql SQL theme={null}
ALTER CLUSTER [ IF EXISTS ] cluster_name
ADD PARTICIPANTS [=] ( node_name1 [,...] );
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------------- | ----------------- | ---------------------------------------------------- |
| `cluster_name` | string | The name of the specified cluster to alter. |
| `node_name1, [,...]` | string | The name of one or more nodes to add to the cluster. |
**Example**
This example adds the node `node3` to a cluster named `example_cluster`, which already contains `node1` and `node2`. Following this operation, `example_cluster` consists of three nodes.
```sql SQL theme={null}
ALTER CLUSTER example_cluster ADD PARTICIPANTS (node3);
```
#### ALTER CLUSTER DROP PARTICIPANTS
`ALTER CLUSTER DROP PARTICIPANTS` drops nodes from an existing cluster.
This SQL statement fails for a Foundation cluster if dropping the specified nodes brings the number of participants below the total width of the storage space associated with that cluster.
**Syntax**
```sql SQL theme={null}
ALTER CLUSTER [ IF EXISTS ] cluster_name
DROP PARTICIPANTS [=] ( node_name1 [,...] );
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------------- | ----------------- | ------------------------------------------------------- |
| `cluster_name` | string | The name of the specified cluster to alter. |
| `node_name1, [,...]` | string | The name of one or more nodes to drop from the cluster. |
**Example**
This example drops participant node `node3` from a cluster named `example_cluster`, which contains `node1`, `node2`, and `node3`. Following this operation, the participants in `example_cluster` consist of the nodes `node1` and `node2`.
```sql SQL theme={null}
ALTER CLUSTER example_cluster DROP PARTICIPANTS (node3);
```
#### ALTER CLUSTER ADD STORAGESPACE
`ALTER CLUSTER ADD STORAGESPACE` links an existing storage space to a storage cluster, enabling tables in that storage space to use the Foundation Nodes of that cluster. A storage space must be associated with at least one storage cluster before you can create tables in the space.
**Required Privileges**
To add a storage space to a cluster, you must have system-level privileges.
**Syntax**
```sql SQL theme={null}
ALTER CLUSTER [ IF EXISTS ] cluster_name ADD STORAGESPACE storage_space_name
```
| Parameter | Type | Description |
| -------------------- | ------ | -------------------------------------------------------------------- |
| `cluster_name` | string | The name of the storage cluster to modify. |
| `storage_space_name` | string | The name of an existing storage space to associate with the cluster. |
**Example**
This example adds the storage space `analytics_space` to the cluster `lts_cluster_0`.
```sql SQL theme={null}
ALTER CLUSTER lts_cluster_0 ADD STORAGESPACE analytics_space;
```
#### ALTER CLUSTER REMOVE STORAGESPACE
`ALTER CLUSTER REMOVE STORAGESPACE` detaches a storage space from a storage cluster. This detaching prevents the creation of new tables in that storage space within the cluster.
The statement fails if:
* Tables still exist in the storage space within the cluster. Remove all associated tables before detaching the storage space.
* The storage space is currently set as the system default storage space. Reset the default by using [ALTER SYSTEM SET DEFAULT STORAGESPACE](#alter-system-set-default-storagespace) before detaching the storage space.
* You are attempting to detach the core system storage space: `"systemStorageSpace"`.
**Required Privileges**
To detach a storage space from a cluster, you must have system-level privileges.
**Syntax**
```sql SQL theme={null}
ALTER CLUSTER [ IF EXISTS ] cluster_name REMOVE STORAGESPACE storage_space_name
```
| Parameter | Type | Description |
| -------------------- | ------ | --------------------------------------------------------- |
| `cluster_name` | string | The name of the storage cluster to modify. |
| `storage_space_name` | string | The name of the storage space to detach from the cluster. |
**Example**
This example detaches the storage space `analytics_space` from the cluster `lts_cluster_0`.
```sql SQL theme={null}
ALTER CLUSTER lts_cluster_0 REMOVE STORAGESPACE analytics_space;
```
#### ALTER CLUSTER ALTER CONFIG SET
`ALTER CLUSTER ALTER CONFIG SET` sets a configuration override for the configuration at the cluster scope. For an explanation of how configuration overrides work, see [Inspect the Current Configuration](/inspect-the-current-configuration).
If the specified path to the configuration setting does not exist, the system considers it as a new configuration and appends it to the collection of existing configurations. To reset a configuration override for a specific key, use the `RESET` keyword.
**Syntax**
```sql SQL theme={null}
-- To set a new configuration override:
ALTER CLUSTER [ IF EXISTS ] cluster_name
ALTER CONFIG SET string_definition [=] string_value [,...]
-- To reset a configuration override:
ALTER CLUSTER [ IF EXISTS ] clusterName
ALTER CONFIG RESET [ string_definition [,...] ]
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `cluster_name` | string | The name of the specified cluster to alter. |
| `string_definition` | string | The name of a configuration parameter to alter.
Contact support for details about altering configuration parameters. |
| `string_value` | string | The new value to set for the specified configuration parameter. |
**Examples**
This example alters the base configuration for cluster `cluster_name` and sets the certificate for all nodes to a certificate named `cert_name.crt`.
```sql SQL theme={null}
ALTER CLUSTER cluster_name
ALTER CONFIG SET 'certificateStore.cert' = 'cert_name.crt';
```
This example resets the certificate configuration for cluster `cluster_name`.
```sql SQL theme={null}
ALTER CLUSTER cluster_name
ALTER CONFIG RESET 'certificateStore.cert';
```
This example alters the configuration at the cluster scope for cluster `cluster_name` and service role `lts`.
```sql SQL theme={null}
ALTER CLUSTER cluster_name
ALTER CONFIG SET 'lts.numLevels' = '3';
```
#### ALTER CLUSTER ALTER LOG LEVEL SET
`ALTER CLUSTER cluster_name ALTER LOG LEVEL SET` sets the log level for a particular logger for all nodes in the provided cluster. For an explanation of how configuration overrides work, see [Inspect the Current Configuration](/inspect-the-current-configuration).
Syntax
```sql SQL theme={null}
-- To set a new configuration override:
ALTER CLUSTER cluster_name
ALTER LOG LEVEL SET [ [,...] ]
::=
{ 'ALL' | logger_name [=] logging_level }
-- To reset a configuration override:
ALTER CLUSTER cluster_name ALTER LOG LEVEL RESET [logger_name [, ...] ]
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------- | ----------------- | ------------------------------------------- |
| `cluster_name` | string | The name of the specified cluster to alter. |
**Logger Parameters (**``**)**
| **Configuration** | **Data Type** | **Description** |
| ----------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `logger_name` | string | Use `ALL` for the root logging configuration. Otherwise, the `logger_name` parameter can be any string specifying a logger name for all nodes in the provided cluster. |
| `logger_level` | string | The level of severity to be assigned to the `logger_name`. `logger_level` must be one of the following options: `'EDEBUG' \| 'DEBUG' \| 'VERBOSE' \| 'INFO' \| 'WARN' \| 'ERROR'` See the [Log Monitoring](/log-monitoring) page for more details on log levels. To reset a logger to the default log level (`INFO`), use the `RESET` keyword. |
**Examples**
This example alters the log level at the cluster scope. This sets the query log level for all nodes in the cluster to `DEBUG`.
```sql SQL theme={null}
ALTER CLUSTER cluster_name
ALTER LOG LEVEL SET 'query' = 'DEBUG';
```
This example resets the log level for the query logger for the entire cluster.
```sql SQL theme={null}
ALTER CLUSTER cluster_name
ALTER LOG LEVEL RESET 'query';
```
#### ALTER CLUSTER RENAME TO
Rename an existing cluster in the system.
**Syntax**
```sql SQL theme={null}
ALTER CLUSTER old_cluster_name RENAME TO new_cluster_name
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------------ | ----------------- | ------------------------------------------- |
| `old_cluster_name` | string | The name of the specified cluster to alter. |
| `new_cluster_name` | string | The new name to assign to the cluster. |
**Example**
This example renames an existing cluster named `lts-cluster-0` to `lts-cluster-1`.
```sql SQL theme={null}
ALTER CLUSTER "lts-cluster-0" RENAME TO "lts-cluster-1";
```
## STORAGESPACE
### CREATE STORAGESPACE
`CREATE STORAGESPACE` creates a new storage space. The name of the storage space must be distinct from the name of any existing storage spaces in the system.
To create a storage space, you must possess the `CREATE STORAGESPACE` privilege for the current system.
It is recommended that the total width of a production system be smaller than the number of Foundation Nodes in the cluster so that loading can continue even in the event of a node outage.
**Syntax**
```sql SQL theme={null}
CREATE STORAGESPACE [ IF NOT EXISTS ] storage_space_name
[ WIDTH [=] width_integer], [ PARITY_WIDTH[=] pw_integer ]
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `storage_space_name` | string | The name of the new storage space. A storage space name must begin with a letter followed by letters, numbers, and underscores. |
| `width_integer` | integer | The total number of nodes to use in each segment group as it is written to disk. Width cannot be greater than the number of nodes in the storage cluster. |
| `pw_integer` | integer | The number of parity coding bits to use for each segment group. This number must be less than `width`. The specified storage space can still complete queries even if nodes are disabled as long as the number of disabled nodes does not exceed the `parity_width`. For example, a storage space with a `width = 5 ` and a `parity_width = 2` can have up to two nodes become disabled, and the system still uses the three remaining nodes to execute queries. However, if a third node goes down, the system can no longer process query operations. |
**Example**
This example creates a new storage space named `ocient`.
```sql SQL theme={null}
CREATE STORAGESPACE ocient WIDTH = 10, PARITY_WIDTH = 2;
```
### DROP STORAGESPACE
`DROP STORAGESPACE` removes an existing storage space, along with all associated tables and views. The SQL statement fails if one or more storage clusters are linked to the storage space.
To remove a storage space, you must possess the `DROP STORAGESPACE` privilege for the storage space. Note that this action cannot be undone.
**Syntax**
```sql SQL theme={null}
DROP STORAGESPACE [ IF EXISTS ] storage_space_name [, ...]
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `storage_space_name` | string | The name of a storage space to drop. You can drop multiple storage spaces by specifying additional storage space names and separating each with commas. |
**Example**
Remove an existing storage space named `ocient_ss`.
```sql SQL theme={null}
DROP STORAGESPACE ocient_ss;
```
Remove multiple storage spaces.
```sql SQL theme={null}
DROP STORAGESPACE ocient_ss1, ocient_ss2;
```
### ALTER STORAGESPACE
`ALTER STORAGESPACE RENAME` renames an existing storage space.
To rename a storage space, the logged-in user must be a system-level user.
**Syntax**
```sql SQL theme={null}
ALTER STORAGESPACE [ IF EXISTS ] old_storage_space_name RENAME TO new_storage_space_name
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------------------ | ----------------- | --------------------------------------------- |
| `old_storage_space_name` | string | The name of a storage space to rename. |
| `new_storage_space` | string | The new name for the specified storage space. |
**Example**
To rename an existing storage space named `teststoragespace` to `storage-space-1`.
```sql SQL theme={null}
ALTER STORAGESPACE "teststoragespace" RENAME TO "storage-space-1";
```
## NODE
### DROP NODE
`DROP NODE` removes an existing node from the system.
A node cannot be removed from the system if it is still part of a cluster or one of the two remaining Administration Nodes.
**Syntax**
```sql SQL theme={null}
DROP NODE [ IF EXISTS ] node_name [, ...]
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `node_name` | string | The name of a node to drop. You can drop multiple nodes by specifying additional node names and separating each with commas. |
**Example**
Remove a node named `example_node`.
```sql SQL theme={null}
DROP NODE example_node;
```
Remove multiple nodes.
```sql SQL theme={null}
DROP NODE example_node1, example_node2;
```
### ALTER NODE
#### ALTER NODE RENAME TO
`ALTER NODE RENAME` renames an existing node.
To rename a node, you must be a system-level user.
Renaming a node can cause a mismatch between the name of the node and the hostname of the node. Furthermore, you have to update users and scripts to use the new name of the node. Use this statement only to reverse these situations that can arise naturally (for example, you must replace a node with a node that has a different name).
If you have a DNS configuration for the node, you must reconfigure the node address after renaming the node by using the [ALTER NODE SET ADDRESS](#alter-node-set-address) SQL statement.
**Syntax**
```sql SQL theme={null}
ALTER NODE [ IF EXISTS ] old_node_name RENAME TO new_node_name
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------- | ----------------- | ------------------------------------ |
| `old_node_name` | string | The name of a node to rename. |
| `new_node_name` | string | The new name for the specified node. |
**Example**
This example renames an existing node named `sql0` to `sql1`.
```sql SQL theme={null}
ALTER NODE sql0 RENAME TO sql1;
```
#### ALTER NODE ADD ROLE
`ALTER NODE ADD ROLE` adds a role to a node. Each node can have one or more roles that it performs.
To add a role, you must be a system-level user.
**Syntax**
```sql SQL theme={null}
ALTER NODE [ IF EXISTS ] node_name ADD ROLE [ IF NOT EXISTS ] ::=
{ sql | streamloader | operatorvm | admin | health }
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ---------------------------- |
| `node_name` | string | The name of a node to alter. |
#### **Node Roles (**``**)**
This table explains the supported roles for nodes.
| **Role** | **Description** | **Notes** |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `streamloader` | The `streamloader` role allows the node to continually import a large amount of data into the database. | When adding the `streamloader` role, the node must be restarted in order for the change to take effect. |
| `sql` | The `sql` role accepts a SQL statement, parses the statement, and compiles the statement. | You can remove this role only if there is at least one other SQL Node present. |
| `operatorvm` | The `operatorvm` role manages database query plans and executes queries. | Added or removed automatically together with the `sql` or `lts` role. |
| `lts` | The nodes with the `lts` role store data on disk in segments in a column-oriented fashion. The `lts` role is associated with the Foundation Nodes on the system. | Can only be added or removed by adding or removing the node as a participant in a Foundation cluster. |
| `admin` | The `admin` role accepts the administrative protocol and updates system metadata. | Can only be removed if there are at least two other Administrative Nodes. |
| `health` | A node with the `health` role is responsible for maintaining performance-related counters and statistics. | Present initially on every node. Cannot be removed. |
**Example**
Add SQL role to the node `sql1`.
```sql SQL theme={null}
ALTER NODE sql1 ADD ROLE sql;
```
#### ALTER NODE REMOVE ROLE
`ALTER NODE REMOVE ROLE` removes a role from a node. For a list of roles, see [Node Roles](#node-roles-\).
Some node roles cannot be removed using an `ALTER NODE` SQL statement, including `health`, `lts`, and `operatorvm`.
To remove a role, you must be a system-level user.
The node must be restarted in order for this change to take effect.
If you remove a SQL role from a SQL Node, the database removes the node from the connectivity pool. You must restart all SQL Nodes so that the other SQL Nodes understand that the node is no longer a SQL Node.
When you remove the `admin` role, you must also remove the `/var/opt/ocient/metadataStorage.raft` file.
**Syntax**
```sql SQL theme={null}
ALTER NODE [ IF EXISTS ] node_name REMOVE ROLE [ IF EXISTS ]
{ sql | streamloader | admin }
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ---------------------------- |
| `node_name` | string | The name of a node to alter. |
**Example**
This example removes the `sql` role from a node.
```sql SQL theme={null}
ALTER NODE my_node REMOVE ROLE sql;
```
#### ALTER NODE ALTER CONFIG SET
`ALTER NODE ALTER CONFIG SET` sets a configuration override for the configuration at the node scope. For an explanation of how configuration overrides work, see [Inspect the Current Configuration](/inspect-the-current-configuration).
If the specified path to the configuration setting does not exist, it will be considered a new configuration and appended to the collection of existing configurations. To reset a configuration override for a specific key, use the `RESET` keyword.
**Syntax**
```sql SQL theme={null}
-- To set a new configuration override:
ALTER NODE [ IF EXISTS ] node_name
ALTER CONFIG SET string_definition [=] string_value [,...]
-- To reset a configuration override:
ALTER NODE [ IF EXISTS ] node_name ALTER CONFIG RESET string_definition [,...]
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `node_name` | string | The name of the specified node to alter. |
| `string_definition` | string | The name of a configuration parameter to alter. Contact Ocient Support for details about altering configuration parameters. |
| `string_value` | string | The new value to be set for the specified configuration parameter. |
**Examples**
This example sets the certificate name for this node to `cert_name.crt`.
```sql SQL theme={null}
ALTER NODE node2 ALTER CONFIG SET 'certificateStore.cert' = 'cert_name.crt';
```
This example resets the certificate configuration for the node `node2`.
```sql SQL theme={null}
ALTER NODE node2 ALTER CONFIG RESET 'certificateStore.cert';
```
This example alters the configuration at the node scope for node `node2` for service role `lts`.
```sql SQL theme={null}
ALTER NODE node2 ALTER CONFIG SET 'lts.numLevels' = '3';
```
#### ALTER NODE ALTER LOG LEVEL SET
`ALTER NODE node_name ALTER LOG LEVEL SET` sets the log level for a particular logger on the specified node. For an explanation of how configuration overrides work, see [Inspect the Current Configuration](/inspect-the-current-configuration).
The logger name specified can be any string specifying a logger name, or ALL for the root logging configuration. See the [Log Configuration](/log-monitoring#log-configuration) for more details.
To reset a logger to the default log level (INFO), use the `RESET` keyword.
**Syntax**
```sql SQL theme={null}
-- To set a new configuration override:
ALTER NODE [ IF EXISTS ] node_name ALTER LOG LEVEL SET { [,...] }
::=
'ALL' | logger_name [=] { 'EDEBUG' | 'DEBUG' | 'VERBOSE' | 'INFO' | 'WARN' | 'ERROR' }
-- To reset a configuration override:
ALTER NODE [ IF EXISTS ] node_name ALTER LOG LEVEL RESET [ logger_name [,...] ]
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `node_name` | string | The name of the specified node to alter. |
| `` | string | Use `ALL` for the root logging configuration. Otherwise, the `logger_name` parameter can be any string specifying a logger name assigned to a severity level. See the [Log Configuration](/log-monitoring) page for more details. To reset a logger to the default log level (`INFO`), use the `RESET` keyword. |
**Examples**
This example alters the log level at the node scope. The example sets the query log level for this particular node to `DEBUG`.
```sql SQL theme={null}
ALTER NODE node_name ALTER LOG LEVEL SET 'query' = 'DEBUG';
```
This example resets log level for the query logger on the specified node.
```sql SQL theme={null}
ALTER NODE node_name ALTER LOG LEVEL RESET 'query';
```
#### ALTER NODE ALTER METRIC LEVEL
Alters the reporting level of various internal metrics on a specific node. For details about internal metrics, see [Statistics Monitoring](/statistics-monitoring).
To set metrics reporting on all nodes across the system, see [ALTER SYSTEM ALTER METRIC LEVEL](#alter-system-alter-metric-level).
**Syntax**
```sql SQL theme={null}
ALTER NODE [ IF EXISTS ] node_name ALTER METRIC LEVEL
{ SET | RESET }
::=
[ LIKE | REGEX ] metric_to_alter [ ,... ] [=] { 'INFO' | 'DEBUG' }
::=
{ [ LIKE | REGEX ] metric_to_reset [ ,... ] | ALL }
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ---------------------------- |
| `node_name` | string | The name of a node to alter. |
#### Set Metric Levels ``
The `SET` SQL statement assigns one or more specified metrics to the specified reporting level.
To set levels for a range of statistics, you can use wildcard characters with the `LIKE` keyword. Alternatively, you can use regular expressions with the `REGEX` keyword.
| **Parameter** | **Data** **Type** | **Description** |
| ----------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `metric_to_alter` | string | The names of one or more metrics to alter for logging. Enclose any metric names in single quotes. The supported logging level values for metrics are `INFO` and `DEBUG`. Either keyword must be in single quotes. |
#### Reset Metric Levels ``
The `RESET` SQL statement reverts one or more specified metrics to the default log level.
You can use wildcard characters with the `LIKE` keyword. Alternatively, you can use regular expressions with the `REGEX` keyword.
Use the `ALL` keyword to revert all metrics to the default log level.
| **Parameter** | **Data** **Type** | **Description** |
| ----------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `metric_to_reset` | string | The names of one or more metrics to reset by reverting their log level to the default. To revert all metrics, use the `ALL` keyword. |
**Examples**
In this example, the `ALTER NODE` SQL statement sets the `resultCache.queries` metric on the node `oc1` to the `DEBUG` level.
```sql SQL theme={null}
ALTER NODE oc1 ALTER METRIC LEVEL
SET 'resultCache.queries' = 'DEBUG';
```
This example uses the `LIKE` wildcard keyword to capture any metrics prefixed by `localStorageService.device.smart.` and assign them to the `INFO` level.
```sql SQL theme={null}
ALTER NODE oc1 ALTER METRIC LEVEL
SET LIKE 'localStorageService.device.smart.%' 'INFO';
```
Similar to the previous example, this SQL statement uses regular expressions to capture any metrics prefixed by `localStorageService.device.smart.`.
```sql SQL theme={null}
ALTER NODE oc1 ALTER METRIC LEVEL
SET REGEX 'localStorageService.device.smart.*' 'INFO';
```
This example alters the level of multiple metrics.
```sql SQL theme={null}
ALTER NODE oc1 ALTER METRIC LEVEL
SET 'resultCache.queries' = 'DEBUG',
'resultCache.data' = 'INFO',
LIKE 'localStorageService.device.smart.%' 'INFO';
```
This example resets the same metrics.
```sql SQL theme={null}
ALTER NODE oc1 ALTER METRIC LEVEL
RESET 'resultCache.queries',
'resultCache.data',
LIKE 'localStorageService.device.smart.%';
```
#### ALTER NODE SET ADDRESS
`ALTER NODE node_name SET ADDRESS ip_address` changes the internal IP address or hostname for any node. You must restart the system after you change the address. If you change the address of an Administrator Node, then you must update the `bootstrap.conf` file for every node with the new address.
For details about this file, see [Ocient System Bootstrapping](/ocient-system-bootstrapping).
**Syntax**
```sql SQL theme={null}
ALTER NODE [ IF EXISTS ] node_name SET ADDRESS node_address
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `node_name` | string | The name of a node to alter. |
| `node_address` | string | The address for a node. This address can be an internal IP address (e.g., `111.11.11.111`) or a DNS hostname with the node address matching the node name (e.g., `sql1`). |
**Examples**
This example changes the IP address to `111.11.11.111` for the node named `my_node`.
```sql SQL theme={null}
ALTER NODE my_node SET ADDRESS '111.11.11.111';
```
This example changes the SQL Node `sql1` to use the DNS address `sql1`.
```sql SQL theme={null}
ALTER NODE sql1 SET ADDRESS 'sql1';
```
## CONNECTIVITY POOL
### CREATE CONNECTIVITY\_POOL
`CREATE CONNECTIVITY_POOL` creates a connectivity pool from participant SQL Nodes for a client connection. Connectivity pools enable you to change the IP address of the client connection. Client redirects happen only within connectivity pools. For details about connectivity pools and managing them, see [Manage the Network Configuration of an Ocient System](/manage-the-network-configuration-of-an-ocient-system).
All SQL Nodes must be part of at least one connectivity pool. SQL Nodes only listen using the values set for the `listen_ip` and `listen_port` parameters.
The database uses the `source_ip`, `source_port`, and `priority` parameters when multiple connectivity pools exist that a client can use for the connection. In this case, the database uses the connectivity pool with the highest priority.
The database commits all changes made from these SQL statements after you restart all the SQL Nodes.
For information on all connectivity pools on the system, query the system catalog tables for [Connectivity Pools](/system-catalog#connectivity-pools). To see the connectivity pool assignment for each node, query the system catalog table for [connectivity pool participants](/system-catalog#sys-connectivity_pool_participants).
**Syntax**
```sql SQL theme={null}
CREATE CONNECTIVITY_POOL [IF NOT EXISTS] pool_name ::=
SOURCE_ADDRESS [=] source_ip
| [ SOURCE_PORT [=] source_port ]
| PRIORITY [=] priority
| [ SSO INTEGRATION [=] sso_name ]
| PARTICIPANTS (
(NODE [=] node_name
LISTEN_ADDRESS [=] listen_ip
LISTEN_PORT [=] listen_port
ADVERTISED_ADDRESS [=] advertised_ip
[ ADVERTISED_PORT [=] advertised_port ]
[ OPENAPI_PORT [=] openapi_port ), ...)
```
| **Parameter** | **Data** **Type** | **Description** |
| ----------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pool_name` | string | The name of the connectivity pool. |
| `source_ip` | string | The source IP address, which is the IP address in CIDR notation of the client that connects to the SQL Node. |
| `source_port` | integer | Optional. The source port number is the port number of the client. This parameter defaults to none, which means any port number. |
| `priority` | integer | The priority of the connection. A higher number indicates a higher priority. |
| `sso_name` | string | The name of an SSO integration to use for the connectivity pool. For details, see [SSO INTEGRATION](#sso-integration). |
| `node_name` | string | The name of the SQL Node. |
| `listen_ip` | string | The IP address for listening. ℹ️ Connectivity pools do not support dynamic IP addresses. If the IP address of your SQL Node changes, you must manually update it by using an [ALTER CONNECTIVITY\_POOL ALTER PARTICIPANT](#alter-connectivity_pool-alter-participant) SQL statement. |
| `listen_port` | integer | The port number for listening. |
| `advertised_ip` | string | The IP address to return to the client. |
| `advertised_port` | integer | Optional. The port number to return to the client. If you specify NULL for this parameter, then the database uses the value of the `listen_port` parameter. |
| `openapi_port` | integer | The specified port for HTTP Query API-compliant specifications and endpoints. |
**Examples**
Create the connectivity pool named `test_pool` with source address `1.2.3.4/32` and priority `1` for one SQL Node named `sql0`. The node has the IP address `111.1.1.1` and port number `4050` for listening. Specify the local IP address to return to the client.
```sql SQL theme={null}
CREATE CONNECTIVITY_POOL IF NOT EXISTS test_pool
SOURCE_ADDRESS '1.2.3.4/32'
PRIORITY 1
PARTICIPANTS (
(NODE sql0
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'));
```
Create the connectivity pool named `test_pool` with source address `1.2.3.4/32`, port number `44`, and priority `1` for one SQL Node named `sql0`. The node has the IP address `111.1.1.1` and port number `4050` for listening. Specify the local IP address and port number `4050` to return to the client.
```sql SQL theme={null}
CREATE CONNECTIVITY_POOL IF NOT EXISTS test_pool
SOURCE_ADDRESS '1.2.3.4/32'
SOURCE_PORT 44
PRIORITY 1
PARTICIPANTS (
(NODE sql0
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'
ADVERTISED_PORT 4050));
```
Create the connectivity pool named `test_pool` with source address `1.2.3.4/32`, port number `44`, priority `2`, and three participant SQL Nodes: `sql0`, `sql1`, and `sql2`. The nodes have the IP address `111.1.1.1` and port number `4050` for listening. Specify the local IP address and port number `4050` to return to the client.
```sql SQL theme={null}
CREATE CONNECTIVITY_POOL IF NOT EXISTS test_pool
SOURCE_ADDRESS '1.2.3.4/32'
SOURCE_PORT 44
PRIORITY 2
PARTICIPANTS (
(NODE sql0
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'
ADVERTISED_PORT 4050),
(NODE sql1
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'
ADVERTISED_PORT 4050),
(NODE sql2
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'
ADVERTISED_PORT 4050));
```
### DROP CONNECTIVITY\_POOL
`DROP CONNECTIVITY_POOL` removes the specified connectivity pool.
All nodes must belong to a connectivity pool. The execution of this SQL statement does not permit the removal of a pool such that a node becomes an orphan.
**Syntax**
```sql SQL theme={null}
DROP CONNECTIVITY_POOL [ IF EXISTS ] pool_name
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------- | ----------------- | -------------------------------------------- |
| `pool_name` | string | The name of the connectivity pool to remove. |
**Example**
Remove the connectivity pool named `test_pool`.
```sql SQL theme={null}
DROP CONNECTIVITY_POOL test_pool;
```
### ALTER CONNECTIVITY\_POOL
#### ALTER CONNECTIVITY\_POOL SET
`ALTER CONNECTIVITY_POOL SET` sets the metadata of a connectivity pool that includes the source IP address, source port number, priority, and node participants.
**Syntax**
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL [ IF EXISTS ] pool_name SET ::=
SOURCE_ADDRESS [=] source_ip |
SOURCE_PORT [=] source_port |
PRIORITY [=] priority |
PARTICIPANTS(
(NODE [=] node_name
LISTEN_ADDRESS [=] listen_ip
LISTEN_PORT [=] listen_port
ADVERTISED_ADDRESS [=] advertised_ip
[ADVERTISED_PORT [=] advertised_port] ), ...)
```
For parameter definitions, see [CREATE CONNECTIVITY POOL](#create-connectivity_pool).
To directly edit the `LISTEN_ADDRESS`, `LISTEN_PORT`, `ADVERTISED_ADDRESS`, or `ADVERTISED_PORT` parameters, you must either remove the participants and add them back with new values for these parameters using the `ALTER CONNECTIVITY_POOL DROP PARTICIPANTS` and `ALTER CONNECTIVITY_POOL ADD PARTICIPANTS` statements, respectively, or use the `ALTER CONNECTIVITY_POOL SET PARTICIPANTS` statement.
**Examples**
This example sets the priority to `2` of the connectivity pool named `test_pool`.
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL test_pool SET PRIORITY = 2;
```
This example sets the participants of the connectivity pool named `test_pool` to the list of participants with SQL Nodes `sql1` and `sql2`. When you execute this statement, the database resets the prior list of node participants to the new list. The nodes have the IP address `111.1.1.1` and port number `4050` for listening. Specify the local IP address and port number `4050` to return to the client.
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL test_pool
SET PARTICIPANTS(
(NODE sql1
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'
ADVERTISED_PORT 4050),
(NODE sql2
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'
ADVERTISED_PORT 4050));
```
View the node identifiers of the participants of the `test_pool` connectivity pool by querying the node identifier `node_id` in the `sys.connectivity_pool_participants` and `sys.connectivity_pools` system catalog tables.
```sql SQL theme={null}
SELECT cpp.node_id
FROM sys.connectivity_pool_participants cpp
INNER JOIN sys.connectivity_pools cp
ON cpp.id = cp.id
WHERE cp.name = 'test_pool';
```
#### ALTER CONNECTIVITY\_POOL RENAME TO
`ALTER CONNECTIVITY_POOL RENAME TO` SQL statement renames the existing connectivity pool.
**Syntax**
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL [ IF EXISTS ] pool_name RENAME TO new_pool_name
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------- | ----------------- | ------------------------------------------- |
| `pool_name` | string | The name of the existing connectivity pool. |
| `new_pool_name` | string | The new name of the connectivity pool. |
**Examples**
Rename the `test_pool` connectivity pool to `new_test_pool`.
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL test_pool RENAME TO new_test_pool;
```
#### ALTER CONNECTIVITY\_POOL ADD PARTICIPANTS
`ALTER CONNECTIVITY_POOL ADD PARTICIPANTS` adds one or more nodes to the participant list of an existing connectivity pool.
For information on all connectivity pools on the system, query the system catalog tables for [Connectivity Pools](/system-catalog). To see the connectivity pool assignment for each node, query the system catalog table for [connectivity pool participants](/system-catalog).
**Syntax**
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL [ IF EXISTS ] pool_name
ADD PARTICIPANTS(
(NODE [=] node_name
LISTEN_ADDRESS [=] listen_ip
LISTEN_PORT [=] listen_port
ADVERTISED_ADDRESS [=] advertised_ip
[ADVERTISED_PORT [=] advertised_port] ), ...)
```
**Examples**
Add one node `sql5` to the participant list of the connectivity pool `test_pool`. The node has the IP address `111.1.1.1` and port number `4050` for listening. Specify the local IP address and port number `4050` to return to the client.
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL test_pool
ADD PARTICIPANTS(
NODE sql5
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'
ADVERTISED_PORT 4050);
```
Add two nodes `sql6` and `sql7` to the participants list of the connectivity pool `test_pool`. The nodes have the IP address `111.1.1.1` and port number `4050` for listening. Specify the local IP address and port number `4050` to return to the client.
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL test_pool
ADD PARTICIPANTS(
(NODE sql6
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'
ADVERTISED_PORT 4050),
(NODE sql7
LISTEN_ADDRESS '111.1.1.1'
LISTEN_PORT 4050
ADVERTISED_ADDRESS 'localhost'
ADVERTISED_PORT 4050));
```
#### ALTER CONNECTIVITY\_POOL ALTER PARTICIPANT
`ALTER CONNECTIVITY_POOL ALTER PARTICIPANT` modifies the configurations of one SQL Node assigned to the existing connectivity pool.
This SQL statement can alter only one configuration parameter of a participant node at a time.
For information on all connectivity pools on the system, query the system catalog tables for [Connectivity Pools](/system-catalog). To see the connectivity pool assignment for each node, query the system catalog table for [connectivity pool participants](/system-catalog).
**Syntax**
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL [ IF EXISTS ] pool_name
ALTER PARTICIPANT node_name
SET ::=
{ LISTEN_ADDRESS [=] listen_ip
| LISTEN_PORT [=] listen_port
| ADVERTISED_ADDRESS [=] advertised_ip
| ADVERTISED_PORT [=] advertised_port
| OPENAPI_PORT [=] openapi_port }
```
| **Parameter** | **Data** **Type** | **Description** |
| ----------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pool_name` | string | The name of the connectivity pool. |
| `node_name` | string | The name of the SQL Node to alter. |
| `listen_ip` | string | The IP address for listening. |
| `listen_port` | numeric | The port number for listening. |
| `advertised_ip` | string | The IP address to return to the client. |
| `advertised_port` | numeric | The port number to return to the client. If you specify NULL for this parameter, then the database uses the value of the `listen_port` parameter. |
| `openapi_port` | numeric | The specified port for HTTP Query API-compliant specifications and endpoints. |
**Example**
Modify the SQL Node `sql0` to use the new `listen_port` value `4051`.
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL cp_test
ALTER PARTICIPANT sql0
SET listen_port 4051;
```
#### ALTER CONNECTIVITY\_POOL DROP PARTICIPANTS
`ALTER CONNECTIVITY_POOL DROP PARTICIPANTS` removes one or more nodes from the participant list of an existing connectivity pool. If you remove the last node of a connectivity pool, the Ocient System automatically removes the connectivity pool.
For information on all connectivity pools on the system, query the system catalog tables for [Connectivity Pools](/system-catalog). To see the connectivity pool assignment for each node, query the system catalog table for [connectivity pool participants](/system-catalog).
All nodes must belong to a connectivity pool. The execution of this SQL statement does not permit the removal of a node such that it becomes an orphan.
**Syntax**
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL [ IF EXISTS ] pool_name
DROP PARTICIPANTS (node_name, ...)
```
**Examples**
Remove one node `sql5` from the connectivity pool `test_pool`.
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL IF EXISTS test_pool DROP PARTICIPANTS sql5;
```
Remove nodes `sql6` and `sql7` from the connectivity pool `test_pool`.
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL test_pool DROP PARTICIPANTS (sql6, sql7);
```
#### ALTER CONNECTIVITY\_POOL SET SSO INTEGRATION
`ALTER CONNECTIVITY_POOL SET SSO INTEGRATION` assigns a connectivity pool to use a specific SSO integration.
Connectivity pools look for the specified SSO integration name for each database you are trying to connect to. If the database does not support that SSO integration name, it uses the default SSO.
**Syntax**
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL [ IF EXISTS ] pool_name
SET SSO INTEGRATION sso_name
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ------------------------------------------- |
| `pool_name` | string | The name of the existing connectivity pool. |
| `sso_name` | string | The new name of the SSO integration. |
**Example**
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL cp_test SET SSO INTEGRATION sso_test;
```
#### ALTER CONNECTIVITY\_POOL REMOVE SSO INTEGRATION
`ALTER CONNECTIVITY_POOL REMOVE SSO INTEGRATION` removes an assigned SSO integration.
**Syntax**
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL [ IF EXISTS ] pool_name
REMOVE SSO INTEGRATION sso_name
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ------------------------------------------- |
| `pool_name` | string | The name of the existing connectivity pool. |
| `sso_name` | string | The name of the existing SSO integration. |
**Example**
This example removes the SSO integration `sso_test` from the connectivity pool `cp_test`.
```sql SQL theme={null}
ALTER CONNECTIVITY_POOL cp_test REMOVE SSO INTEGRATION sso_test;
```
## SSO INTEGRATION
### CREATE SSO INTEGRATION
Creates a new SSO integration protocol, which can connect to databases as a database integration (see [ALTER DATABASE SET SSO INTEGRATION](/databases#alter-database-set-sso-integration) ) or connect using a connectivity pool (see [ALTER CONNECTIVITY\_POOL SET SSO INTEGRATION](#alter-connectivity_pool-set-sso-integration)).
**Syntax**
```sql SQL theme={null}
CREATE SSO INTEGRATION [IF NOT EXISTS ] sso_name
PROTOCOL sso_protocol [, ... ]
::=
-- literal or string value
property_name = value |
-- list of values
property_name = [ value [, ...] ] |
-- map of values
property_name = { key = value [, ...] }
```
| **Parameter** | **Type** | **Description** |
| --------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sso_name` | string | The identifier of the SSO integration to create. |
| `sso_protocol` | string | Supported values are: `oidc`, `openid`, and `openid_connect`. All these values are aliases of each other and use the OAuth 2.0 Authorization. |
| `property_name` | string | One or more properties to include in the SSO integration. Each SSO property must be specified either as a literal, list, or map. See the SSO Properties table for the requirements for each supported SSO parameter. SSO properties also have these rules: You can place any string key or value between double quotations (e.g., `"default_group"`). String values that contain characters other than `[a-zA-z] \| [0-9] \| '_' ` require double quotations (e.g., `"this.is.a.complex-$tring"`). Using a NULL value clears the existing configuration of a list or map property (e.g., `user_claim_ids = NULL`). |
#### SSO Properties
| **Name** | **Required** | **Value Type** | **Default Value** | **Description** |
| -------------------------------- | ------------ | ------------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `issuer` | Yes | string | None | The [complete URL](https://openid.net/specs/openid-connect-core-1_0.html#Terminology) for the OAuth 2.0 and OpenID Connect Authorization Server. This property value is the expected `\"iss\"` claim in access tokens validated by the database. |
| `client_id` | Yes | string | None | The [client identifier](https://openid.net/specs/openid-connect-core-1_0.html#Terminology) as registered with the OpenID Provider. |
| `client_secret` | Yes | string | None | The [client secret](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation) as registered with the OpenID Provider. This property is required for some SSO workflows. |
| `default_group` | Yes | string | None | The group users are assigned if no group is specified in the `group_claim_mappings` property for the OpenID Provider. |
| `redirect_host` | No | string | Depends on the connector (pyocient or JDBC). | Specifies the host name during SSO redirection. |
| `redirect_ssl` | No | Boolean | Depends on the connector (pyocient or JDBC). | Set to `true` to enable SSL callback during SSO redirection (i.e., redirect uses `https`). Set to `false` to disable (i.e., redirect uses `http`). |
| `disabled` | No | Boolean | `false` | Set to `true` to disable the OIDC integration for maintenance temporarily. ⚠️ If you set this property to `true`, all authentication requests using this connection fail. |
| `enable_id_token_authentication` | No | Boolean | `false` | Set this property to `true` if the identifier token also contains the authorization token. In most circumstances, this option is necessary only for machine-to-machine connections without user interaction, such as a server using a script to connect to an Ocient System. |
| `user_id_claims` | No | list of strings (e.g., value \[, ...] | \["email"] | Set the identifier token claims used to identify users in audit trails. If you do not set a value, the system uses the `"email"` claim if it is present, otherwise it uses `["iss", "sub"]`. |
| `additional_scopes` | No | list of strings (e.g., value \[, ...] | \[] | Specifies additional scopes to request when executing the Authorization Code Flow. |
| `additional_audiences` | No | list of strings (e.g., value \[, ...] | \[] | Specifies additional audiences to accept when validating tokens. This property is useful for authorization servers without the token exchange capability. Each additional audience is a case-sensitive URL from a provider, similar to the `issuer` value. |
| `groups_claim_ids` | No | list of strings (e.g., value \[, ...] | \[] | Specifies the token claims that can be used to map the user to a Database group. If you specify the `groups_claim_mappings` property, you must also specify the `groups_claim_ids` property. |
| `groups_claim_mappings` | No | map of strings (e.g., key = value \[, ...]) | Specifies mappings from the Provider group to the Database group. | |
| `roles_claim_ids` | No | list of strings (e.g., value \[, ...] | \[] | Specifies the token claims that can be used to map the user to a Database role. If you specify the `roles_claim_mappings` property, you must also specify the `roles_claim_ids` property. |
| `roles_claim_mappings` | No | map of strings (e.g., key = value \[, ...]) | Specifies mappings from the Provider role to the Database role. | |
| `allowed_groups` | No | list of strings (e.g., value \[, ...] | \[] | Specifies a list of external identity provider groups that are permitted to authenticate through this SSO integration. If you specify the `allowed_groups` property, only users who are members of the specified identify provider groups can access the Ocient System.
If this property is empty or you do not specify it, then group-based filtering is disabled, and the system allows all authenticated users from the provider unless they are explicitly blocked. Group names must match exactly as they appear in the claims of the identify provider group. |
| `allowed_roles` | No | list of strings (e.g., value \[, ...] | \[] | Defines a list of external identity provider roles that are authorized to access the Ocient System through this SSO integration. Only users assigned to the specified roles in the external provider can authenticate.
If this property is empty or you do not specify it, role-based access control is disabled for this integration. Role names must correspond exactly to the role claims provided by the identity provider in the authentication response. |
| `blocked_groups` | No | list of strings (e.g., value \[, ...] | \[] | Specifies a list of external identity provider groups that are explicitly denied access through this SSO integration. The system blocks users who are members of any specified group in the external identity provider from authenticating, regardless of other permissions they have. Setting this property takes precedence over the `allowed_groups` property if a user belongs to both an allowed group and a blocked group. Group names must match exactly as they appear in the claims of the identify provider group. |
| `blocked_roles` | No | list of strings (e.g., value \[, ...] | \[] | Defines a list of external identity provider roles that are explicitly prohibited from accessing the Ocient System through this SSO integration. The system denies access to users assigned to any of the specified roles, overriding any other access permissions. Setting this property takes precedence over the `allowed_roles` property in cases where a user is in both an allowed role and a blocked role. Role names must correspond exactly to the role claims of the identity provider group. |
| `allow_offline_access` | No | Boolean | `false` | When the `allow_offline_access` property is `true`, Ocient requests offline access from the OpenID Connect identity provider by including `access_type=offline` and `prompt=consent` in the authorization URL. |
**Example**
This example creates an SSO integration protocol with the specified OpenID issuer `"https://accounts.google.com"`, client identifier, and default group. Each of these parameters is required to create a new SSO integration. The example assumes preset values for the client identifier and default group.
```sql SQL theme={null}
CREATE SSO INTEGRATION sso_test PROTOCOL oidc
issuer = "https://accounts.google.com",
client_id = example_database_app_id,
default_group = example_database_group;
```
### DROP SSO INTEGRATION
Drops an SSO integration protocol.
**Syntax**
```sql SQL theme={null}
DROP SSO INTEGRATION [ IF EXISTS ] sso_name
```
| **Parameter** | **Type** | **Description** |
| ------------- | -------- | ---------------------------------------------- |
| `sso_name` | string | The identifier of the SSO integration to drop. |
**Example**
This SQL statement drops the SSO integration protocol `sso_test`.
```sql SQL theme={null}
DROP SSO INTEGRATION sso_test;
```
### ALTER SSO INTEGRATION
Alters an SSO integration protocol by renaming it or modifying its properties.
```sql SQL theme={null}
ALTER SSO INTEGRATION sso_name [ IF EXISTS ] {
RENAME TO new_name |
SET [, ... ]
}
::=
-- literal or string value
property_name = value |
-- list of values
property_name = [ value [, ...] ] |
-- map of values
property_name = { key = value [, ...] }
```
| **Parameter** | **Type** | **Description** |
| --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sso_name` | string | The identifier of the SSO integration to alter. |
| `new_name` | string | The new name of the SSO integration. |
| `property_name` | string | One or more properties to include in the SSO integration. Each SSO property must be specified either as a literal, list, or map. See the [SSO Properties](#sso-properties) table to see the requirements for each supported SSO parameter. SSO properties also have these rules: You can place any string key or value between double quotations (e.g., `"default_group"`). String values that contain characters other than `[a-zA-z] \| [0-9] \| '_' ` require double quotations (e.g., `"this.is.a.complex-$tring"`). Using a NULL value clears the existing configuration of a list or map property (e.g., `user_claim_ids = NULL`). |
**Examples**
**Alter SSO Integration Properties**
This example alters the SSO integration to use different properties, changing the OpenID client identifier and the default group to `"group2"`. The example assumes a preset value for the client identifier.
```sql SQL theme={null}
ALTER SSO INTEGRATION sso_test SET
client_id = different_database_app_id,
default_group = "group2";
```
**Rename an SSO Integration**
This example renames the SSO integration to `sso_test_2`.
```sql SQL theme={null}
ALTER SSO INTEGRATION sso_test RENAME TO sso_test_2;
```
## SYSTEM
### ALTER SYSTEM ALTER CONFIG SET
`ALTER SYSTEM ALTER CONFIG SET` sets an override for the configuration at the system scope. For an explanation of how configuration overrides work, see [Inspect the Current Configuration](/inspect-the-current-configuration).
If the specified path to the configuration setting does not exist, it is considered a new configuration and appended to the collection of existing configurations. To reset a configuration override for a specific parameter, use the `RESET` keyword.
This configuration override is set in the base node configuration by default. To apply the override to a specific service role, prefix the key with the service role name.
**Syntax**
```sql SQL theme={null}
-- To set a new configuration override:
ALTER SYSTEM
ALTER CONFIG SET parameter_name [=] parameter_value [,...]
-- To reset a configuration override:
ALTER SYSTEM
ALTER CONFIG RESET [ parameter_name [,...] ]
```
| **Parameter** | **Data** **Type** | **Description** |
| ----------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `parameter_name` | string | The name of a configuration parameter to alter. This parameter should be a string literal (i.e., enclosed in single quotes). Contact Ocient Support for details about altering configuration parameters. |
| `parameter_value` | any | The new value to be set for the specified configuration parameter. The data type of this value depends on the configuration parameter. This can be a string literal that can be cast to the data type of the configuration parameter. For example, the string literal `'true'` is equivalent to the Boolean value `true`. |
**Examples**
This example alters the base configuration of the system scope. The example sets the certificate name for each node in the entire system to `cert_name.crt`.
```sql SQL theme={null}
ALTER SYSTEM ALTER CONFIG SET 'certificateStore.cert' = 'cert_name.crt';
```
This example resets the certificate configuration for the entire system.
```sql SQL theme={null}
ALTER SYSTEM ALTER CONFIG RESET 'certificateStore.cert';
```
This example alters the configuration for the service role `sql`. The `purgeCacheFrequency` setting determines the frequency in seconds to purge the result-set cache of stale values.
```sql SQL theme={null}
ALTER SYSTEM ALTER CONFIG SET 'sql.purgeCacheFrequency' = 600;
```
#### ALTER SYSTEM ALTER LOG LEVEL
`ALTER SYSTEM ALTER LOG LEVEL SET` sets the log level for a particular logger for all nodes in the system. For an explanation of how configuration overrides work, see [Inspect the Current Configuration](/inspect-the-current-configuration).
The logger name specified can be any string specifying a logger name, or `ALL` for the root logging config. See the [Log Configuration](/log-monitoring) for more details.
**Syntax**
```sql SQL theme={null}
-- To set a new configuration override:
ALTER SYSTEM ALTER LOG LEVEL SET { [,...] }
::=
'ALL' | logger_name [=] { 'EDEBUG' | 'DEBUG' | 'VERBOSE' | 'INFO' | 'WARN' | 'ERROR' }
-- To reset a configuration override:
ALTER SYSTEM ALTER LOG LEVEL RESET [logger_name [, ...]]
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `` | string | Use `ALL` for the root logging config. Otherwise, the `logger_name` parameter can be any string specifying a logger name assigned to a severity level. See the [Log Configuration](/log-monitoring) page for more details. To reset a logger to the default log level (`INFO`), use the `RESET` keyword. |
**Example**
This example alters the log level at the system scope.
```sql SQL theme={null}
ALTER SYSTEM ALTER LOG LEVEL SET 'ALL' = 'DEBUG';
```
### ALTER SYSTEM RENAME TO
`ALTER SYSTEM RENAME TO` sets the system name. The system name appears in the `sys.system_information` system catalog table. You can also see the current system name by using the [CURRENT\_SYSTEM](/other-functions-and-expressions#current_system) function.
**Syntax**
```sql SQL theme={null}
ALTER SYSTEM RENAME TO system_name
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------- | ----------------- | ------------------------------ |
| `system_name` | string | The name of the Ocient System. |
**Example**
```sql SQL theme={null}
ALTER SYSTEM RENAME TO "productionSystem";
```
### ALTER SYSTEM ALTER METRIC LEVEL
Alters the reporting level of various internal metrics across the system, including all nodes. For details about internal metrics, see [Statistics Monitoring](/statistics-monitoring).
To set metrics reporting for individual nodes, see [ALTER NODE ALTER METRIC LEVEL](#alter-node-alter-metric-level).
**Syntax**
```sql SQL theme={null}
ALTER SYSTEM ALTER METRIC LEVEL
{ SET | RESET }
::=
[ LIKE | REGEX ] metric_to_alter [ ,... ] [=] { 'INFO' | 'DEBUG' }
::=
{ [ LIKE | REGEX ] metric_to_reset [ ,... ] | ALL }
```
#### Set Metric Levels ``
The `SET` SQL statement assigns one or more specified metrics to the specified reporting level. You can assign metrics to `INFO` or `DEBUG` levels.
To set levels for a range of statistics, you can use wildcard characters with the `LIKE` keyword. Alternatively, you can use regular expressions with the `REGEX` keyword.
| **Parameter** | **Data** **Type** | **Description** |
| ----------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `metric_to_alter` | string | The names of one or more metrics to alter for logging. Enclose any metric names in single quotes. The supported logging levels for metrics are `INFO` and `DEBUG`. Either keyword must be in single quotes. |
#### Reset Metric Levels ``
The `RESET` SQL statement reverts one or more specified metrics to the default reporting level.
You can use wildcard characters with the `LIKE` keyword. Alternatively, you can use regular expressions with the `REGEX` keyword.
Use the `ALL` keyword to revert all metrics to the default level.
| **Parameter** | **Data** **Type** | **Description** |
| ----------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `metric_to_reset` | string | The names of one or more metrics to reset by reverting their level to the default. To revert all metrics, use the `ALL` keyword. |
**Examples**
In this example, the `ALTER SYSTEM` SQL statement sets the `resultCache.queries` metric to the `DEBUG` level.
```sql SQL theme={null}
ALTER SYSTEM ALTER METRIC LEVEL
SET 'resultCache.queries' = 'DEBUG';
```
This example uses the `LIKE` wildcard to capture any metrics prefixed by `localStorageService.device.smart.` and assign them to the `INFO` level.
```sql SQL theme={null}
ALTER SYSTEM ALTER METRIC LEVEL
SET LIKE 'localStorageService.device.smart.%' 'INFO';
```
Similar to the previous example, this SQL statement uses regular expressions to capture any metrics prefixed by `localStorageService.device.smart.`.
```sql SQL theme={null}
ALTER SYSTEM ALTER METRIC LEVEL
SET REGEX 'localStorageService.device.smart.*' 'INFO';
```
This example alters the level of multiple metrics.
```sql SQL theme={null}
ALTER SYSTEM ALTER METRIC LEVEL
SET 'resultCache.queries' = 'DEBUG',
'resultCache.data' = 'INFO',
LIKE 'localStorageService.device.smart.%' 'INFO';
```
This example resets the same metrics.
```sql SQL theme={null}
ALTER SYSTEM ALTER METRIC LEVEL
RESET 'resultCache.queries',
'resultCache.data',
LIKE 'localStorageService.device.smart.%';
```
### ALTER SYSTEM ALTER SECURITY
Set security settings using the `ALTER SYSTEM ALTER SECURITY` SQL statement. Replace `` with the security setting and `` with the value.
You can inspect the current values of system configuration settings using the `sys.config` and `sys.node_config` system catalog tables.
**Syntax**
```sql SQL theme={null}
ALTER SYSTEM ALTER SECURITY [=]
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `security_setting` | string | The security setting with values: \* `password_minimum_length` \* `password_complexity_level` \* `password_no_repeat_count` \* `password_lifetime_days` \* `password_invalid_attempt_limit` For details about these values, see [Database Password Security Settings](/database-password-security-settings). |
| `value` | numeric | An integer to represent one of the security settings. For details about this value, see [Database Password Security Settings](/database-password-security-settings). |
**Examples**
**Set a Security Setting for All Databases**
Set the password lifetime to 30 days for the entire system.
```sql SQL theme={null}
ALTER SYSTEM ALTER SECURITY password_lifetime_days = 30;
```
**Set Multiple Security Settings**
Set multiple security settings in a single SQL statement. In this case, set the password lifetime to 30 days and the minimum password character length to 12. As with other similar SQL statements, the `=` character is optional.
```sql SQL theme={null}
ALTER SYSTEM ALTER SECURITY
password_lifetime_days 30,
password_minimum_length 12;
```
### ALTER SYSTEM SET DEFAULT STORAGESPACE
Sets the specified storage space as the default for creating new tables.
`CREATE TABLE` SQL statements automatically use the default storage space unless you specify a different storage space (see [Table Options](/tables#create-option-\)). After you create a table, you cannot alter its assigned storage space. Statements such as `DROP STORAGESPACE` and `ALTER CLUSTER REMOVE STORAGESPACE` throw an error if they attempt to drop the default storage space of the system.
To remove the default storage space, use the optional `RESET` keyword. The `RESET` keyword alters the system to have no default storage space. Until you set a storage space as the new default, `CREATE TABLE` statements throw an error if they do not specify a storage space for the new table.
**Required Privileges**
To use this SQL statement, you must have the `ALTER` privilege for the system. For details about privileges, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
**Syntax**
```sql SQL theme={null}
ALTER SYSTEM { SET | RESET } DEFAULT STORAGESPACE [ storage_space_name ]
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `storage_space_name` | string | The name of a storage space to set as the system default. This parameter is required when you use the `SET` keyword to define a default storage space.
Do not include this parameter when you use the `RESET` keyword to remove the default storage space. |
**Examples**
**Set a Default Storage Space**
This example sets `ss_0` as the system default storage space.
```sql SQL theme={null}
ALTER SYSTEM SET DEFAULT STORAGESPACE ss_0;
```
**Remove the Default Storage Space**
This example removes any default storage space.
```sql SQL theme={null}
ALTER SYSTEM RESET DEFAULT STORAGESPACE;
```
## Related Links
[Other Functions and Expressions](/other-functions-and-expressions)
[CREATE TABLE SQL Statement Examples](/create-table-sql-statement-examples)
[Database Password Security Settings](/database-password-security-settings)
# Clustering Analysis and Dimensionality Reduction
Source: https://docs.ocient.com/clustering-analysis-and-dimensionality-reduction
Apply clustering and dimensionality reduction in Ocient with OcientML using k-means, PCA, and related algorithms for unsupervised exploration of data.
This tutorial uses examples to explain the clustering and dimensionality reduction capabilities in .
## Clustering Models
Clustering models bear similarities to classification, but they use unsupervised learning, which means they do not use any class labels. Instead, the algorithm tries to identify groupings on its own by finding clusters of data that seem closer to each other and farther away from other clusters.
These models generate an integer label, but its ordering is arbitrary. The clustering models require you to specify upfront the number of clusters.
### K-Means Clustering
K-means is by far the most well-known clustering algorithm because it is simple and fast. K-means performs particularly well if you can scale your features so clusters are roughly circular and equal in size.
These examples demonstrate the k-means model. The examples do not use a data set that is primed for optimal performance of the model, such that they show the shortcomings of the k-means model and how it can perform relatively well even with sub-optimal data.
The examples use a data set of three-dimensional points.
```sql SQL theme={null}
SELECT x, y, z FROM mldemo.clusters_3d LIMIT 10;
x y z
------------------------------------------------------------------
-2.332818550827427 2.1009728159912044 -0.7199553405333495
0.27417054580238553 -0.29545777905624226 0.6797340230215586
-2.8608875606526794 2.8532647291218884 -0.7296054608643955
-4.9539478834915345 -4.987358010702081 -0.818608017693332
0.7043958454569171 -0.7209720558364705 -0.7879961167668906
4.949298606341526 4.956911476243746 0.6015700102502752
2.245935331812275 -2.158347482865157 -1.0786578947921444
-1.3725012757407247 1.5652243270484643 -2.5951429274728794
4.516051945094492 4.560705560578962 -0.1569348000058415
5.140105808358035 -4.9583101530224 -1.0064835641873153
Fetched 10 rows
```
This example shows a k-means model created over this data. You can specify multiple options, but the only one that is required is the `k` value, which represents the number of clusters.
```sql SQL theme={null}
CREATE MLMODEL kmeans1 TYPE KMEANS ON (
SELECT x,
y,
z
FROM mldemo.clusters_3d
) options('k'->'3');
Modified 0 rows
```
This data set has labels, but they are hidden from the model to allow for unsupervised learning.
These example queries compare how well the unsupervised k-means clustering performs against the actual correct classes and labels.
Before you can do that, you must figure out which cluster numbers correspond to which labels.
```sql SQL theme={null}
SELECT COUNT(*),
cluster_num
FROM (
SELECT kmeans1(x, y, z) AS cluster_num
FROM mldemo.clusters_3d
WHERE label = 'LEFT'
)
GROUP BY cluster_num;
count(*) cluster_num
--------------------------------
3165 0
146329 1
Fetched 2 rows
SELECT COUNT(*),
cluster_num
FROM (
SELECT kmeans1(x, y, z) AS cluster_num
FROM mldemo.clusters_3d
WHERE label = 'RIGHT'
)
GROUP BY cluster_num;
count(*) cluster_num
--------------------------------
3877 0
145761 2
Fetched 2 rows
SELECT COUNT(*),
cluster_num
FROM (
SELECT kmeans1(x, y, z) AS cluster_num
FROM mldemo.clusters_3d
WHERE label = 'CENTER'
)
GROUP BY cluster_num;
count(*) cluster_num
--------------------------------
700868 0
Fetched 1 row
```
The results indicate that cluster `0` is the `CENTER` class, cluster `1` is `LEFT`, and cluster `2` is `RIGHT`.
With that information, you can compute the overall accuracy.
```sql SQL theme={null}
SELECT count(*) / 1000000.0
FROM mldemo.clusters_3d
WHERE (
kmeans1(x, y, z) = 0
AND label = 'CENTER'
)
OR (
kmeans1(x, y, z) = 1
AND label = 'LEFT'
)
OR (
kmeans1(x, y, z) = 2
AND label = 'RIGHT'
);
(_count(*)_0)/((1000000.0))
----------------------------
0.992958
Fetched 1 row
```
The accuracy is very good. This calculation indicates that the model never miscategorized `CENTER`, but there were some wrong classifications for the `LEFT` and `RIGHT` labels, although they were rare.
For details, see [K-Means Clustering](/clustering-and-dimension-reduction-models#k-means-clustering).
### Gaussian Mixture Models
Gaussian mixture models (GMMs) also perform clustering, however they use a significantly more complex algorithm. GMMs can handle several things that k-means cannot, such as:
* GMMs can handle clusters that are not circular, i.e., they have different variances in different directions.
* GMMs can handle clusters that have an arbitrary rotation, i.e., they can have covariances.
* GMMs can handle the fact that all clusters might not be equally as likely, i.e. if a point is located right between two clusters, then it is more likely to be the one more common in the training data.
* GMMs can show the probability of a new point belonging to each cluster rather than outputting a single cluster value.
GMMs operate by finding a weighted mixture of k multi-variate Gaussians that is most likely to represent the population from which the data was sampled. Each Gaussian in the mix has a mean vector, which represents the center of each cluster.
After you create the model, it is simple to determine the cluster that a point most likely belongs to. The examples demonstrate how to find the highest probability cluster.
This example makes a model over the same data set. This model requires the `numDistributions` option, which represents the number of clusters.
```sql SQL theme={null}
CREATE MLMODEL gmm TYPE GAUSSIAN MIXTURE MODEL ON (
SELECT x,
y,
z
FROM mldemo.clusters_3d
) options('metrics'->'true', 'numDistributions'->'3');
Modified 0 rows
```
This query executes the GMM model.
```sql SQL theme={null}
SELECT gmm(0,0,0) AS class_probabilities;
class_probabilities
--------------------------------------------------------------------------------
[[2.0445296213545875E-4, 0.999582295498657, 2.1325153920763012E-4]]
Fetched 1 row
```
The results are very different than executing a k-means model because these are probabilities. In this case, the output means the probability of `(0,0,0)` being the second class is very high (greater than 99.9 percent), while the probability of it being the other classes is essentially zero.
To find the most likely class, use the `VECTOR_ARGMAX` function, which returns a 1-based class index.
```sql SQL theme={null}
SELECT VECTOR_ARGMAX(gmm(0,0,0)) AS class_probabilities;
class_probabilities
--------------------
1
Fetched 1 row
```
You can write a query to assess the accuracy of this model. But first, you must figure out the association between classes and labels.
```sql SQL theme={null}
SELECT COUNT(*),
cluster_num
FROM (
SELECT VECTOR_ARGMAX(gmm(x, y, z)) AS cluster_num
FROM mldemo.clusters_3d
WHERE label = 'LEFT'
)
GROUP BY cluster_num;
count(*) cluster_num
----------------------------------------
149483 3
2 1
9 2
Fetched 3 rows
SELECT COUNT(*),
cluster_num
FROM (
SELECT VECTOR_ARGMAX(gmm(x, y, z)) AS cluster_num
FROM mldemo.clusters_3d
WHERE label = 'CENTER'
)
GROUP BY cluster_num;
count(*) cluster_num
----------------------------------------
700868 1
Fetched 1 row
SELECT COUNT(*),
cluster_num
FROM (
SELECT VECTOR_ARGMAX(gmm(x, y, z)) AS cluster_num
FROM mldemo.clusters_3d
WHERE label = 'RIGHT'
)
GROUP BY cluster_num;
count(*) cluster_num
----------------------------------------
6 2
3 3
149629 1
Fetched 3 rows
```
This model misclassified 20 rows, which is far better than the 7,042 rows the k-means model misclassified. This is a direct result of the additional complexity of the GMM.
GMM models can handle much more complex situations than k-means models, but this comes at the cost of more time training and executing the model. The time a GMM model takes compared to a k-means model depends on the number of clusters.
For details, see [Gaussian Mixture](/clustering-and-dimension-reduction-models#gaussian-mixture).
## Dimensionality Reduction
Dimensionality reduction algorithms reduce the number of input features while still keeping as much of the meaningful properties of the data as possible. Models are quicker to build, and often higher quality after a dimensionality reduction model reduces the number of input features.
A common first step in an analysis is to use dimensionality reduction to simplify the data. See these examples that demonstrate how to use dimensionality reduction as a preprocessing step before using other model types.
### Principal Component Analysis
Principal component analysis (PCA) is an unsupervised algorithm that only operates on the inputs, and does not understand what the data is being used for. It is also a linear dimensionality reduction algorithm, meaning that the new features it generates are linear combinations of existing features.
PCA generates as many new features as there are input features. So by itself, it is not reducing the number of dimensions. However, PCA creates new features that try to maximize variance and sorts the new features in terms of the amount of variance they contain. The system catalog tables provide information on how much variance is contained by the new features. You can use this information to find how many trailing new features to drop.
This PCA tutorial uses a new data set. Start with a regression problem that is trying to find the best-fit polynomial for `f(x1, x2, x3) = y`. The tutorial starts with a [Polynomial Regression](/regression-models#polynomial-regression) model to see how well it does using three input features, and then it uses PCA to reduce the number of variables without losing accuracy.
This example shows the Polynomial Regression model.
```sql SQL theme={null}
CREATE MLMODEL poly TYPE POLYNOMIAL REGRESSION ON (
SELECT x1,
x2,
x3,
y
FROM mldemo.pca_poly
) options('order'->'2', 'metrics'->'true');
Modified 0 rows
```
The system catalog table shows that the model fits the data perfectly.
```sql SQL theme={null}
SELECT coefficient_of_determination
FROM sys.machine_learning_models a,
sys.polynomial_regression_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'poly';
coefficient_of_determination
-----------------------------
1.0
Fetched 1 row
```
In this instance, PCA can reduce the three independent variables to two.
The first step is to build a PCA model over the input features.
```sql SQL theme={null}
CREATE MLMODEL pca1 TYPE PRINCIPAL COMPONENT ANALYSIS ON (
SELECT x1,
x2,
x3
FROM mldemo.pca_poly
);
Modified 0 rows
```
The model does not include `y` because PCA operates over only the input features.
Examine the `machine_learning_models` and `principal_component_analysis_models` system catalog tables.
```sql SQL theme={null}
SELECT importance
FROM sys.machine_learning_models a,
sys.principal_component_analysis_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'pca1';
importance
--------------------------------------------------------------------------------
[0.6022962127628679, 0.33286202821081917, 0.06484175902631285]
Fetched 1 row
```
The `importance` value indicates that over 93 percent of the signal is in the first two PCA output features, which means it is possible to have a robust model even if you remove the third feature.
This example uses the Polynomial Regression model to access the PCA output features. The example executes the `pca1` PCA function with the PCA input features followed by the number of features. This number starts at `1`, so this example uses PCA features `1` and `2`, but not the last feature.
```sql SQL theme={null}
CREATE MLMODEL poly2 TYPE POLYNOMIAL REGRESSION ON (
SELECT pca1(x1, x2, x3, 1),
pca1(x1, x2, x3, 2),
y
FROM mldemo.pca_poly
) options('order'->'2', 'metrics'->'true');
Modified 0 rows
```
Notice that the example still references all three input features, but this model now has only two independent variables. As a result, the model trains 15 percent faster than the version with three independent variables. It is also a much simpler model. The model has six terms in the polynomial regression instead of 10, when there were three independent variables.
This query examines how well the model fits the data.
```sql SQL theme={null}
SELECT coefficient_of_determination
FROM sys.machine_learning_models a,
sys.polynomial_regression_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'poly2';
coefficient_of_determination
-----------------------------
0.9952839146818417
Fetched 1 row
```
The model is a great fit with more than 99 percent accuracy.
In contrast, here is an example where PCA is not a good idea. This example goes back to the three-dimensional clusters data set used in the [Clustering Models](#clustering-models) examples.
This example creates the PCA model and checks the `importance` value of the PCA output features in the `machine_learning_models` and `principal_component_analysis_models` system catalog tables.
```sql SQL theme={null}
CREATE MLMODEL pca2 TYPE PRINCIPAL COMPONENT ANALYSIS ON (
SELECT x,
y,
z
FROM mldemo.clusters_3d
);
Modified 0 rows
SELECT importance
FROM sys.machine_learning_models a,
sys.principal_component_analysis_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'pca2';
importance
--------------------------------------------------------------------------------
[0.3688781607553818, 0.3333390832624229, 0.2977827559821952]
Fetched 1 row
```
In this case, all three PCA output features are fairly evenly weighted. By removing the last feature, the model covers only about 70% of the signal. This strongly indicates that proceeding with a two-feature model would be problematic and inaccurate.
### Linear Discriminant Analysis
While PCA is unsupervised, linear discriminant analysis (LDA) is a supervised dimensionality reduction algorithm. LDA works only with numeric classification algorithms, but the classification can be binary or multi-class. Hence, LDA understands how the data should be used, making it operate differently.
Creating an LDA model is mostly similar to PCA. One difference is that LDA also requires a class or label.
This tutorial uses the three-dimensional cluster data that the PCA model struggled to work with. The example uses LDA to reduce the features of the cluster data by using the label already contained in the data set.
```sql SQL theme={null}
CREATE MLMODEL lda1 TYPE LINEAR DISCRIMINANT ANALYSIS ON (
SELECT x,
y,
z,
label
FROM mldemo.clusters_3d
);
Modified 0 rows
```
As with PCA, there is an `importance` column in the system catalog tables.
```sql SQL theme={null}
SELECT importance
FROM sys.machine_learning_models a,
sys.linear_discriminant_analysis_models b
WHERE a.id = b.machine_learning_model_id
AND name = 'lda1';
importance
--------------------------------------------------------------------------------
[1.0000000000000133, -1.4051695910079908E-20, -1.3342566035320652E-14]
Fetched 1 row
```
This output strongly indicates that only the first LDA output feature matters, which means that it is possible to make a single feature classification model.
This example takes the LDA-reduced model as input and uses it to create a neural network model, using the `FEEDFORWARD NETWORK` model. Note that this model uses the `cross_entropy_loss` option to enable multi-class classification.
```sql SQL theme={null}
CREATE MLMODEL three_d_clusters_with_1_feature TYPE FEEDFORWARD NETWORK ON (
SELECT lda1(x, y, z, 1),
CASE
WHEN label = 'LEFT' THEN { { 1.0,
0.0,
0.0 } }
WHEN label = 'RIGHT' THEN { { 0.0,
1.0,
0.0 } }
ELSE { { 0.0,
0.0,
1.0 } }
END AS target
FROM mldemo.clusters_3d
) options(
'metrics'->'true',
'hiddenLayers'->'2',
'hiddenLayerSize'->'4',
'outputs'->'3',
'lossFunction'->'cross_entropy_loss',
'useSoftMax'->'true'
);
Modified 0 rows
```
Execute the model for a new point to see if it returns a reasonable value.
```sql SQL theme={null}
SELECT three_d_clusters_with_1_feature(lda1(0, 0, 0, 1)) AS predicted;
predicted
--------------------------------------------------------------------------------
[[0.007386760165583984, 0.0022085315302674473, 0.9904047083041486]]
Fetched 1 row
```
In this case, the query asks for a prediction for the input `0, 0, 0`. This input first passes through the LDA model because that is what the neural network model was built on.
The query asks the LDA model for its first component, and then runs the neural network on that value. The neural network outputs a vector of class probabilities; `VECTOR_ARGMAX` returns the 1‑based index of the highest probability.
In this example, the highest probability class is the third class, which the query defines as `CENTER`.
```sql SQL theme={null}
SELECT count(*) / 1000000.0
FROM mldemo.clusters_3d
WHERE (
VECTOR_ARGMAX(
three_d_clusters_with_1_feature(lda1(x, y, z, 1))
) = 1
AND label = 'LEFT'
)
OR (
VECTOR_ARGMAX(
three_d_clusters_with_1_feature(lda 1(x, y, z, 1))
) = 2
AND label = 'RIGHT'
)
OR (
VECTOR_ARGMAX(
three_d_clusters_with_1_feature(lda1(x, y, z, 1))
) = 3
AND label = 'CENTER'
);
(_count(*)_0)/((1000000.0))
----------------------------
0.818108
Fetched 1 row
```
This model is nearly 82 percent accurate despite being simplified from three features to one. While the accuracy is worse, the time required to train this model is greatly reduced.
## Related Links
[Machine Learning Model Functions](/machine-learning-model-functions)
[Clustering and Dimension Reduction Models](/clustering-and-dimension-reduction-models)
# Clustering and Dimension Reduction Models
Source: https://docs.ocient.com/clustering-and-dimension-reduction-models
Train and apply OcientML clustering and dimensionality reduction models including k-means and PCA, with SQL syntax, model options, and example queries.
supports these machine learning models for clustering and dimension reduction.
To create the model, use the `CREATE MLMODEL` syntax. For details, see [CREATE MLMODEL](/machine-learning-model-functions).
Model option names are case-sensitive.
## Principal Component Analysis
Model Type: `PRINCIPAL COMPONENT ANALYSIS`
Principal Component Analysis (PCA) is typically not used as a model on its own. PCA is most commonly used on the inputs to other models. PCA serves two purposes.
1. PCA normalizes all numeric feature data. Some types of models are sensitive to the scale of numeric features, and when different features have different scales, the results end up skewed. PCA normalizes all features to the same scale.
2. PCA is used for dimensionality reduction. PCA computes linear combinations of the original features to put the most signal into a smaller number of new features.
The input result set when creating a PCA model is N numeric columns, which are all features. There is no label or dependent variable. After you create a PCA model, the `sys.principal_component_analysis_models` system catalog table contains information on the percentage of the signal in each PCA feature. You can use this information to figure out how many of the output features to keep.
Also, after you create the model, you can see its details by querying the `sys.machine_learning_models` and `sys.machine_learning_model_options` system catalog tables.
### Principal Component Analysis and Logistic Regression
You can also use PCA models as inputs to other models. For example, if you have three features and you want to use PCA to reduce the number to two features, you can execute the following SQL statements.
```sql SQL theme={null}
CREATE MLMODEL reduceTo2
TYPE PRINCIPAL COMPONENT ANALYSIS ON (
SELECT
c1,
c2,
c3
FROM public.my_table
);
```
You can use this model as input for another model, for example, logistic regression.
```sql SQL theme={null}
CREATE MLMODEL binaryClass
TYPE LOGISTIC REGRESSION ON (
SELECT
reduceTo2(c1, c2, c3, 1),
reduceTo2(c1, c2, c3, 2),
label
FROM …
);
```
To correctly use this model later, you must pass the original features through the PCA model when you execute the logistic regression model.
```sql SQL theme={null}
SELECT
binaryClass(
reduceTo2(x1, x2, x3, 1),
reduceTo2(x1, x2, x3, 2)
)
FROM … ;
```
Similarly, to create a PCA analysis over four variables, execute this SQL statement:
```sql SQL theme={null}
CREATE MLMODEL my_model
TYPE PRINCIPAL COMPONENT ANALYSIS ON (
SELECT
c1,
c2,
c3,
c4
FROM public.my_table
);
```
### **Model Options**
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
## K-Means Clustering
Model Type: `KMEANS`
K-means is an unsupervised clustering algorithm. All of the columns in the input result set are features, and there is no label. All the input columns must be numeric. The algorithm finds `k` points such that all points are classified by the closest `k` points. Distance calculations are Euclidean by default.
### **Model Options**
#### Required
`k` — This option must be a positive integer. The option specifies the algorithm for how many clusters to make.
#### Optional
`epsilon` — If you specify this option, the value must be a valid positive floating point value. When the maximum distance that a centroid moves from one iteration of the algorithm to the next is less than this value, the algorithm terminates. This parameter defaults to `1e-4`.
`normalize` — If you set this option to `true`, the model normalizes the data before the start of training. The default value is `true`.
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
### **Execute the Model**
Create a K-means model with `8` clusters.
```sql SQL theme={null}
CREATE MLMODEL my_model
TYPE KMEANS
ON (
SELECT
x1,
x2,
x3,
x4
FROM public.my_table
)
options(
'k' -> '8'
);
```
Also, after you create the model, you can see its details by querying the `sys.machine_learning_models` and `sys.machine_learning_model_options` system catalog tables.
Because there are no labels for clusters, when you execute this function after training with the same number (and same order) of features as input, the result is an integer that specifies the cluster to which the point belongs.
```sql SQL theme={null}
SELECT my_model(x1, x2, x3, x4) FROM my_table;
```
After you execute a model, you can find the details about the execution results in the `sys.k_means_models` system catalog table.
For details, see the description of the associated system catalog tables in the Machine Learning section in the [System Catalog](/system-catalog#page-title).
## Gaussian Mixture
Model Type: `GAUSSIAN MIXTURE MODEL`
Gaussian Mixture Models (GMMs) find the mixture of `N` Gaussian distributions that best fit the data. The most common use is unsupervised clustering, but there are some key differences compared to K-means clustering:
* GMMs can handle clusters that are not circular, i.e., clusters in the shape of ovals or higher-dimensional analogs with variances in different directions.
* Clusters can have an arbitrary rotation, i.e., they can have covariance.
* GMMs can handle instances when clusters are not as equally likely. If a point is right between two clusters, it is more likely to be more common in the training data.
* GMMs can show the probability of a new point belonging to each cluster instead of providing only a single cluster value.
GMMs generally handle more complex data than K-means models, but they require more training and processing time during execution.
### Model Options
#### Required
`numDistributions` — Must be a positive integer. This value specifies the number of clusters of Gaussian distributions for the model to make.
#### Optional
`epsilon` — If you specify this option, the value must be a valid positive floating point value. When the maximum distance that the entire best model moves in its n-dimensional space is less than this value, the algorithm terminates. This parameter defaults to 1e-8 (0.00000001 as a decimal number).
`normalize` — If you set this option to `true`, the model automatically computes the mean and standard deviation of each feature and uses them to normalize the data during training. Defaults to `true`.
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
### Execute the Model
Create a GMM with three clusters of Gaussian distributions.
```sql SQL theme={null}
CREATE MLMODEL gmm
TYPE GAUSSIAN MIXTURE MODEL
ON (
SELECT
x,
y,
z
FROM my_table
)
options(
'numDistributions' -> '3'
);
```
Also, after you create the model, you can see its details by querying the `sys.machine_learning_models` and `sys.machine_learning_model_options` system catalog tables.
When you execute this function after training with the same number (and same order) of features as input, the result is an integer that specifies the probable cluster to which the point belongs.
```sql SQL theme={null}
SELECT gmm(x,y,z) FROM my_table;
```
After you execute a model, you can find the details about the execution results in the `sys.gaussian_mixture_models` system catalog table.
For details, see the description of the associated system catalog tables in the Machine Learning section in the [System Catalog](/system-catalog).
## Linear Discriminant Analysis
Model Type: `LINEAR DISCRIMINANT ANALYSIS`
Linear Discriminant Analysis (LDA) is a dimension-reduction technique similar to PCA. While PCA is unsupervised, LDA can classify and use class labels to find linear combinations of features that best separate the classes.
The input result set when you create an LDA model is `N` numeric columns that are all features. The last column is a class label and can be any data type. After you create an LDA model, the `sys.linear_discriminant_analysis_models` system catalog table contains information on the percentage of the signal that is in each LDA feature. You can use this information to figure out how many of the output features to keep.
Also, after you create the model, you can see its details by querying the `sys.machine_learning_models` and `sys.machine_learning_model_options` system catalog tables.
### Linear Discriminant Analysis and Logistic Regression
You can use LDA models as inputs to other models. For example, to reduce the number of features from three to two using LDA, you can execute these SQL statements.
```sql SQL theme={null}
CREATE MLMODEL reduceTo2
TYPE LINEAR DISCRIMINANT ANALYSIS ON (
SELECT
c1,
c2,
c3,
label
FROM public.my_table
);
```
You can use this model as input for another model, for example, logistic regression.
```sql SQL theme={null}
CREATE MLMODEL binaryClass
TYPE LOGISTIC REGRESSION ON (
SELECT
reduceTo2(c1, c2, c3, 1),
reduceTo2(c1, c2, c3, 2),
label
FROM …
);
```
To correctly use this model later, you must pass the original features through the LDA model when you execute the logistic regression model.
```sql SQL theme={null}
SELECT
binaryClass(
reduceTo2(x1, x2, x3, 1),
reduceTo2(x1, x2, x3, 2)
)
FROM … ;
```
Similarly, to create an LDA model over four variables, execute this SQL statement.
```sql SQL theme={null}
CREATE MLMODEL my_model
TYPE LINEAR DISCRIMINANT ANALYSIS ON (
SELECT
c1,
c2,
c3,
c4,
label
FROM public.my_table
);
```
### **Model Options**
`normalize` — If you set this option to `true`, the model automatically computes the mean and standard deviation of each feature and uses them to normalize the data during training. Defaults to `true`.
`featureArray` — If you set this option to `true`, the model expects only one array-type column as input instead of multiple columns of training data. Each array row in the input column must be of the same size. Regardless of whether you use this option, the model treats training data the same with labeling and weight scoring. The default value is `false`.
`loadBalance` — If you set this option, the database appends the `USING load_balance_shuffle = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified option value (`true` or `false`). The default value is unspecified. In this case, the database does not add this clause.
`queryInternalParallelism` — If you set this option, the database appends the `USING parallelism = ` clause to all intermediate SQL queries the model executes during training where `value` is the specified positive integer value. The default value is unspecified. In this case, the database does not add this clause.
`skipDropTable` — If you set this option to `false`, the database deletes any intermediate tables created during model training. If you set this option to `true`, the database prevents the deletion of any intermediate tables created during model training. The default value is `false`.
### Execute the Model
When you execute the trained LDA model, you must provide the same original input features in the same order, followed by a positive integer argument that specifies the LDA component to return. The LDA component index starts at 1.
```sql SQL theme={null}
SELECT
my_model(col1, col2, col3, col4, 2) as component2,
my_model(col1, col2, col3, col4, 3) as component3,
FROM public.my_table;
```
## Bibliography
Bahmani, Bahman, Benjamin Moseley, Andrea Vattani, Ravi Kumar, and Sergei Vassilvitskii. “Scalable K-Means++.” Proceedings of the VLDB Endowment 5, no. 7 (2012): 622–33. [https://doi.org/10.14778/2180912.2180915](https://doi.org/10.14778/2180912.2180915).
## Related Links
[Classification Models](/classification-models)
[Other Models](/other-models)
[Machine Learning Models](/machine-learning-models)
#
# Commands Supported by the Ocient JDBC CLI Program
Source: https://docs.ocient.com/commands-supported-by-the-ocient-jdbc-cli-program
Reference for commands supported by the Ocient JDBC CLI program, including session management, query execution, file output, and SQL script execution.
Commands are not case-sensitive in the JDBC CLI program.
For DDL statements, see [Data Definition Language (DDL) Statement Reference](/data-definition-language-ddl-statement-reference).
All commands, except QUIT, must end with a semicolon at the command line.
You can cancel any query that does not update data by pressing CTRL+C.
The Ocient JDBC driver supports multi-statement transactions. By default, a connection uses the autocommit mode, in which the database commits each statement immediately. To group several statements into a single transaction, disable autocommit with [SET AUTOCOMMIT](#set-autocommit), and then end the transaction with [COMMIT](#commit) or [ROLLBACK](#rollback).
The HTTP Query API does not support transactions. To use transactions, connect to the Ocient System with the JDBC driver or the pyocient module.
The Connector supports transactions and performs the commit and rollback actions automatically. When you use the Spark Connector, you do not need to issue COMMIT or ROLLBACK commands.
### CANCEL
Cancels the current query that is still running on the system.
**Syntax**
```shell Shell theme={null}
CANCEL uuid;
```
| **Parameter** | **Data Type** | **Description** |
| ------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| uuid | String | A query Universally Unique IDentifier (UUID) that is currently running. Use [LIST ALL QUERIES](#list-all-queries), or search the `sys.queries` table to find the UUID. You must enclose the UUID in single quotes, such as `'c87b506f-66d6-4987-8bf7-1fd4a06b64b1'`. |
### COMMIT
Commits the current transaction and permanently saves all changes made after the transaction started. This command applies only when you disable autocommit with [SET AUTOCOMMIT](#set-autocommit). When autocommit is enabled, COMMIT has no effect.
**Syntax**
```shell Shell theme={null}
COMMIT [ TRANSACTION ];
```
Entering the COMMIT command with no other arguments commits the current transaction on the connection. This action is equivalent to calling the `commit()` method on the JDBC Connection object.
### CONNECT
Connects to a SQL Node. For details on the connection steps, see [Connect Using JDBC](/connect-using-jdbc).
**Syntax**
```shell Shell theme={null}
CONNECT TO [ USER username USING password ]
```
The `` parameter must follow this format:
`jdbc:ocient://node_address1:port1[,node_address2:port2[,...]]/database_name[;property=value[;...]]`
If you do not specify the `username` and `password`, then the database uses the default credentials specified at startup.
**JDBC URL parameters**
| **Parameter** | **Description** |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `node_address` | A hostname or IP address. The database attempts to connect using each `DNSName:Port` pair in the comma-delimited list from left to right until a successful connection happens. |
| `port` | Standard JDBC port number is `4050`. For details about ports, see [Ports](/ocient-simulator#ports). |
| `database_name` | The identifier used for your database. |
**Additional JDBC URL Parameters**
The JDBC URL can include these optional parameters in the key-value format `property=value`. Separate each parameter pair by semicolons.
URL parameters are case-insensitive.
To authenticate using Single Sign-On, set the `handshake` parameter to `SSO` and leave the `user` and `password` parameters empty. For example: `jdbc:ocient://DNSName:Port[,IP2:Port2,...]/databaseName;handshake=SSO;user=;password=;`
| **Parameter** | **Description** |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bulkLoadChunkSize` | The number of rows to include in each JSON data file (chunk) uploaded. The default value is `60000`. |
| `bulkLoadCleanupOnFailure` | If you set this parameter value to `true`, the driver deletes the temporary files and pipelines even if the load fails. The default value is `true`. |
| `bulkLoadFailOnError` | If you set this parameter value to `true`, `executeBatch()` fails if any `INSERT` operation fails.
If you set this parameter value to `false`, `executeBatch()` falls back to a standard multi-row `INSERT` operation if any INSERT operation fails. The default value is `false`. |
| `bulkLoadLoaderNodesCacheSeconds` | The number of seconds to cache the list of active Loader Nodes the system discovers during bulk load. When you set this parameter to a value greater than `0`, the driver caches the Loader Node list for the specified duration and forwards the same value as a server-side `CACHE_MAX_TIME` hint on the lookup query. This cache is -wide and is not specific to individual connections. Do not enable this parameter if your application connects to multiple Ocient clusters from the same JVM. The default value is `0` (disabled). |
| `bulkLoadMode` | The bulk load transport mode. Set this parameter to `ssh` to stage data using SSH/SFTP to Loader Nodes, or set it to `s3` to stage data in an S3-compatible object store. The default value is `ssh`. |
| `bulkLoadPollIntervalSeconds` | The number of seconds to wait between polling the `sys.pipelines` system catalog table for load status. The default value is `2`. |
| `bulkLoadS3AccessKeyId` | The access key identifier for authenticating to the S3 endpoint. This parameter is required when you set the `bulkLoadMode` parameter to `s3`. |
| `bulkLoadS3ApiCallTimeoutMs` | The timeout, in milliseconds, for individual S3 API calls. The default value is `120000` (two minutes). |
| `bulkLoadS3Bucket` | The S3 bucket name for staging bulk load data files. This parameter is required when you set the `bulkLoadMode` parameter to `s3`. |
| `bulkLoadS3EnablePathStyleAccess` | If you set this parameter to `true`, the driver uses path-style access for S3 requests (e.g., `http://endpoint/bucket/key` instead of `http://bucket.endpoint/key`). This parameter is required for S3-compatible services such as MinIO or Ceph. The default value is `true`. |
| `bulkLoadS3Endpoint` | The S3-compatible endpoint URL for bulk load staging (e.g., `https://s3.us-east-1.amazonaws.com`). This parameter is required when you set the `bulkLoadMode` parameter to `s3`. |
| `bulkLoadS3MultipartPartSize` | The size, in bytes, of each part in a multipart upload. The minimum value is `5242880` (5 MiB). The default value is `10485760` (10 MiB). |
| `bulkLoadS3MultipartThreshold` | The size, in bytes, above which the driver uses multipart upload instead of a single PUT request. The default value is `10485760` (10 MiB). |
| `bulkLoadS3Prefix` | The key prefix for staged objects in S3. The default value is `ocient-bulk-load/`. |
| `bulkLoadS3Region` | The AWS region for the S3 endpoint. The default value is `us-east-1`. |
| `bulkLoadS3SecretAccessKey` | The secret access key for authenticating to the S3 endpoint. This parameter is required when you set the `bulkLoadMode` parameter to `s3`. |
| `bulkLoadS3UploadConcurrency` | The number of data chunks to upload to S3 in parallel. Increasing this value can improve staging throughput for large batches. The default value is `1`. |
| `bulkLoadSshChannelTimeoutSeconds` | The number of seconds to wait for an SFTP channel to open on an established SSH connection during bulk load. If the channel does not open within this duration, the driver throws an error. The default value is `30`. |
| `bulkLoadSshConnectTimeoutSeconds` | The number of seconds to wait for the SSH connection and authentication to a Loader Node during bulk load. If the system does not establish a connection within this duration, the driver throws an error. The default value is `10`. |
| `bulkLoadSshKeyPath` | The absolute path to the password-less private SSH key file. The default value is `~/.ssh/id_rsa`. |
| `bulkLoadSshHostKeyVerification` | Controls how the JDBC driver verifies an SSH server host key for bulk load connections.
Supported values are:
`acceptAll` (default) — The driver accepts all host keys. The connector does not check the server host key against the `known_hosts` file and does not output warning logs. `strict` — The driver accepts only hosts with keys present in the `known_hosts` file (see the `bulkLoadSshKnownHostsPath` parameter). The driver rejects unknown hosts or hosts with changed keys. `acceptNew` — The driver accepts new hosts and adds their keys to the `known_hosts` file, but rejects hosts with keys changed from the data in `known_hosts`. |
| `bulkLoadSshKnownHostsPath` | The path to the `known_hosts` file, which contains SSH verification keys. The system uses this path only if the `bulkLoadSshHostKeyVerification` parameter is set to `strict` or `acceptNew`.
The default path is `~/.ssh/known_hosts`. |
| `bulkLoadSshUser` | The SSH username to use when connecting to Loader Nodes. |
| `bulkLoadThreshold` | The minimum number of rows in a batch group to trigger a bulk load. The default value is `25000`. |
| `bulkLoadUseAtomicPipeline` | If you set this parameter to `true`, bulk load uses an atomic pipeline that creates, starts, and monitors the pipeline in a single blocking operation `(CREATE TRANSACTIONAL PIPELINE ... START FOREGROUND)`. This mode requires the Ocient System version 27.1 or later.
Set this parameter to `false` to use the legacy create, start, monitor, and drop functionality when connecting to older servers. The default value is `true`. |
| `defaultSchema` | Default schema. |
| `enableBulkLoad` | Enables the high-speed bulk load feature. Set this parameter value to `true` to enable this feature. Otherwise, set this parameter to `false` to leave the feature disabled. The default value is `false`. |
| `force` | If set to true (case-sensitive), this parameter disables load-balancing for the connection. |
| `handshake` | Specifies the handshake protocol used for the connection. Supported options include: `"CBC", "GCM", "SSO"` `"GCM"` — (Galois/Counter Mode). This is the default encryption and is the recommended password encryption algorithm. `"CBC"` — (Cipher Block Chaining) for password encryption. `"SSO"` — Single Sign-On. |
| `identityprovider` | An SSO integration established in the database. For details, see [CREATE SSO INTEGRATION](/cluster-and-node-management#create-sso-integration). |
| `logfile` | The filename to use for JDBC tracing. |
| `loglevel` | If set to ERROR (warnings and errors only) or DEBUG (verbose tracing) and logfile is also set, JDBC tracing is enabled. This parameter is case-sensitive. |
| `longQueryThreshold` | Estimated query runtime in milliseconds before deeper query optimization runs. `0` — Use database server default. `-1` — Never run deeper optimization. |
| `maxRows` | Maximum allowed result set size in the number of rows. |
| `maxRowsPerInsertBatch` | The maximum number of rows to combine into a single multi-row `INSERT` SQL statement when executing a batch load. If the total number of rows in a batch group exceeds this limit, the driver splits the group into multiple sub-statements.
The default value is 128,000 rows. |
| `maxTempDisk` | Maximum allowed temp disk usage as a percentage (0 - 100). |
| `maxThreadsPerResultSet` | The maximum number of threads the client uses to fetch rows from the server per Result Set, as defined in the [official JDBC documentation](https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html). In this context, a thread represents a logical connection to the database. Applications that create and operate on Statement objects concurrently might find value in setting this parameter. Defaults to `0`, which effectively creates an unbounded Result Set thread pool. |
| `maxTime` | Maximum allowed runtime of a query in seconds before it is canceled on the server. |
| `networkTimeout` | Network connection timeout in milliseconds. If unspecified, this defaults to 10000 milliseconds. |
| `parallelism` | Limits a query to running on a specified number of cores on each CPU. |
| `password` | The password for the user. |
| `priority` | Query priority. This sets the priority for queries to run on the server side. If unspecified, this defaults to `1.0`. |
| `priorityAdjustFactor` | The default query priority adjustment value. For details, see [SET ADJUSTFACTOR](/commands-supported-by-the-ocient-jdbc-cli-program#set-adjustfactor). |
| `priorityAdjustTime` | The default frequency to adjust the query priority. For details, see [SET ADJUSTTIME](/commands-supported-by-the-ocient-jdbc-cli-program#set-adjusttime). |
| `serviceClassName` | Specifies the name of the service class to use for the database session. |
| `sparkMode` | When you set this parameter to `true`, the driver enables -specific JDBC behavior intended to improve compatibility with the Ocient Spark connector. For details, see [JDBC Spark Connector](/jdbc-spark-connector).
This parameter defaults to `false` if you are connecting directly using the Ocient JDBC driver (e.g., connecting with the `DriverManager` class or CLI). Otherwise, if you are using the Spark connector (catalog or `.format("ocient")`), the default is `true`. |
| `ssoNumericAddress` | Specifies the SSO callback URL as `127.0.0.1`. When this value is `false`, the URL is `localhost`. The default value is `false`. |
| `ssoOAuthCodeCallbackPort` | If `ssoOAuthFlow=authorizationCode`, this parameter specifies the port that the SSO authorization uses. If unspecified, the default value is `7050`. |
| `ssoOAuthFlow` | This parameter is only applicable if SSO authorization is enabled. Forces the driver to use either the "authorizationCode" or "deviceGrant" flow to establish a Single Sign-On session. If this parameter is not provided, the System uses the "authorizationCode" flow when a web browser is available to the client and the "deviceGrant" flow when a web browser is not available to the client. |
| `ssoDebugMode` | When set to `true`, the system records additional log messages related to SSO. |
| `ssoOktaNativeTokenPath` | The path to the Native Token (AES-256GCM JWE). The path is relative to your home directory (i.e. '\~/'). |
| `ssoSslCallback` | Specifies whether to use HTTPS instead of HTTP for the SSO callback URL. The default value is `false`. |
| `ssoTimeoutSeconds` | The number of seconds before the SSO connection request times out. The default value is `60`. |
| `statementPooling` | ℹ️ This parameter has been removed as of Ocient JDBC version 2.104 and later. When set to `ON`, recently used statements are cached. Set to `OFF` when using a third-party application that implements statement pooling |
| `tls` | Can be set to `unverified` or `on`. Enables SSL/TLS encryption for the connection. |
| `timeoutMillis` | Number of milliseconds before cancellable operations are timed out and killed by the driver. 0 means no timeout. Default: 0 |
| `user` | The identifier of the user. |
The JDBC driver also supports system properties that apply globally across all connections. To set these properties, use the `-D` flag at JVM startup. For details, see [JVM System Properties](/jdbc-manual#jvm-system-properties).
### DESCRIBE TABLE
Lists the columns of the specified table and its associated data types.
**Syntax**
```shell Shell theme={null}
DESCRIBE TABLE [schema.]table [verbose]
```
| **Parameter** | **Description** |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `table` | A table identifier. |
| `schema` | A qualifying schema name for the specified table. If a qualifying schema is not specified for the table, the default name schema is assumed. |
| `verbose` | If specified, the Ocient System prints the full column metadata for the specified table as returned by GetColumns. |
### DESCRIBE VIEW
Returns the query text used to create the specified view.
**Syntax**
```shell Shell theme={null}
DESCRIBE VIEW [schema.]view [verbose]
```
| **Parameter** | **Description** |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `view` | A view identifier. |
| `schema` | A qualifying schema name for the specified table. If a qualifying schema is not specified for the table, the default name schema is assumed. |
| `verbose` | If specified, the Ocient System prints the full column metadata for the specified table as returned by GetColumns. |
### EXTRACT
Extracts a result set in delimited files to a specified location. For details about using this command, see [Data Extract Tool](/data-extract-tool).
**Syntax**
```sql SQL theme={null}
EXTRACT TO location
{ LOCAL | S3 }
[ OPTIONS ( [ param=value [ ,... ] ] ) ] AS query
```
### GET JDBC VERSION
Returns the JDBC version of the driver.
**Syntax**
```shell Shell theme={null}
GET JDBC VERSION
```
### GET SCHEMA
Retrieves the default name schema for tables.
**Syntax**
```shell Shell theme={null}
GET SCHEMA
```
### KILL
Issues a hard kill command to the virtual machine to terminate a query running on the system. Use only if `CANCEL` fails.
**Syntax**
```shell Shell theme={null}
KILL uuid
```
| **Parameter** | **Description** |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `uuid` | A query UUID that is currently running. Use [LIST ALL QUERIES](#list-all-queries), or search the `sys.queries` table to find the UUID. |
### LIST ALL QUERIES
List all the currently executing queries on the database. This is the equivalent of executing `SELECT * FROM sys.queries`.
**Syntax**
```shell Shell theme={null}
LIST ALL QUERIES
```
### LIST INDEXES
Lists the indexes on the specified table and its columns.
**Syntax**
```shell Shell theme={null}
LIST INDEXES [schema.]table [verbose]
```
| **Parameter** | **Description** |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `table` | A table identifier. |
| `schema` | A qualifying schema name for the specified table. If a qualifying schema is not specified for the table, the default name schema is assumed. |
| `verbose` | If specified, the Ocient System prints the full column metadata for the specified table as returned by getIndexInfo. |
### LIST SYSTEM TABLES
Lists all system catalog tables in the database.
**Syntax**
```shell Shell theme={null}
LIST SYSTEM TABLES [verbose]
```
| **Parameter** | **Description** |
| ------------- | --------------------------------------------------------------------------------------- |
| `verbose` | If verbose is specified, the full table metadata, as returned by getTables, is printed. |
### LIST TABLES
Lists all tables (in all schemata) in the database.
**Syntax**
```shell Shell theme={null}
LIST TABLES [verbose]
```
| **Parameter** | **Description** |
| ------------- | --------------------------------------------------------------------------------------- |
| `verbose` | If verbose is specified, the full table metadata, as returned by getTables, is printed. |
### LIST VIEWS
Lists all views (in all schemata) in the database.
**Syntax**
```shell Shell theme={null}
LIST VIEWS [verbose]
```
| **Parameter** | **Description** |
| ------------- | -------------------------------------------------------------------------------------- |
| `verbose` | If verbose is specified, the full table metadata, as returned by getViews, is printed. |
### OUTPUT GIS KML
Outputs the next query in KML format to the specified filename. This flag affects only the next query.
This syntax prints out all GIS types to the KML file, and non-GIS types are added to the description of elements in the same row. You can upload this KML file to certain visualization tools.
**Syntax**
```shell Shell theme={null}
OUTPUT GIS KML
```
| **Parameter** | **Description** |
| ------------- | ------------------------------ |
| `filename` | A filename for the KML output. |
### OUTPUT NEXT QUERY
Output the next query in CSV format to the specified filename. This flag only affects the next query. All subsequent queries print out their results.
Add `APPEND` to add output to the specified file instead of overwriting it.
**Syntax**
```shell Shell theme={null}
OUTPUT NEXT QUERY filename [APPEND]
```
| **Parameter** | **Description** |
| ------------- | ------------------------------ |
| `filename` | A filename for the CSV output. |
### PERFORMANCE
Enables different levels of query result output for measuring benchmarks by using different performance options.
**Syntax**
```shell Shell theme={null}
PERFORMANCE [ NETWORK | DATABASE | OFF ]
```
| **Parameter** | **Description** |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `OFF` | This is the default mode. The system executes a query through all normal stages, including the database, client network, and client processing. |
| `NETWORK` | The system executes a query through the database and client network, but discards rows before they are processed by the client (nothing is printed to stdout). Use this mode when you think the client network is hindering performance. |
| `DATABASE` | The system executes a query through the database only. The database does not send any matching rows to the client. Use this mode when you think the database query execution is affecting performance. |
`PERFORMANCE ON` mode has been removed as of JDBC version 3.0.
### QUIT
Closes the command-line interface.
**Syntax**
```shell Shell theme={null}
QUIT
```
### REPORT LOG ON
Enables -based metrics collection and redirects reporting events to the configured appenders.
The `REPORT LOG ON` command requires JDBC driver version 2.88 or later.
The Log4j configuration determines the destination for report logs. The Ocient logger name is `com.ocient.util.ReportLogger`. For details about configuring Log4j, see [the Log4j documentation](https://logging.apache.org/log4j/2.x/manual/configuration.html).
The default Log4j configuration routes report logs to the `RollingFileAppender`. The default configuration includes these settings:
**Properties**
* `fileName="logs/${sys:ocient.jdbc.sessionId:-unknown}/report.log"`
* `filePattern="logs/${sys:ocient.jdbc.sessionId:-unknown}/%d{yyyy-MM-dd}-%i-report.log.gz"`
**Rollover Policies**
* `TimeBasedTriggeringPolicy`
* `SizeBasedTriggeringPolicy (100MB)`
You can retrieve the default configuration from the `ocient-jdbc4` jar file by using an archive utility like **unzip**. For example:
```shell Shell theme={null}
unzip -p log4j2.xml
```
**Syntax**
```shell Shell theme={null}
REPORT LOG ON [ interval ]
```
| **Parameter** | **Description** |
| ------------- | ----------------------------------------------------------------------------------------------- |
| `interval` | Optional. Sets the Log4j reporting interval in seconds. If unspecified, defaults to `30`. |
### REPORT LOG OFF
Disables file-based metrics collection.
The `REPORT LOG OFF` command requires JDBC driver version 2.88 or later.
**Syntax**
```shell Shell theme={null}
REPORT LOG OFF
```
### ROLLBACK
Rolls back the current transaction and discards all changes made after the transaction started. This command applies only when you disable autocommit with [SET AUTOCOMMIT](#set-autocommit). When autocommit is enabled, ROLLBACK has no effect.
**Syntax**
```shell Shell theme={null}
ROLLBACK [ TRANSACTION ];
```
Entering ROLLBACK with no other arguments rolls back the current transaction on the connection. This action is equivalent to calling the `rollback()` method on the JDBC Connection object.
### SELECT
Retrieves the appropriate result set of a SQL `SELECT` statement.
**Syntax**
```shell Shell theme={null}
SQL select statement
```
### SET AUTOCOMMIT
Enables or disables the autocommit mode for the connection. When autocommit is enabled, the database commits each statement immediately. This mode is the default. When autocommit is disabled, the database groups statements into a transaction that you complete with the [COMMIT](#commit) or [ROLLBACK](#rollback) commands.
When you change autocommit from `OFF` to `ON`, the database commits any pending transactions.
**Syntax**
```shell Shell theme={null}
SET AUTOCOMMIT { ON | OFF }
```
Enables or disables autocommit mode with values `ON` or `OFF`, respectively. When you enter the `ON` value, the database commits each statement immediately. This value is the default. When you enter the `OFF` value, the database groups subsequent statements into a transaction until you enter the COMMIT or ROLLBACK command.
### SET MAXROWS
Sets the maximum number of rows allowed in a result set. Applies only to the statement object that executed the command.
**Syntax**
```shell Shell theme={null}
SET MAXROWS num_of_rows
```
| **Parameter** | **Description** |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `num_of_rows` | The maximum number of rows allowed in a result set. If a query returns more rows than the specified value, the result set is truncated by `num_of_rows`. To disable this setting, you can either set the maximum rows to 0 or use the `RESET` keyword (e.g., `SET MAXROWS RESET;`). |
### SET ADJUSTFACTOR
Adjusts the query priority by a specified percentage amount at every interval set by the [SET ADJUSTTIME](#set-adjusttime) command.
The `SET ADJUSTFACTOR` command requires JDBC driver version 2.52 or later.
**Syntax**
```shell Shell theme={null}
SET ADJUSTFACTOR priorityAdjustFactor
```
| **Parameter** | **Description** |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `priorityAdjustFactor` | A percentage amount to raise or lower the query priority. Accepted values are in the range of \[-1,1]. At every interval set by the `priorityAdjTime`, the query priority is multiplied by `1 + priorityAdjustFactor` to get a new priority value. |
### SET ADJUSTTIME
Modifies how frequently the query priority is adjusted during the course of execution.
The `SET ADJUSTTIME` command requires JDBC driver version 2.52 or later.
**Syntax**
```shell Shell theme={null}
SET ADJUSTTIME priorityAdjTime
```
| **Parameter** | **Description** |
| ----------------- | ---------------------------------------------------------- |
| `priorityAdjTime` | The frequency for adjusting the query priority in seconds. |
### SET MAXTEMPDISK
Sets the maximum percentage of temporary disk used by queries. Applies only to the statement object that executed the command.
**Syntax**
```shell Shell theme={null}
SET MAXTEMPDISK percentage
```
| **Parameter** | **Description** |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `percentage` | The maximum percentage of temporary disk used by queries. Any queries exceeding this threshold are killed. To disable this setting, use the `RESET` keyword (e.g., `SET MAXTEMPDISK RESET;`). |
### SET MAXTIME
Sets the maximum query time. Applies only to the statement object that executed the command.
**Syntax**
```shell Shell theme={null}
SET MAXTIME seconds
```
| **Parameter** | **Description** |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `seconds` | The maximum query time. Queries longer than this are killed. To disable this setting, you can either set the maximum time to 0 or use the `RESET` keyword (e.g., `SET MAXTIME RESET;`). |
### SET PARALLELISM
Sets a limit on the number of cores on each CPU that can be allocated to running the query. Applies only to the statement object that executed the command.
The `parallelism` value limits a query to running on the specified number of cores on each CPU.
**Syntax**
```shell Shell theme={null}
SET PARALLELISM parallelism
```
| **Parameter** | **Description** |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `parallelism` | Limits a query to running on a specified number of cores on each CPU. To disable this setting, you can either set the `parallelism` value to -1 or use the `RESET` keyword (e.g., `SET PARALLELISM RESET;`). |
### SET PRIORITY
Sets the scheduling priority to use for queries. Applies only to the statement object that executed the command.
**Syntax**
```shell Shell theme={null}
SET PRIORITY priority
```
| **Parameter** | **Description** |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `priority` | The scheduling priority to use for queries. Set from 0 to 100. To disable this setting, you can either set the priority to -1 or use the `RESET` keyword. (e.g., `SET PRIORITY RESET;`). |
### SET SCHEMA
Changes the default schema for tables. Applies only to the statement object that executed the command.
**Syntax**
```shell Shell theme={null}
SET SCHEMA schema
```
| **Parameter** | **Description** |
| ------------- | ---------------------------------- |
| `schema` | The default schema for new tables. |
### SET SERVICECLASS
Limits a query to using the specified service class. Applies only to the statement object that executed the command.
**Syntax**
```shell Shell theme={null}
SET SERVICECLASS service_class_name
```
| **Parameter** | **Description** |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `service_class_name` | The service class that a query is limited to using. To disable this setting, you can use the `RESET` keyword. (e.g., `SET SERVICECLASS RESET;`). |
### SOURCE
Reads and executes commands found in the specified file.
**Syntax**
```shell Shell theme={null}
SOURCE filename
```
| **Parameter** | **Description** |
| ------------- | ------------------------- |
| `filename` | A valid filename or path. |
### TIMING
Enables or disables reporting the execution time of each query.
**Syntax**
```shell Shell theme={null}
TIMING { ON | OFF }
```
## Related Links
[JDBC Manual](/jdbc-manual)
[System Catalog](/system-catalog)
# Compute-Adjacent Input and Output on Large Working Sets
Source: https://docs.ocient.com/compute-adjacent-input-and-output-on-large-working-sets
Ocient compute-adjacent storage architecture co-locates compute and NVMe storage to deliver high throughput on large working sets and analytic queries.
The storage of the data warehouse and the input and output (I/O) layer is built using a (CASA). When contrasted against modern cloud-based database engines, this means that the majority of the data to be analyzed is stored on NVMe SSDs directly attached to a significant fraction of the computational capacity of the system using the local PCIe busses of the nodes that make up the ***foundation level*** of the database engine.
This approach, which is similar to a traditional MPP architecture, is designed to capitalize on the performance characteristics of NVMe SSDs when executing queries against a large ***working set*** of data. It is important to note that when executing a query, a specific record could be included as part of the results, but I/O and computational effort must be undertaken to make that determination. A working set, therefore, is defined as the set of records stored in the database that are considered as part of query execution, even if those records are eventually filtered out or not returned. A "large" working set is one that is substantially larger, even by multiple orders of magnitude, than the available DRAM on the set of nodes performing the computations. When this is the case, ***remote-object*** database engines that store the majority of their data in a separate storage layer are substantially affected by their inability to keep all the potentially-addressed records near and accessible to computation at the same time. Depending on the query load and their exact engine design and scheduling, query execution times negatively suffer from both simple bottlenecks due to network link capacity and "cache thrashing" that produces expensive extra drive I/O.
Large working sets can be realized in two major ways:
1. Queries that regularly consider a substantial fraction of the entire data set. For example, regular querying or analysis of all data spanning years can mean a single query addresses most of the records in the database.
2. A large number of smaller queries that all consider a disjoint subset of the whole data set. When these queries are executed in parallel the sum total of the disjoint sets of addressed records can also approach most of the records in the database.
The database engine in the System is a world-class relational database engine that can go toe-to-toe with other modern engines on small working sets but won’t necessarily out-perform them. After all, well known algorithms like sorting and hashing can only be made so fast when everything is in memory. But the performance distinctions of Ocient derive from its ability to scale CASA to keep all of the data close to the computation.
## NVMe SSDs in CASA
One of the biggest drivers for the development of the was the ongoing shift from spinning HDDs to NVMe SSDs for data storage. SSD prices continue to fall, relative to HDDs, and there remains little doubt that they will eventually supplant HDDs for all but esoteric or extreme bulk storage applications.
To ride this storage wave, the Ocient engine has been built to minimize the cost of using these drives as the primary storage tier of the engine while maximizing their performance. There are two major aspects to cost management:
1. *Minimization of the total number of stored bytes needed to achieve reliable access to data in a performant manner*. This is achieved using a novel and tunable ***erasure coding*** scheme in conjunction with a variety of compression techniques. This is detailed more thoroughly in the following sections.
2. *Consideration for endurance management in I/O operations against the NVMe SSDs.* The Ocient storage and execution engine is designed to minimize the number of I/O write operations undertaken against the storage media in order to maximize its lifetime and reduce drive replacement rate due to endurance wear. At a high level, this usually means minimizing small or random writes to the drives and instead favoring larger and sequential ones. To achieve this, the storage layer uses a specially-written and database-aware file system underneath storage structures designed to capitalize on the large volume of low-mutability data being stored. Using these mechanisms, the storage layer is able to collate writes in a manner that produces relatively large (from the drive’s point of view) ranges of contiguous blocks, ordered in the hundreds of KiB to hundreds of MiB in size.
## Erasure Coding
Of particular note in the storage and I/O layer of the OcientAIQ Unified Data Platform is the novel use of a tunable erasure coding scheme for data storage.
You can think of erasure coding as a generalization of simple XOR parity calculations. In a simple error correction scheme, you can apply the XOR operation on a sequence of bits: `B0, B1, B2, ..., Bn` such that: `B0 XOR B1 XOR ... XOR Bn = Bx`. An easily provable property of the XOR operation is that for any single Bi with 0 ≤ i ≤ n, that `B0 XOR ... XOR Bi-1 XOR Bi+1 XOR ... XOR Bn XOR Bx = Bi`. You can determine any single bit by performing the XOR operation on the other original bits and the extra bit together. In the context of error correction, this means that for the cost of an extra bit of storage (or memory) a system is able to detect, and even correct for, the loss of a single bit.
There are a variety of error correction schemes described in computer science and found in the industry. In the application of this concept to database storage, the Ocient storage layer extends it from individual bits, and beyond bytes, to an error correction unit of the 4KiB block (which is notably aligned with the I/O resolution of standard NVMe SSD drives). It also further extends from enabling single loss or failure to a fully tunable approach that uses ***XOR***, ***P+Q***, or ***Cauchy-Reed-Solomon*** coding that allows the user to specify exactly how many faults: one, two, or K, respectively. Like the simple XOR formulation, these schemes utilize mathematical computations (in this case, polynomials over a finite/Galois field) to compute additional blocks of data that enable reconstructing a configurable number of missing blocks.
In database and storage systems that utilize replication to provide data reliability and availability, it is common to describe storage in terms of the number of replicas (e.g., 3x replication allows for up to three failures). The obvious implication of replication is that each replica is a full copy of the original data and represents a multiple of the minimal data storage required. In an erasure coding scheme, the overhead for `K` tolerable faults is calculated as `(N + K)/N`, where `N` is the total width and `K` is parity width. If `N` is 10 (take that as a given for the moment) then to support a maximum of 2 faults (the equivalent of 3x replication, which includes the original data and two copies) the system needs only `12 / 10 = 1.2x` times the original storage size, contrasted with the 3x of the replication scheme.
The utilization of space-efficient erasure coding can be found in a variety of storage and transmission systems, but, in a classic space-time trade-off, the space savings come at a computational cost. The approach taken in the Ocient storage layer is novel, at least for databases, and is designed to mitigate the computational overhead of erasure coding.
If one considers a "file" of some size as a unit of storage, a basic approach for applying an erasure coding scheme to provide loss tolerance to this file would be to break it into `N` chunks and perform the requisite computation to produce an additional `K` chunks. At read time, the system would select an available subset of the `N+K` chunks (possibly preferring the original `N`) and perform the **rebuild** computation to produce the original file for access. In this framing the unit of fault tolerance is the individual file, and rebuilding computational overhead can be found in the read path.
However, in a database designed for OLAP-style queries, the potential for the overhead of any rebuilding computation in the read path even when no drives or nodes are offline is troublesome. Additionally, when the system is in a degraded state, the potential need to rebuild an entire file only to retrieve a small subset of its data is expensive as well. The Ocient storage layer, by directly implementing the erasure coding scheme and integrating with it, avoids these issues in two major ways.
The first advantage is the unit of storage. Ocient uses storage units named ***segments***, which are not chunked into `N` pieces. Instead, `N` separate and similarly sized segments are considered together as a unit named a ***segment group***. The erasure coding scheme is then applied across the segments to produce `K` additional "segments" worth of redundancy information, which, in a very loose application of the term, is named ***parity data***.
This graphic shows a high-level illustration of how Ocient stores each data segment. Segments contain all the data needed for a subset of table rows, including the actual column data as well as indexes, metadata, and statistical data such as probability density functions (PDFs) and count distinct estimates (CDEs). In addition, the erasure coding scheme also includes parity data for other segments in the same segment group.
The newly generated parity data is then broken up and evenly distributed amongst the original segments (in a particular and calculated way) such that each segment is now approximately
`(N+K)/N` times larger than it originally was, and any missing segment from a particular segment group can be reconstructed when one has access to any set of `N` segments from the same group. The Ocient storage layer ensures that each segment from a group is stored on a separate physical node, thereby providing data availability in the event of up to `K` node losses.
Another important feature of this scheme is due to the fact that a given record is always stored in a single segment. Because the segments themselves are not chunked, any specified record is guaranteed to exist intact on some node/drive, and readable with no overhead incurred when that drive is online. Put another way, in the non-degraded state, the reliability scheme implemented incurs no computational cost.
The second advantage of the Ocient System is each segment acts as a self-contained unit of information, containing not only database records but also metadata and indexes on those records. These sub-units within the segment, named ***segment parts*** are individually addressable and independently rebuildable with 4KiB resolution. The implication of this is that in a degraded state (where a node or drive is missing), it is not strictly necessary to rebuild all missing segments to service a specified query. Instead, the storage layer is capable of addressing and rebuilding only the parts and even single blocks of parts required for it. This often greatly reduces the overhead and performance impact of a degraded state.
## Choice of "N"
Earlier, it was taken as a given that `N` is equal to 10. The exact choice of this value is somewhat arbitrary but is generally bounded by system-level consensus constraints as well as the calculated cost of the network transit during rebuild operations. As `N` increases, the storage overhead for the data reliability for some specified `K` *decreases* because `(N+K)/N` approaches 1. However, the total amount of information that must be considered and moved over the network for, as well as the actual computational cost of, a rebuild *increases*. Real-world usage has found that an `N` somewhere between 8 and 12 provides a good tradeoff between these two opposing considerations.
## NVMe Userspace Optimizations
A final important aspect of the Ocient storage and I/O layer is the database engine’s direct interaction with the SSDs storing segments. The term "direct" in this context can be contrasted with how a more standard approach might look. In many database systems, record storage is achieved using a set of files stored on a disk in some file system (such as EXT4, NTFS, or ZFS). And generally speaking, kernel-provided system invocations or services, like `read()`, `write()`, and `mmap()`, perform reading and writing of those files. Obviously, this is a fine approach in general, but when performance is of utmost importance, the overhead of the system calls, memory copies to and from kernel memory, as well as the implementation of the underlying file systems, all have detrimental and sometimes unpredictable effects. For example, it is well known that the kernel of EXT4 implementation takes global locks during certain metadata operations, which can have a significant detrimental effect on parallelism and throughput.
Some databases eschew standard files and perform some form of I/O directly against kernel block devices in order to avoid file system overhead. This is surely an improvement, but the kernel’s block scheduler, extra memory copies to/from kernel memory, and the overhead of system calls still exist.
In order to overcome these performance impacts, the Ocient storage layer directly interacts with the NVMe SSDs that store segments in two important ways:
1. Each NVMe drive is decoupled from the standard Linux block device driver and instead attached to a device driver that enables low-level interaction with the device using the PCIe protocol. The implications of this approach are that the storage layer and database engine can directly communicate the NVMe protocol to the devices *and* do so using user memory. This completely eliminates all system calls and memory copies required to do I/O with the NVMe drives. The database provides direct pointers to its own virtual memory for I/O operations, and the drives directly write and read to and from that memory.
An interesting result from this approach is that the Ocient storage layer and engine were entirely unaffected by the Linux kernel’s mitigations for the Spectre and Meltdown classes of attacks. This is because the primary mechanism of the mitigation resulted in a substantial increase in the overhead of the user-to-kernel transition associated with system calls. Other database engines with more standard approaches saw, in many cases, appreciable performance degradation.
2. Modern NVMe SSDs are capable of a million 4KiB random reads per second. This is strikingly and substantially more than HDDs (where even the best drives can produce only hundreds). However, for most economical SSDs, these rates can only be achieved when large numbers of parallel in-flight requests are maintained over a substantial fraction of the drive’s address
space. The Ocient storage layer implementation, in conjunction with specially tailored data and metadata structures, not only promotes this parallelism to be evoked during query execution, but also is written to minimize "latency bubbles" by always having a replacement I/O operation teed up for a drive when it completes a previous one.
## Columnar Compression
As a column-oriented data warehouse, Ocient is able to leverage per-column data locality and similarity to achieve excellent data compression.
* For fixed-length columns, a combination of delta-delta compression, run-length encoding, and NULL elimination provides significant storage reduction for many data types.
* For variable-length columns, the Ocient System can apply per-row compression to reduce the size of large values.
* Both fixed and variable-length columns can benefit from whole-column compression using a shared dictionary trained on a per-column and per-segment basis.
Column compression works best when combined with secondary indexes on frequently filtered columns.
## Related Links
[Secondary Indexes](/secondary-indexes)
[Key Concepts](/key-concepts)
## Related Videos
[At the Whiteboard with Ocient: Compute Adjacent Storage Architecture™](https://www.youtube.com/watch?v=7cv0hr7f1fg)
***
*Linux® is the registered trademark of Linus Torvalds in the U.S. and other countries.*
# Configuration Settings for Data Pipelines
Source: https://docs.ocient.com/configuration-settings-for-data-pipelines
Reference for Ocient data pipeline configuration settings, including JVM memory, S3 timeouts, Kafka polling, Parquet memory limits, and file system access.
Data pipeline functionality enables the use of SQL statements to load data. You can use a variety of configuration settings to manage the load. See this table for the settings that you can use.
| **Configuration Setting Parameter Name** | **Default** | **Data Type** | **Description** |
| ------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `streamloader.extractorEngineParameters.enabled` | `true` | BOOLEAN | Whether the Loader Node attempts to bootstrap the extractor process for data pipelines on start-up. If you set this parameter to `true`, the Loader Node does not become active until the Java loading process has successfully started. |
| `streamloader.extractorEngineParameters.jvmMemoryConfiguration` | - `32g` for `initialHeap` - `64g` for `maxHeap` - `64g` for `maxDirect` | VARCHAR | The memory configuration to use for the extractor Java process. Use strings representing data sizes in SI format: 1 KiB, 5 MiB, etc. You must set the three memory options in the same statement.
**Example** `ALTER SYSTEM ALTER CONFIG SET 'streamloader.extractorEngineParameters.jvmMemoryConfiguration.initialHeap' = '32g',` `'streamloader.extractorEngineParameters.jvmMemoryConfiguration.maxHeap' = '64g',` `'streamloader.extractorEngineParameters.jvmMemoryConfiguration.maxDirect' = '64g';` |
| `streamloader.extractorEngineParameters.restPort` | 8090 | INT | Use this parameter with the `streamloader.extractorEngineParameters.portOffset` parameter to form the REST port for the extractor. (External monitoring services like can query the REST server for loading process metrics.) |
| `streamloader.extractorEngineParameters.portOffset` | 0 | INT | Use this parameter with the `streamloader.extractorEngineParameters.restPort` parameter to form the REST port of the extractor. (External monitoring services like Telegraf can query the REST server for loading process metrics.) |
| `streamloader.extractorEngineParameters.configurationOption.expect.empty.file.list` | `false` | BOOLEAN | Set this value to `false` to fail a file source data pipeline that finds no files to load instead of the load completing successfully with no data loaded. |
| `streamloader.extractorEngineParameters.configurationOption.pipeline.preview.rows.limit` | 1000 | INT | The maximum number of rows a `PREVIEW PIPELINE` SQL statement can return. For example, when you use this statement, if the specified `LIMIT` value exceeds this number, then the loading process throws an error. |
| `streamloader.extractorEngineParameters.configurationOption.engine.transform.udt.jarRootDirectory` | `/opt/ocient/current/lib/extractorengine_udt` | VARCHAR | The absolute path to the directory containing JARs for data pipeline functions. To install and enable a third-party library for using data pipeline functions, install the JAR package at this location on all Loader Nodes. Then, add the chosen fully-qualified class name to the IMPORT clause of the data pipeline function. For details, see [CREATE OR REPLACE PIPELINE FUNCTION](/data-pipelines#create-pipeline-function). |
| `streamloader.extractorEngineParameters.configurationOption.engine.external.jdbc.jarRootDirectory` | `/opt/ocient/current/lib/extractorengine_jdbc` | VARCHAR | The absolute path to the directory containing JARs for external source lookup functionality. For details, see [Load Data from External Sources in Data Pipelines](/load-data-from-external-sources-in-data-pipelines). |
| `streamloader.extractorEngineParameters.configurationOption.source.record.max.size` | Dynamically calculated value at start-up based on the number of processors and amount of memory available to the JVM | BIGINT | The maximum source record size, in bytes, that the loading process tolerates before throwing an error. |
| `streamloader.extractorEngineParameters.configurationOption.s3.region` | `us-east-1` | VARCHAR | The default region for S3 file sources. |
| `streamloader.extractorEngineParameters.configurationOption.s3.force.path.style.access` | `false` | BOOLEAN | Set this value to `true` to use path-style access for all S3 file sources. The default is a virtual-hosted style. |
| `streamloader.extractorEngineParameters.configurationOption.s3.force.path.style.access.if.endpoint.overriden` | `true` | BOOLEAN | Set this value to `true` to use path-style access for S3 file sources that specify endpoints. (The system still uses virtual-hosted style access for sources without endpoint overrides unless you set `streamloader.extractorEngineParameters.configurationOption.s3.force.path.style.access` to `true`). |
| `streamloader.extractorEngineParameters.configurationOption.s3.retries.count` | 10 | INT | The number of retries for the S3 file source client. |
| `streamloader.extractorEngineParameters.configurationOption.s3.netty.read.timeout.seconds` | 0 | INT | The timeout value for read operations, in seconds, for the S3 file source client. `0` means do not perform a timeout. |
| `streamloader.extractorEngineParameters.configurationOption.s3.netty.max.concurrency` | 50 | INT | Maximum number of allowed concurrent requests for the S3 file source client. |
| `streamloader.extractorEngineParameters.configurationOption.awssdk.backoff.strategy.base.delay.seconds` | 1 | INT | The base amount of time, in seconds, for calculating the time the S3 file source client waits before retrying a failed request. The range of values that the calculated time can achieve increases exponentially with each failure. You can set the maximum value using the `streamloader.extractorEngineParameters.configurationOption.awssdk.backoff.strategy.max.backoff.seconds` parameter. |
| `streamloader.extractorEngineParameters.configurationOption.awssdk.backoff.strategy.max.backoff.seconds` | 20 | INT | The maximum amount of time the S3 file source client waits before retrying a failed request. |
| `streamloader.extractorEngineParameters.configurationOption.awssdk.max.pending.connection.acquires` | 20000 | INT | The maximum number of pending connection acquires that the S3 file source client allows. |
| `streamloader.extractorEngineParameters.configurationOption.awssdk.connection.timeout.seconds` | 10 | INT | The amount of time, in seconds, that the S3 file source client waits when initially establishing a connection. |
| `streamloader.extractorEngineParameters.configurationOption.awssdk.connection.max.idle.timeout.seconds` | 300 | INT | The maximum amount of time, in seconds, that the system allows a connection established by the S3 file source client to remain open while idle. |
| `streamloader.extractorEngineParameters.configurationOption.awssdk.connection.acquisition.timeout.seconds` | 300 | INT | The amount of time, in seconds, that the S3 file source client waits when acquiring a connection from the pool. |
| `streamloader.extractorEngineParameters.configurationOption.kafka.poll.timeout.msec` | 1000 | BIGINT | The amount of time, in milliseconds, that a consumer for a pipeline with an source waits for records to become available during a poll operation. |
| `streamloader.extractorEngineParameters.configurationOption.kafka.assign.timeout.msec` | 20000 | BIGINT | The amount of time, in milliseconds, that a `PREVIEW PIPELINE` SQL statement waits for partitions to be assigned to the consumer on a pipeline with a Kafka source. If the system does not assign any partitions when the timeout elapses, then the `PREVIEW PIPELINE` statement terminates without data processing. |
| `streamloader.extractorEngineParameters.configurationOption.kafka.activate.timeout.msec` | 5000 | BIGINT | The amount of time, in milliseconds, that a `PREVIEW PIPELINE` SQL statement waits for a partition to receive records on a pipeline with a Kafka source. |
| `streamloader.extractorEngineParameters.configurationOption.arrow.max.native.memory.usage.bytes` | 23756537856 | BIGINT | The default maximum native memory usage, in bytes, for the reader. |
| `streamloader.extractorEngineParameters.configurationOption.arrow.max.java.buffer.memory.usage.bytes` | 15837691904 | BIGINT | The default maximum buffer memory usage, in bytes, for the Parquet reader. |
| `streamloader.extractorEngineParameters.configurationOption.filesystem.access.directories` | `/tmp` | VARCHAR | Comma-separated list of directories where you can load server file system data.
Each directory must exist.
All files must be located within one of the directories.
By default, you can load from the `/tmp` directory. |
## Related Links
[Load Data](/load-data)
[Alter Default Data Pipeline Behavior](/alter-default-data-pipeline-behavior)
# Configure Data Pipeline Logging
Source: https://docs.ocient.com/configure-data-pipeline-logging
Adjust log levels for Ocient data pipelines with the ALTER SYSTEM ALTER LOG LEVEL SQL command to troubleshoot loading issues without impacting performance.
You can troubleshoot data pipelines using the standard logging mechanism in .
Set these log levels in consultation with Ocient Support because this setting might impact performance.
## Modify the Level of Logging
Execute these two SQL statements in this order to bump up the log message.
First, set the log level.
```sql SQL theme={null}
ALTER SYSTEM ALTER LOG LEVEL SET 'log4j' 'EDEBUG';
```
Then, set the level for the logging configuration.
```sql SQL theme={null}
ALTER SYSTEM ALTER CONFIG SET 'streamloader.extractorEngineParameters.loggingConfig.com.ocient.extractor.allowLevel' 'trace';
```
If the log level of the first SQL statement is lower than the log level of the second SQL statement, the system loses log entries.
It is also possible to repeat the second SQL statement for different package names, such as:
* `ALTER SYSTEM ALTER CONFIG SET 'streamloader.extractorEngineParameters.loggingConfig.com.ocient.extractor.allowLevel' 'Info';`
* `ALTER SYSTEM ALTER CONFIG SET 'streamloader.extractorEngineParameters.loggingConfig.com.ocient.extractor.en gine.allowLevel' 'Trace';`
## Valid Log Levels
This table provides an overview of the log levels you can specify for the `ALTER SYSTEM ALTER LOG LEVEL SET` SQL statements with the `streamloader.extractorEngineParameters.loggingConfig` keys. The necessary log level for `log4j` must be set accordingly to at least the value specified in the column for the `log4j` level.
| **Log Level of** `streamloader.extractorEngineParameters.loggingConfig` | **Derived Level for** `log4j` |
| ----------------------------------------------------------------------- | ----------------------------- |
| FATAL | ERROR |
| ERROR | ERROR |
| WARN | WARN |
| INFO | INFO |
| DEBUG | DEBUG |
| TRACE | EDEBUG |
## Reset the Log Level
To reset the log level after you reproduce a problem, execute these SQL statements.
```sql SQL theme={null}
ALTER SYSTEM ALTER CONFIG RESET 'streamloader.extractorEngineParameters.loggingConfig.com.ocient.extractor.allowLevel';
ALTER SYSTEM ALTER CONFIG RESET 'log4j';
```
## Related Links
[Monitor Data Pipelines](/monitor-data-pipelines)
[Data Pipeline Loading Errors](/data-pipeline-loading-errors)
# Configure Storage Spaces
Source: https://docs.ocient.com/configure-storage-spaces
Configure storage spaces in an Ocient System, including segment group width, parity width, and overprovisioning for fault tolerance and capacity planning.
When setting up an System, a storage cluster represents a set of Foundation Nodes in the system. A storage space is a set of parameters within a storage cluster that defines how the system administers data and fault tolerance.
Creating a storage space is an important step for launching an Ocient System that must be done after installing hardware and bootstrapping nodes, but before you start loading and querying data. To see how creating a storage space fits into the Ocient installation process, see [Ocient Application Configuration](/ocient-application-configuration).
This tutorial explains how to set up and configure storage spaces to meet the needs of your Ocient System.
When an Ocient System starts, the system automatically creates a default system storage space for persistent metadata, such as system catalog tables. This default storage space is immutable, meaning you cannot delete or modify it.
The name of the metadata storage space is `systemStorageSpace` in the [sys.storage\_spaces](/system-catalog#sys-storage_spaces) system catalog table.
## User-Defined Storage Spaces
For storage other than metadata, you must create one or more separate storage spaces. The creation of storage spaces is necessary before loading data or performing other operations. User-defined storage spaces are configurable for extra resiliency or storage based on your system needs.
A storage space represents how the storage cluster spreads data across Foundation Nodes to balance storage and fault tolerance. In general terms, the storage cluster configuration defines how the storage cluster behaves for these attributes:
* Regular data storage operations (see [Segment Group Width](#segment-group-width))
* Query resiliency (see [Parity Width](#parity-width))
* Load resiliency (see [Overprovision](#overprovision))
You can configure a storage space to assign nodes to these job roles by using DDL statements (see [CREATE STORAGESPACE](/cluster-and-node-management#create-storagespace)).
Planning out your storage space carefully is important because you cannot change a storage space configuration after creation.
### **Segment Group Width**
Storage space parameter: `WIDTH`
The Segment Group Width determines the number of segments that comprise a segment group. Functionally, this setting defines how many Foundation Nodes perform read and write operations for a segment group.
Within a Segment Group, the system assigns each segment to a different node. Hence, the Segment Group Width cannot exceed the number of nodes in your system.
In most circumstances, Segment Group Width should comprise most of your Foundation Nodes. On system startup, the default Segment Group Width is three, which is the minimum number of nodes required for an Ocient System.
### Parity Width
Storage space parameter: `PARITY_WIDTH`
You can assign a subset of the Segment Group Width to Parity Width.
The Parity Width of a storage space determines its fault tolerance, defining the number of parity coding bits to use for each segment group. This number determines how many nodes can fail before the cluster is disabled.
Parity Width protects system querying capabilities. If any nodes fail, the system can execute and complete queries as long as the number of failed nodes is less than or equal to the Parity Width. When deployed in conjunction with overprovisioned nodes, Parity Width also provides fault tolerance for loading operations.
The `PARITY WIDTH` requires additional storage overhead, which is calculated by the formula `(PARITY WIDTH) / (SEGMENT GROUP WIDTH - PARITY WIDTH)`.
### Overprovision
The Ocient System overprovisions any Foundation Nodes in the cluster in excess of the Segment Group Width by default. These nodes can include any nodes not configured in the storage space or any nodes added later.
Overprovisioned nodes protect loading operations from node failure, although they must be used in conjunction with Parity Width. In the event of node failures, loading operations can continue as long as the number of failed nodes does not exceed the Parity Width nodes or the number of overprovisioned nodes. For this reason, providing fault tolerance for loading requires a balance of Parity Width and overprovisioned nodes.
Unlike Segment Group Width and Parity Width, you do not explicitly define a value for overprovisioning. Instead, any Foundation Nodes in the cluster in excess of the number allocated toward Segment Group Width or Parity Width become overprovisioned by default.
## Storage Space Configuration Examples
This section demonstrates different configurations for storage spaces. The examples each go through different scenarios for node failures to show the fault tolerance of each setup.
For information on the syntax for storage spaces, see [CREATE STORAGESPACE](/cluster-and-node-management).
### 10-Node Cluster
This example assumes you have a storage cluster of 10 Foundation Nodes.
```sql SQL theme={null}
CREATE STORAGESPACE ocient WIDTH = 10, PARITY_WIDTH = 2;
```
* The `WIDTH = 10` parameter means the system stores a segment group on 10 different nodes.
* The `PARITY_WIDTH = 2` parameter means each segment in the group contains enough parity bits to restore lost data for up to two nodes. In effect, this means parity bits comprise 20 percent of storage.
**Tolerance Scenarios**
This storage space setup has no overprovisioning, making loading operations less resilient. This setup results in these outcomes if nodes become disabled:
* If one node fails, loading fails, and querying can continue.
* If two nodes fail, loading fails, and querying can continue.
* If three nodes fail, loading and querying both fail.
### 12-Node Cluster
This example assumes a storage cluster of 12 Foundation Nodes.
```sql SQL theme={null}
CREATE STORAGESPACE ocient WIDTH = 10, PARITY_WIDTH = 2;
```
Note that this DDL statement is the same as the [10-Node Cluster Example](#10-node-cluster), but the cluster in this example has two additional nodes.
* The `WIDTH = 10` parameter means the system stores a segment group on 10 of the 12 nodes.
* The two remaining nodes are overprovisioned.
* The `PARITY_WIDTH = 2` parameter means each segment in the group contains enough parity bits to restore lost data for up to two nodes. In effect, this means parity bits comprise 16.6 percent of storage.
**Tolerance Scenarios**
This setup provides a level of resiliency for both querying and loading. The setup results in these outcomes if nodes become disabled:
* If one node fails, loading and querying continues.
* If two nodes fail, loading and querying continues.
* If three nodes fail, loading and querying both fail.
### 12-Node Cluster with More Parity Width
This example assumes a storage cluster of 12 Foundation Nodes with more nodes allocated to parity.
```sql SQL theme={null}
CREATE STORAGESPACE ocient WIDTH = 10, PARITY_WIDTH = 3;
```
* The `WIDTH = 10` parameter means the system stores a segment group on 10 of the 12 nodes.
* The two remaining nodes are overprovisioned.
* The `PARITY_WIDTH = 3` parameter means each segment in the group contains enough parity bits to restore lost data for up to three nodes. In effect, this means parity bits comprise 42 percent of storage.
**Tolerance Scenarios**
This setup provides resiliency for loading and especially for querying. The setup results in these outcomes if nodes become disabled:
* If one node fails, both loading and querying continue.
* If two nodes fail, both loading and querying continue.
* If three nodes fail, loading fails, and querying continues.
* If four nodes fail, both loading and querying fail.
### 15-Node Cluster
This example assumes a cluster of 15 Foundation Nodes. The configuration in this setup includes five overprovisioned nodes, exceeding the Parity Width nodes. This number of overprovisioned nodes would be inefficient and unable to provide the full benefit in a real system, but this example demonstrates what happens if you added extra nodes at a later time to a cluster, which the storage space would recognize as overprovisioned.
```sql SQL theme={null}
CREATE STORAGESPACE ocient WIDTH = 10, PARITY_WIDTH = 3;
```
* The `WIDTH = 10` parameter means the system stores a segment group on 10 of the 15 nodes.
* The five remaining nodes are overprovisioned.
* The `PARITY_WIDTH = 3` parameter means each segment in the group contains enough parity bits to restore lost data for up to three nodes. In effect, this means parity bits comprise 20 percent of storage.
**Tolerance Scenarios**
This setup provides resiliency for both querying and loading, but having more than three overprovisioned nodes provides no benefit because it exceeds three Parity Width nodes.
This setup results in these outcomes if nodes become disabled:
* If one node fails, loading and querying continue.
* If two nodes fail, loading and querying continue.
* If three nodes fail, loading and querying continue.
* If four nodes fail, loading and querying both fail because this breaches the Parity Width tolerance.
## Related Links
[Core Elements of an Ocient System](/core-elements-of-an-ocient-system)
[Cluster and Node Management](/cluster-and-node-management)
##
# Connect to Ocient
Source: https://docs.ocient.com/connect-to-ocient
Connect client applications to an Ocient SQL Node using JDBC, pyocient, or REST on the default port 4050 with automatic load balancing across nodes.
You can connect to any of the SQL Nodes in an System to run queries or commands. The SQL Node is available by default on port `4050` at the IP address or hostname assigned to the SQL Nodes. When more than one SQL Node is present in the Ocient System, Ocient automatically loads balance connections between the nodes to even out the load across connections.
Ocient provides a JDBC driver and a driver named `pyocient`. You can use any of these drivers to connect to an online Ocient System.
To connect from a client computer that can access the SQL Node using the network, follow any of the following examples. Note that you must have the IP address of the SQL Node and a valid username and password to connect.
* [Connect Using JDBC](/connect-using-jdbc)
* [Connect Using pyocient](/connect-using-pyocient)
If you are unable to connect, check the logs on the SQL Nodes for issues or check the [Errors and Warnings](/errors-and-warnings) for more detail on error codes.
For supported third-party tools, see [Ocient Integrations](/ocient-integrations).
# Connect Using JDBC
Source: https://docs.ocient.com/connect-using-jdbc
Learn how to set up and configure a JDBC connection to Ocient, ensuring secure and efficient data access for large-scale analytics.
The JDBC driver can be executed in a command-line interface (CLI) mode or used directly in a program with standard JDBC methods. This example describes how to connect using the CLI mode. For details on using the JDBC driver in code, please see [Establishing a Connection](https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html).
## Step 1: Download the JDBC Driver
First, confirm the recommended version of the JDBC driver for your version of by finding it in [Version Compatibility](/version-compatibility). Download the correct JDBC driver from the [repository](https://mvnrepository.com/artifact/com.ocient/ocient-jdbc4) by clicking on your preferred version, then selecting **view all**, and finally downloading the JAR file that is labeled with the pattern `ocient-jdbc4--jar-with-dependencies.jar`.
Save this file to a convenient location on your client machine.
## Step 2: Run the JDBC CLI Program
To run the JDBC CLI Program, you must have installed on your machine. For the version, see [Version Compatibility](/version-compatibility). Next, run the following command to start the JDBC CLI Program. Assuming your JAR stored at `~/ocient-jdbc4-jar-with-dependencies.jar`.
```shell Shell theme={null}
java -classpath ~/ocient-jdbc4-jar-with-dependencies.jar com.ocient.cli.CLI
```
The system prompts you to enter the username and password.
```shell Shell theme={null}
Username: test@system
Password: fakepassword
```
**Example Response:**
```shell Shell theme={null}
Ocient> _
```
The Ocient CLI prompt appears.
## Step 3: Connect
To connect, enter the connection string to your SQL Nodes. SQL Nodes install by default with a self-signed TLS certificate for encryption by default, and a custom certificate can be present. Depending on the TLS configuration, you can use `tls=unverified` (default) or `tls=on` for the required setting.
Assuming the standard port `4050`, a self-signed certificate, and the SQL Node IP Address of `10.10.1.1`, you can connect to the system database with the following connecting string:
```shell Shell theme={null}
Ocient> connect to jdbc:ocient://10.10.1.1:4050/system;
```
**Example Response:**
```shell Shell theme={null}
Connected to jdbc:ocient://10.10.1.1:4050/system
Ocient> _
```
You are now connected and can execute queries based on your user’s permissions. Try running: `select * from sys.tables;` to see what tables are defined.
For more details on using the JDBC driver and the CLI program, see the [JDBC Manual](/jdbc-manual).
The system cancels any queries made with the JDBC driver if you perform any of these actions:
* Fetch the entire result set.
* Close the connection.
* Execute a new query on the same connection.
## Related Links
[Connect to Ocient](/connect-to-ocient)
[Ocient Integrations](/ocient-integrations)
# Connect Using pyocient
Source: https://docs.ocient.com/connect-using-pyocient
Follow this guide to establish a Pyocient connection to the Ocient data warehouse, enabling Python-based data operations and analysis.
The module `pyocient` supports direct connections to Ocient Systems in a Command-Line Interface (CLI) as well as in Python programs that follow the Python Database API Specification 2.0.
After you install `pyocient`, you can establish Ocient connections to run queries and commands.
## Installation Tutorial
To install and run `pyocient`, follow these steps.
Install `pyocient` using pip.
```shell Shell theme={null}
pip3 install pyocient
```
After running the pip install, `pyocient` is installed in the `bin` directory.
Use `venv` to install `pyocient` using a virtual environment. For more information, see the Python [venv](https://docs.python.org/3/library/venv.html) documentation.
`pyocient` is started from the command line with a connection string. It includes many options to configure the connection and client similar to the JDBC driver. Learn more about supported options in the [Ocient Python Module: pyocient](/ocient-python-module-pyocient).
After installation, you can launch from a command line by typing the `pyocient` command.
```shell Shell theme={null}
pyocient ocient://example_user:example_password@10.10.1.1/system
```
To connect to the system database, replace the example username (`example_user`) and password (`example_password`) with your credentials, set your IP address,
The connection example assume a SQL Node exists at `10.10.1.1`. The example uses the default port `4050`, and is set up with default self-signed certificates for TLS.
**Example Response**
```SQL SQL theme={null}
Ocient Database™
System Version: , Client Version
> _
```
Use the command `quit;` to exit the `pyocient` CLI interface.
In the `pyocient` CLI, you can run any SQL query supported by your database. In this example, a query is selecting rows from the system tables:
```sql SQL theme={null}
SELECT * FROM sys.tables;
```
You can also run queries from the command line with the connection string:
```shell Shell theme={null}
pyocient ocient://example_user:example_password@10.10.1.1/system 'SELECT * from sys.tables'
```
**Example Response**
```SQL SQL theme={null}
[
{
"id": "359e21b1-770a-4860-aec9-f158d307f725",
"name": "data_type_coverage",
"schema": "loading",
"database_id": "f827ff7c-dd94-43bf-8386-93d048344a32",
"storage_space_id": "2ad08e7c-15d1-4861-b38b-256c4df4a191",
"maximum_segment_size_gib": 4,
"description": null,
"streamloader_property_string": null,
"created_at": "2023-08-08T21:22:49.622213"
}
]
```
The system cancels any queries made with the `pyocient` driver if you perform any of these actions:
* Fetch the entire result set.
* Close the connection.
* Execute a new query using the same connection.
For more information and API reference material for pyocient, see the [Ocient Python Module: pyocient](/ocient-python-module-pyocient) page.
## Related Links
[Connect to Ocient](/connect-to-ocient)
[Ocient Integrations](/ocient-integrations)
# Connection Driver Reference
Source: https://docs.ocient.com/connection-driver-reference
Reference for Ocient connection drivers, including JDBC, ODBC, pyocient, and the HTTP Query API, with version compatibility and integration guidance.
includes multiple ways to connect and issue statements or queries to the database. The most common drivers used for communicating with Ocient are the JDBC driver and the pyocient module. Many third-party tools use the JDBC driver for business intelligence, visualization, and data exploration. These drivers can also be used in custom programs by leveraging the programming language’s appropriate mechanisms to use the driver, for example, using a JDBC driver directly in .
* [JDBC Manual](/jdbc-manual)
* [Data Extract Tool](/data-extract-tool)
* [Commands Supported by the Ocient JDBC CLI Program](/commands-supported-by-the-ocient-jdbc-cli-program)
* [JDBC Classes and Methods](/jdbc-classes-and-methods)
* [JDBC Spark Connector](/jdbc-spark-connector)
* [OCGraph Java Library](/ocgraph-java-library)
* [Ocient Python Module: pyocient](/ocient-python-module-pyocient)
* [OCGraph Python Library](/ocgraph-python-library)
# Conversion Functions
Source: https://docs.ocient.com/conversion-functions
Reference for OcientGeo conversion functions that transform geospatial values between WKT, WKB, GeoJSON, and Ocient native point, linestring, and polygon types.
conversion functions transform a specified operand to a different data type.
## ST\_ASBINARY
Alias of ST\_ASWKB.
Returns the well-known binary (WKB) representation of the specified geography.
**Syntax**
```sql SQL theme={null}
ST_ASBINARY(geo [, XDR_or_NDR ] )
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, or `POLYGON` | The geospatial object used to calculate the dimensions. |
| `XDR_or_NDR` | `CHAR` | Optional. This argument determines whether the resulting WKB is in little endian (NDR) or big endian (XDR) format. If you specify this argument, it must be either `XDR` or `NDR`. Otherwise, it defaults to `NDR`. |
**Example**
```sql SQL theme={null}
SELECT ST_ASBINARY(ST_POINT(2, 2), 'NDR');
```
*Output*: `010100000000000000000000400000000000000040`
## ST\_ASGEOJSON
Returns the GeoJSON representation of the specified geography using the [IETF standards](https://datatracker.ietf.org/doc/html/rfc7946).
```sql SQL theme={null}
ST_ASGEOJSON( geo [, planar_conversion ] )
```
| **Argument** | **Data** **Type** | **Description** |
| ------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, or `POLYGON` | The geospatial object used to create a GeoJSON representation. ℹ️ The GeoJSON specification has certain requirements for a `LINESTRING` and `POLYGON`. In keeping with this specification, a `POLYGON` instance that represents a `LINESTRING` results in a `LINESTRING` GeoJSON instance. Similarly, a `POLYGON` instance that represents a `POINT` results in a `POINT` GeoJSON instance. A `LINESTRING` instance that represents a `POINT` results in a `POINT` GeoJSON instance. Unlike the GeoJSON specification, a specified `POLYGON` does not need to follow the Right-Hand Rule. If a specified `POLYGON` contains any holes that are not valid `POLYGON` objects, then the function omits those holes in the resulting GeoJSON instance. |
| `planar_conversion` | `BOOLEAN` | Optional. A Boolean value that determines if the geodesic edges of the specified geography are converted to planar representation before the function applies the GeoJSON format. standards state that all GeoJSON objects are to be interpreted as explicitly planar. This argument allows preservation of the original geodesic shape. If `planar_conversion` is specified `TRUE`, points will be added such that the resulting GeoJSON represents a planar shape within 10m of the original geospatial object. Additionally, if the original geospatial object crossed the international dateline, it will be split at the point where it crosses. This will generate a GeoJSON object of either `MultiLineString` or `MultiPolygon` type, depending on the original type of the geospatial object. If you do not specify this argument, the value defaults to `FALSE`. |
**Examples**
This example converts a `POINT` value into a GeoJSON representation.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(ST_POINT(2, 2), false);
```
*Output*:
```Text Text theme={null}
{"type":"Point","coordinates":[2,2]}
```
This example converts an empty `POINT` value.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(ST_POINTFROMTEXT('POINT EMPTY'), false);
```
*Output*:
```Text Text theme={null}
{"type":"Point","coordinates":[]}
```
This example converts a `LINESTRING` value into a GeoJSON representation.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(ST_LINESTRING(ST_POINT(1.234, 2),ST_POINT(3.456, 5));
```
*Output*:
```Text Text theme={null}
{"type":"LineString","coordinates":[[1.234,2],[3.456,5]]}
```
This example again converts a `LINESTRING` value.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(ST_LINESTRING(ARRAY[ST_POINT(1.234, 2)]);
```
*Output*:
```Text Text theme={null}
{"type":"Point","coordinates":[1.234,2]}
```
This example converts an empty `LINESTRING` value into a GeoJSON representation.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(ST_LINEFROMTEXT('LINESTRING EMPTY'), false);
```
*Output*:
```Text Text theme={null}
{"type":"LineString","coordinates":[]}
```
This example converts a `POLYGON` value into a GeoJSON representation.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(
ST_POLYGON(
ARRAY [ST_POINT(1.234, 2),ST_POINT(3.456, 5),ST_POINT(5.678, 2),ST_POINT(1.234, 2)],
ARRAY [ARRAY[ST_POINT(2,2.5),ST_POINT(2.1,2.6),ST_POINT(2.2,2.5),ST_POINT(2,2.5)],
ARRAY [ST_POINT(3,2.5),ST_POINT(3.1,2.6),ST_POINT(3.2,2.5),ST_POINT(3,2.5)]]), false);
```
*Output*:
```Text Text theme={null}
{"type":"Polygon","coordinates":[[[1.234,2],[3.456,5],[5.678,2],[1.234,2]],[[2,2.5],[2.1,2.6],[2.2,2.5],[2,2.5]],[[3,2.5],[3.1,2.6],[3.2,2.5],[3,2.5]]]}
```
This example again converts a `POLYGON` value.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(
ST_POLYGON(
ARRAY [ST_POINT(1.234, 2),ST_POINT(3.456, 5),ST_POINT(5.678, 2),ST_POINT(1.234, 2)],
ARRAY [ARRAY[ST_POINT(2,2.5),ST_POINT(2.1,2.6),ST_POINT(2.2,2.5),ST_POINT(3,2.5)],
ARRAY [ST_POINT(3,2.5),ST_POINT(3.2,2.5),ST_POINT(3,2.5)]]), false);
```
*Output*:
```Text Text theme={null}
{"type":"Polygon","coordinates":[[[1.234,2],[3.456,5],[5.678,2],[1.234,2]]]}
```
This example converts a two-point `POLYGON`, which results in a `LINESTRING` type in the GeoJSON representation.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(
ST_POLYGON(
ST_LINESTRING(ST_POINT(1.234, 2), ST_POINT(3.456, 5))),
false);
```
*Output*:
```Text Text theme={null}
{"type":"LineString","coordinates":[[1.234,2],[3.456,5]]}
```
This example converts a single-point `POLYGON`, which results in a `POINT` type in the GeoJSON representation.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(ST_POLYGON(ST_POINT(1.234, 2)), false);
```
*Output*:
```Text Text theme={null}
{"type":"Point","coordinates":[1.234,2]}
```
This example converts an empty `POLYGON` value into a GeoJSON representation.
```sql SQL theme={null}
SELECT ST_ASGEOJSON(ST_POLYGONFROMTEXT('POLYGON EMPTY'), false);
```
*Output*:
```Text Text theme={null}
{"type":"Polygon","coordinates":[]}
```
## ST\_ASLATLONTEXT
Returns a string that represents geographic coordinates of a specified `POINT` in the specified format.
```sql SQL theme={null}
ST_ASLATLONTEXT(point, [ output_format ] )
```
| **Argument** | **Data** **Type** | **Description** |
| --------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `point` | `POINT` | A POINT value used to calculate geographic coordinates. If `point` is NULL, then this function returns NULL. |
| `output_format` | `CHAR` | Optional. A string that includes option flags to set the format and decimal precision for the output of the coordinates. Option flags must be uppercase to be recognized. Accepted option flags are: `D` — Represents coordinate degrees. If you specify a format string for `output_format`, this value is required. If `M` is omitted, this option flag sets the decimal precision. `M` — Represents minutes of latitude or longitude distance. If `S` is omitted, this option flag sets the decimal precision. `S` — Represents seconds of latitude or longitude distance. `C` — Represents the cardinal direction. If you specify this value, the appropriate cardinal direction is represented as N/S/E/W. If you omit this value, coordinates that are south or west are represented as negative values while east or north remain positive values. For all option flags besides `C`, you can repeat the option characters and use them with decimal points to set the format and decimal precision. The number of characters after the decimal point indicates the precision, while the number of characters before the decimal indicates the total width of the formatted number, including the decimal POINT. If the formatted number is shorter than the requested width, the system pads the value with leading spaces. Characters other than `D`, `M`, `S`, `C`, and `.` are passed through as string characters. If you do not specify `output_format` or leave it as empty, the value defaults to the format `D°M''S.SSS"C`. |
**Example**
```sql SQL theme={null}
SELECT ST_ASLATLONTEXT(ST_POINT(10.2342342,-2.32498), 'D.D degrees MM.MM minutes C');
```
*Output*: `'2.0 degrees 19.50 minutes S 10.0 degrees 14.05 minutes E'`
## ST\_ASTEXT
Alias of ST\_ASWKT and ST\_EWKT.
Returns the well-known text (WKT) representation of the specified geography.
If you use `ST_ASEWKT`, the database prepends the resultant string with `SRID=4326;`.
```sql SQL theme={null}
ST_ASTEXT(geo)
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `geo` | `POINT`, `LINESTRING`, or `POLYGON` | A geospatial object that is to be returned as a WKT value. If you specify a `LINESTRING` or `POLYGON` that contains a single `POINT`, the function returns the WKT representation as a `POINT`. If you specify a `POLYGON` that has an exterior that is not closed, the function returns the WKT representation as a `LINESTRING`. |
**Example**
```sql SQL theme={null}
SELECT ST_ASTEXT(ST_POLYGON(ST_LINESTRING('LINESTRING(1 2, 1 3, 1 3, 1 2)')));
```
*Output*: `POLYGON((1 2, 1 3, 1 3, 1 2))`
## ST\_ASEWKT
For usage, see [ST\_ASTEXT](#st_astext).
## ST\_ASWKT
Alias of [ST\_ASTEXT](#st_astext).
## ST\_ASWKB
Alias of [ST\_ASBINARY](#st_asbinary).
## ST\_GEOHASH
Returns a string that represents the geohash of the input `POINT`. This function also accepts an optional second argument to specify the length of the geohash result.
If you specify any argument as NULL, then the function returns NULL.
```sql SQL theme={null}
ST_GEOHASH(point [, precision ] )
```
| **Argument** | **Data** **Type** | **Description** |
| ------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `point` | `POINT` | A `POINT` value that is to be converted into a geohash. |
| `precision` | `INTEGER` | Optional. A numeric value that specifies the geohash precision, which determines the length of the output string. This number must be in the range of 1 to 20. If you do not specify this value, `precision` defaults to 20. |
**Example**
```sql SQL theme={null}
SELECT ST_GEOHASH(ST_POINT(-126, 48));
```
*Output*: `c0w3hc0w3hf1s70w3hf1s70w3`
## Related Links
[Geospatial Data Types](/data-types#geospatial-data-types)
[Attribute Functions](/attribute-functions)
# Core Elements of an Ocient System
Source: https://docs.ocient.com/core-elements-of-an-ocient-system
Explore the core elements of an Ocient System, including SQL Nodes, Foundation Nodes, Loader Nodes, storage clusters, and the global metadata services.
## The System and Nodes
The System is the collection of all the nodes within a single environment. This architecture diagram is an example of one Ocient System. Across systems, the number of nodes can vary along with the total storage capacity. Within a single system, users can define varying numbers of databases, storage groups, users, etc.
An Ocient System is made up of a collection of distributed nodes which each play a predefined role in the data warehouse. The different roles are generally responsible for storing and analyzing data, administration, and moving data into Ocient. These nodes are connected to each other through a high-speed 100 Gbps network connection. In addition to storing user data, the data warehouse also stores metadata about the system and data for its own internal operation and recovery. This collection of nodes, their data, and the interconnection between them make up the Ocient System.
The end user, analyzing data in Ocient, connects to this system through a JDBC or a -based client. From there, they interact with the database objects, such as tables and views. The architecture itself is abstracted from users, allowing them to focus on SQL queries and results.
While the number of nodes in an environment might vary, the inclusion of and purpose of the different roles do not. The following sections briefly describe the components in the architecture.
### Node Types
#### SQL Nodes
A SQL Node is responsible for receiving incoming SQL requests and parsing the statements. This node also serves as the interface for System Administrators and Database Administrators to configure and maintain an Ocient System. Administrators can connect to a SQL Node using the Ocient command-line interface or their chosen client.
When a SQL Node receives a query, it creates a plan for it using one of two optimization methods. After there is a plan for the query, the SQL Node distributes it to the Foundation Nodes. When the Foundation Nodes finish their processing, they return data back to the SQL Node for further processing and packaging the result set to the client. When the result set is finalized, the SQL Node returns the data to the client. Beyond the Foundation Nodes, further processing is done on the SQL Nodes to process intermediate result sets delivered by the Foundation Nodes. Depending on the query, the SQL Node is responsible for a different proportion of the overall work of the query. Common processing done here are aggregations and joins that happen across the intermediate results delivered by the Foundation Nodes.
Administrators also use DDL or DCL statements to make changes to an Ocient System. When submitted to a SQL Node, the node executes the SQL statement across the system or forwards the SQL statement to the node assigned to execute it.
#### Foundation Nodes
The Foundation Nodes store the user data in Ocient and perform the bulk of query processing.
A key architectural concept of Ocient is the , which collocates data and processing where possible. The Foundation Node is the central element of this architectural principle. When a query is deployed to the Foundation Node, it performs as much of the query as it can with the data on the node before having to join, aggregate, or compare it to other data. It returns that result up to the SQL Node for further processing, packaging, and returning to the user.
Foundation Nodes contain the majority of the storage in an Ocient System and are also typically the largest in number.
#### Loader Nodes
Loader Nodes are responsible for extracting, transforming, indexing, and loading data ingested by Ocient from batch file sources as well as streaming data sources such as . A user can specify the extraction source details and supply a transformation pipeline that manipulates the structured or semi-structured source data before loading it into relational form into Ocient tables.
Loader Nodes operate in a horizontal scale-out fashion allowing the loading system to scale to fit various ingestion requirements. Transparently to the end user, the Loader Node also manages exactly-once guarantees with data as it is loaded and converts pages into segments in the Foundation Nodes.
## Flows and Networking Between Nodes
Data and communication flows across the nodes of an Ocient System for a variety of different purposes. There are two networks that connect nodes, a 100 Gbps high speed network and a 10 Gbps network. These are used in different ways for data flows and administrative purposes.
### A Query in Ocient
When a user issues a query against the database, their SQL statement moves from the JDBC client to the SQL Node. The SQL Node parses and optimizes the query before handing the plan off to the Foundation Nodes. The Foundation Nodes do the first level of processing against the data before handing the results back to the SQL Node. The SQL Node further processes the data, constructs the results, and returns them to the client.
* The connection between the SQL Nodes and Foundation Nodes is typically a 100 Gbps network connection. The speed of the connection between the client and the SQL Node is subject to the speed of that network (outside Ocient).
* Every Foundation Node is connected to every SQL Node.
### Administration Flows
When administrators configure or make changes to an Ocient System, they do it using DDL and DCL using a SQL client. The SQL client relays the statement to a SQL Node, which parses it into commands that the Administrator Role on the SQL Node executes. This can impact the SQL Nodes, Foundation Nodes, or Loader Nodes, depending on the type of change or operation.
* The administration flow connections with the Ocient System are 10 Gbps connections.
* Every node is connected to the SQL Nodes that perform the Administrator Role.
### Loading Flow
When the load job is defined and started, the Loader Nodes read data from the source files, stage the data, process that data, and move the data into the Foundation Nodes. Data pipelines enable you to define the data load and any corresponding transformations to ensure data is properly loaded.
* The network connections between the Loader and the Foundation Nodes are 100 Gbps.
* The Loader Nodes connect to every Foundation Node.
## Database, Tables, and Views
Similar to other databases, an is a grouping of databases, schemas, tables, views, users, and data within one Ocient System. A single system can have multiple databases and schemas. Schemas define the structure of a database and contain the definition of tables, views, and indexes. While Ocient stores data on disk in columnar format, creating and working with tables in Ocient is like any other relational database. Ocient supports a wide variety of standard SQL data types along with an expanding set of geospatial data types.
Read more about:
* [Data Definition Language (DDL) Statement Reference](/data-definition-language-ddl-statement-reference)
* [Data Query Language (DQL) Statement Reference](/data-query-language-dql-statement-reference)
* [Functions Overview](/functions-overview)
## TimeKey and Clustering Key
Each table in Ocient can contain a column that is specified when defining the table. The TimeKey column is used to partition the data within the Foundation Nodes. Time partitioning is an important performance mechanism used by the OcientAIQ Unified Data Platform. Because many, if not most, queries specify some time filter for the results, time partitioning allows Ocient to quickly skip data from irrelevant times.
When defining a table, users can also specify a clustering key containing one or more of the columns to further subdivide records on disk. This allows the database to quickly find records with the same key values.
Read more in [TimeKeys and Clustering Keys](/timekeys-and-clustering-keys).
## Resilience to Hardware Failure
In order to provide reliability in the case of a hardware outage, Ocient uses erasure coding. Erasure coding is a mechanism to organize and compute parity blocks so that the system can rebuild missing data. This means that Ocient does not store redundant copies of the data for reliability. As a result, an Ocient System requires less overall storage than if it were storing one or more copies of the data for failover.
When a user defines their storage configuration, they specify the width of the group and the parity width. These values can vary based on how many Foundation Nodes are in the system and how resilient users want to make the Ocient System.
## Segments and Segment Groups
Segments in Ocient are storage units that contain rows and are divided into a fixed number of coding blocks with a defined size. Segments are typically sized on the order of gigabytes. You set the segment size when you define tables in Ocient. The size of the segment must be a multiple of the coding block size. The coding block is the unit of parity calculation and the smallest unit of recovery as well.
Multiple segments combine to form Segment Groups. A Segment Group has a fixed number of segments, named the width, which is the number of segments in the group. It also has a pre-defined number of parity blocks per set of data blocks for resiliency. Each segment has a defined index in the group. The Segment Group is physically stored in a storage cluster. Segment Groups can also be nested in directories named Segment Directory Groups.
When the user configures an Ocient System, they need to define at least one storage space and a storage cluster. A storage cluster is a set of Foundation Nodes with an associated storage space. Also, these nodes coordinate together to store segment groups in a reliable manner. The storage cluster also has a width in the number of nodes. The width of the cluster and the Segment Groups stored on it must be the same. At the storage space level, the user defines the width and parity width of the space. Segments and their Segment Groups are stored across these storage spaces and clusters. To learn more about erasure coding, see [Compute-Adjacent Input and Output on Large Working Sets](/compute-adjacent-input-and-output-on-large-working-sets#erasure-coding).
For details, see [Configure Storage Spaces](/configure-storage-spaces).
## Related Links
* [Ocient Architecture](/ocient-architecture)
* [Compute-Adjacent Input and Output on Large Working Sets](/compute-adjacent-input-and-output-on-large-working-sets)
* [Key Concepts](/key-concepts)
## Related Videos
* [At the Whiteboard with Ocient: Deployment Options](https://youtu.be/gkTb4dRHNKc)
* [At the Whiteboard with Ocient: Data Reliability](https://www.youtube.com/watch?v=MKR8j9kYXvg)
# CREATE TABLE SQL Statement Examples
Source: https://docs.ocient.com/create-table-sql-statement-examples
Examples of the Ocient CREATE TABLE SQL statement showing time-keyed tables, clustering keys, secondary indexes, partitioning, and supported data types.
Tables in the contain various configuration options that can impact performance, reduce storage requirements, or provide extra data safeguards.
As some table configuration options cannot be added after data is already loaded, it is important that you take the time to design `CREATE TABLE` SQL statements with forethought for the queries that you expect to execute frequently. This topic provides examples of `CREATE TABLE` SQL statements designed for different use cases and describes the configuration choices.
For syntax and parameter information, see [CREATE TABLE](/tables#create-table).
## Create a Table with All Data Types
This example creates a table with all supported data types in . The intent of this example is to show the required formatting for different data type values, which is shown as the `DEFAULT` value for each column.
```sql SQL theme={null}
CREATE TABLE data_type_example (
col_bigint BIGINT NOT NULL DEFAULT 9876543210,
col_binary BINARY(3) NOT NULL DEFAULT '0xabcdef',
col_boolean BOOL NOT NULL DEFAULT TRUE,
col_char CHAR(4) NOT NULL DEFAULT 'val',
col_date DATE NOT NULL DEFAULT '2000-01-01',
col_decimal DECIMAL(18,4) NOT NULL DEFAULT 123.45,
col_double DOUBLE NOT NULL DEFAULT 3.141592,
col_float FLOAT NOT NULL DEFAULT 2.718,
col_int INT NOT NULL DEFAULT 123456789,
col_int_array INT[] NOT NULL DEFAULT 'INT[0,1,2,3]',
col_ipv4 IPV4 NOT NULL DEFAULT '127.0.0.1',
col_ip IP NOT NULL DEFAULT '0123:4567:89ab:cdef:0123:4567:89ab:cdef',
col_smallint SMALLINT NOT NULL DEFAULT 32767,
col_matrix MATRIX[2][3] NOT NULL DEFAULT '{ {0, 0, 0}, {0, 0, 0} }',
col_point POINT NOT NULL DEFAULT 'POINT(0 0)',
col_linestring LINESTRING NOT NULL DEFAULT 'LINESTRING(0 0, 1 1)',
col_polygon POLYGON NOT NULL DEFAULT 'POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))',
col_time TIME NOT NULL DEFAULT '12:34:56.012345678',
col_timestamp TIMESTAMP NOT NULL DEFAULT '2000-01-02 12:34:45',
col_tinyint TINYINT NOT NULL DEFAULT 127,
col_tuple TUPLE<> NOT NULL DEFAULT 'tuple<>(0,0)',
col_array_of_tuples TUPLE<>[] NOT NULL DEFAULT 'TUPLE<>[tuple<>(1,2),tuple<>(3,4)]',
col_uuid UUID NOT NULL DEFAULT '01234567-89ab-cdef-1357-0123456789ab',
col_varbinary VARBINARY NOT NULL DEFAULT '0xaabbccddeeff',
col_varchar VARCHAR NOT NULL DEFAULT 'This is a variable length string'
);
```
## Create a Table for Real-Time Analysis
This example assumes you plan to ingest large quantities of time series data for rapid querying. The most important columns that you plan to reference in queries frequently include:
* `created_at` — A granular timestamp column that represents the primary time reference in the table.
* `user_id` — An integer column to identify each unique user.
* `sell_id` — An integer column representing each transaction by a user.
```sql SQL theme={null}
CREATE TABLE IF NOT EXISTS "transact_data" (
"created_at" TIMESTAMP TIME KEY BUCKET(1, HOUR) NOT NULL,
"user_id" BIGINT NOT NULL DEFAULT 0,
"sell_id" BIGINT NOT NULL,
"purchase_amount" DOUBLE NOT NULL DEFAULT 0,
"buyer_name" VARCHAR,
CLUSTERING KEY "ck" ("sell_id", "user_id")
);
CREATE INDEX "purchase_idx" ON "transact_data" ("purchase_amount");
CREATE INDEX "buyer_idx" ON "transact_data" ("buyer_name")
USING NGRAM(4);
```
This example table makes use of these Ocient System configurations.
| **Column Name** | **Configuration Description** |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `created_at` | This column is the table , which means that the database indexes for filter optimization. The example configures the TimeKey to partition segments by every hour, `(1, HOUR)`, which is the approximate time granularity you expect to use in your query filters. |
| `user_id`, `sell_id` | The example table identifies these two columns as the table Clustering Key. The database pairs these two columns for quick reference, such as filtering one column for row values of the other. |
| `purchase_amount` | The `CREATE INDEX` SQL statement adds a secondary index to this column. As a `BIGINT` data type, the `purchase_amount` column defaults to the `INVERTED` index. |
| `buyer_name` | This `CREATE INDEX` SQL statement adds a secondary index to this column. As a `VARCHAR` column, the `buyer_name` column normally defaults to a `HASH` index, but this example specifies it should be an `NGRAM` index of width `4` instead. |
For details about using the TimeKey and Clustering Key functionality, see [TimeKeys and Clustering Keys](/timekeys-and-clustering-keys).
For details about other index types, see [Secondary Indexes](/secondary-indexes).
## Create a Table for Geospatial Data
This example assumes you plan to ingest geospatial data linked to time series data using . The most important columns that you plan to reference frequently in queries include:
* `route_time` — A granular timestamp column that represents the primary time reference in the table.
* `start_point`, `end_point` — The geospatial point values for the start and destination locations.
* `trip_id` — An integer column to identify each unique trip.
* `vehicle_id` — An integer column that represents each vehicle.
```sql SQL theme={null}
CREATE TABLE "trip_details" (
"route_time" TIMESTAMP TIME KEY BUCKET(14, DAY) NOT NULL,
"start_point" POINT NULL,
"end_point" POINT NOT NULL DEFAULT 'POINT(0 0)',
"route_path" LINESTRING NOT NULL
DEFAULT 'LINESTRING(0 0, 1 1)',
"route_area" POLYGON NOT NULL
DEFAULT 'POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))',
"trip_id" BIGINT NOT NULL,
"vehicle_id" BIGINT NOT NULL,
CLUSTERING KEY "ck" ("trip_id", "vehicle_id")
);
CREATE INDEX "start_idx" on "trip_details" ("start_point")
USING SPATIAL;
CREATE INDEX "end_idx" on "trip_details" ("end_point")
USING SPATIAL;
```
This example table makes use of these Ocient System configurations.
| **Column Name** | **Configuration Description** |
| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `route_time` | This column is the table TimeKey, which means that the database indexes for filter optimization. The example configures the TimeKey to partition segments by every two weeks `(14, DAY)`, which is the approximate time granularity that you expect to use in your query filters. |
| `trip_id`, `vehicle_id` | The example table identifies these two columns as the table Clustering Key. The database pairs these two columns for quick reference, such as filtering one column for row values of the other. |
| `end_point`, `route_path`, `route_area` | These columns have `POINT`, `LINESTRING`, and `POLYGON` data types, respectively. Each of these geospatial columns includes default values in its respective format. |
| `start_point`, `end_point` | The `CREATE INDEX` SQL statements for both of these columns assign `SPATIAL` indexes for quicker reference. This index is the default type for any column with a geospatial data type. |
For details about OcientGeo functionality, see [Geospatial Functions](/geospatial-functions).
## Create a Table With Compression Options
This example table includes multiple compression options to ensure minimal storage for specific columns and extra performance.
Most data types, except arrays, have `COMPRESSION DYNAMIC` applied by default.
```sql SQL theme={null}
CREATE TABLE "call_records" (
"utc_timestamp" TIMESTAMP TIME KEY BUCKET(1, DAY) NOT NULL,
"sectorid" VARCHAR
COMPRESSION ZSTD,
"address" VARCHAR
COMPRESSION NONE,
"call_type" VARCHAR
COMPRESSION ZSTD
COMPRESSION GDC(4),
"access_information" VARCHAR(500)
COMPRESSION GDC(4),
"file_name" VARCHAR
COMPRESSION ZSTD compression_level = 3,
dictionary_size = 1048576,
CLUSTERING KEY "ck" ("call_type", "access_information")
);
```
This example table makes use of these Ocient System configurations.
| **Column name** | **Configuration Description** |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `address` | This column explicitly removes compression by specifying `COMPRESSION NONE` in the `CREATE TABLE` SQL statement. |
| `call_type`, `access_information` | These columns have `VARCHAR` data types configured with Global Dictionary Compression (GDC). This compression scheme maps the variable-length type rows to integers. Among other benefits, this compression allows both columns to support a Clustering Key for faster querying. The `call_type` column stacks multiple compression schemes by including both GDC and ZSTD compression to provide additional storage reduction. |
| `file_name` | This column uses ZSTD compression with extra options. The `compression_level` is set for `3`, meaning the column data is slightly more compressed than the default `0`. The dictionary\_size is set for the maximum value, `1048576`, which means greater compression but higher memory demand. |
For details about Ocient compression schemes, see [Table Compression Options](/table-compression-options).
## Create a Table for Various Container Types
This example table includes complex container data types, including a two-dimensional array, a tuple with variable-length values, and a tuple with various data types.
```sql SQL theme={null}
CREATE TABLE "container_data" (
"utc_timestamp" TIMESTAMP TIME KEY BUCKET(1, DAY) NOT NULL,
"user_id" BIGINT NOT NULL DEFAULT 0,
"sell_id" BIGINT NOT NULL DEFAULT 0,
"point_array_col" POINT[],
"array_col" VARCHAR[] COMPRESSION GDC(4),
"2D_array_col" INT[][],
"tuple_col1" TUPLE<<
VARCHAR(255),
VARCHAR(500)
>>,
"tuple_col2" TUPLE<<
INT,
INT[],
VARCHAR COMPRESSION GDC(1) COMPRESSION ZSTD,
VARCHAR
>>,
"matrix_col" MATRIX[5][10],
CLUSTERING INDEX "ck" ("user_id", "sell_id")
);
CREATE INDEX "point_idx" on "container_data" ("point_array_col")
USING SPATIAL;
CREATE INDEX "tuple_idx" on "container_data" ("tuple_col1"[1])
USING HASH;
CREATE INDEX "tuple_idx2" on "container_data" ("tuple_col2"[2])
USING INVERTED;
```
This example table makes use of these Ocient System configurations.
| **Column name** | **Configuration Description** |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `point_array_col` | This column is an array of `POINT` values that is indexed using a `SPATIAL` index type as specified by the `CREATE INDEX` SQL statement. |
| `tuple_col1` | This tuple column contains two variable-length values. Each object in the tuple can support its own compression scheme and index. The `CREATE INDEX` SQL statement assigns a `HASH` index to the first value (`VARCHAR(255)`). |
| `tuple_col2` | This tuple column contains various data types. Each object in the tuple can support its own compression scheme and index. The two `VARCHAR` objects in the tuple column each have their own unique compression scheme. The `CREATE INDEX` SQL statement assigns an `INVERTED` index to the second tuple object, the integer array `INT[]`. |
For details about Ocient container types, see [Array, Tuple, and Matrix Overview](/array-tuple-and-matrix-overview).
## Create a Table With a Retention Policy
This example creates a retention policy that keeps rows only if they are less than one day old, as specified by the last line, `RETENTION POLICY AGE 1 DAY`. The retention policy depends on the `created_at` column because it is the TimeKey column. The TimeKey bucket value `(1, HOUR)` determines how frequently the system checks for any rows to remove.
```sql SQL theme={null} theme={null}
CREATE TABLE IF NOT EXISTS "transact_data" (
"created_at" TIMESTAMP TIME KEY BUCKET(1, HOUR) NOT NULL,
"user_id" INT NOT NULL DEFAULT 0,
"sell_id" BIGINT NOT NULL,
"purchase_amount" BIGINT NOT NULL DEFAULT 0,
"buyer_name" VARCHAR(1048576),
CLUSTERING KEY "primary_index" ("sell_id", "user_id")
) RETENTION POLICY AGE 1 DAY;
```
For details about configuring table retention, see [Table Retention Policies](/table-retention-policies).
## Related Links
[Data Types](/data-types)
[Data Definition Language (DDL) Statement Reference](/data-definition-language-ddl-statement-reference)
[Table Compression Options](/table-compression-options)
[Secondary Indexes](/secondary-indexes)
# Data Control Language (DCL) Statement Reference
Source: https://docs.ocient.com/data-control-language-dcl-statement-reference
Reference for Ocient Data Control Language (DCL) statements, including GRANT and REVOKE for managing privileges, roles, and access in the database.
In order to assign privileges to users, administrators can use Data Control Language (DCL) statements. You can write and execute DCL statements like any other SQL statements against the System and databases. DCL statements allow you to quickly and easily grant or revoke privileges from users. DCL statements work off two main concepts: Grants and Revokes. Statements that begin with `GRANT` give the associated privileges to a user or group. Statements that begin with `REVOKE` remove those privileges from a user or group.
A full list of privileges can be found in the [Ocient Privileges Reference](#ocient-privileges-reference).
Supported DCL SQL statements are:
* GRANT PRIVILEGE
* REVOKE PRIVILEGE
* GRANT ROLE
* REVOKE ROLE
When you create an object in the system, database, or schema, the Ocient System automatically grants you all valid privileges for that type of object. For example, if you create a table in a database, the system grants you all privileges that apply to the created table. For details, see [Table Privileges](#table-privileges).
For non-SSO users, the system assigns creator privileges to the user. For SSO users, the system follows specific criteria to assign the privileges. To understand the criteria the system uses, see [User Access Control and Workload Management with SSO](/authentication-methods#user-access-control-and-workload-management-with-sso).
## Grant Privileges
The `GRANT` statement grants privileges to a user or group. The privileges that you can grant in the `GRANT` statement map to the tables and differ per object. The `WITH GRANT OPTION` keywords specify that the grantee can also grant privileges on that object.
To grant privileges, you must have:
* `VIEW` privileges for the specified user or group being granted new privileges.
* `SYSAUTH` privileges over the system or database object that the specified user or group is being granted privileges on.
**Syntax**
```sql SQL theme={null}
GRANT {
{ CREATE { }
| VIEW { SCHEMA | TABLE | VIEW | QUERIES | REDACTED QUERIES }
| ALTER { SCHEMA | TABLE | VIEW }
| DROP { SCHEMA | TABLE | VIEW }
| CANCEL QUERIES
| SELECT | DELETE | SYSAUTH | USE | ALL }
ON SYSTEM
| { CREATE { }
| VIEW { SCHEMA | TABLE | VIEW | QUERIES | REDACTED QUERIES }
| ALTER { SCHEMA | TABLE | VIEW }
| DROP { SCHEMA | TABLE | VIEW }
| CANCEL QUERIES
| SELECT | ALTER | DROP | DELETE | SYSAUTH | USE | ALL }
ON DATABASE object_name
| { CREATE { | MLMODEL } | VIEW { }
| ALTER { }
| DROP { }
| VIEW | SELECT | ALTER | DROP | DELETE | SYSAUTH | INSERT | ALL }
ON SCHEMA object_name
| { VIEW | ALTER | DROP | SYSAUTH | ALL }
ON { GROUP | USER } object_name
| { SELECT | DROP | SYSAUTH | ALL }
ON MLMODEL object_name
| { VIEW | EXECUTE | ALTER | DROP | SYSAUTH | ALL }
ON PIPELINE object_name
| { VIEW | DROP | SYSAUTH | ALL }
ON PIPELINE FUNCTION object_name
| { VIEW | SELECT | ALTER | DROP | SYSAUTH | ALL }
ON VIEW object_name
| { VIEW | SELECT | ALTER | LOAD | DROP | DELETE | SYSAUTH | INSERT | ALL }
ON TABLE object_name
| { VIEW | SELECT | ALL }
ON TABLE sys.system_catalog_table
}
TO { { GROUP | USER } object_name | PUBLIC } [ WITH GRANT OPTION ]
::=
DATABASE | TABLE | VIEW | USER | GROUP
::=
SCHEMA | TABLE | VIEW | MLMODEL | PIPELINE | PIPELINE FUNCTION | USER | GROUP
::=
TABLE | VIEW
```
When you grant any privilege to a user on a system or database object other than the `VIEW` privilege, the database implicitly grants the `VIEW` privilege on the specified object to the user, as well as associated object types (e.g., `DROP VIEW ON DATABASE` also grants `VIEW VIEW ON DATABASE` and `VIEW ON DATABASE`).
**Examples**
**Grant Privilege on a Table**
This example grants privileges for the `SELECT` SQL statement on a table to a trusted group.
```sql SQL theme={null}
GRANT SELECT ON TABLE company_data TO GROUP trusted_employees;
```
**Grant Privilege on a Database**
This example grants the `SELECT` privilege for all tables and views on the `database_name` database to a trusted group.
```sql SQL theme={null}
GRANT SELECT ON DATABASE database_name TO GROUP trusted_employees;
```
**Grant Privilege on the System**
This example grants the `SELECT` privilege for all tables and views on all databases in the system to a trusted group.
```sql SQL theme={null}
GRANT SELECT ON SYSTEM TO GROUP trusted_employees;
```
For examples of granting privileges for individual users, see [Grant Role Membership](#grant-role-membership).
## Revoke Privileges
The `REVOKE` statement revokes privileges from a user or group.
To revoke privileges, you must have:
* `VIEW` privileges for the specified user or group having their privileges revoked.
* `SYSAUTH` privileges over the system or database object from which the specified user or group has their privileges revoked.
```sql SQL theme={null}
REVOKE [ GRANT OPTION FOR ] {
{ CREATE { }
| VIEW { SCHEMA | TABLE | VIEW | QUERIES | REDACTED QUERIES }
| ALTER { SCHEMA | TABLE | VIEW }
| DROP { SCHEMA | TABLE | VIEW }
| CANCEL QUERIES
| SELECT | DELETE | SYSAUTH | USE | ALL }
ON SYSTEM
| { CREATE { }
| VIEW { SCHEMA | TABLE | VIEW | QUERIES | REDACTED QUERIES }
| ALTER { SCHEMA | TABLE | VIEW }
| DROP { SCHEMA | TABLE | VIEW }
| CANCEL QUERIES
| SELECT | ALTER | DROP | DELETE | SYSAUTH | USE | ALL }
ON DATABASE object_name
| { CREATE { | MLMODEL } | VIEW { }
| ALTER { }
| DROP { }
| VIEW | SELECT | ALTER | DROP | DELETE | SYSAUTH | INSERT | ALL }
ON SCHEMA object_name
| { VIEW | ALTER | DROP | SYSAUTH | ALL }
ON { GROUP | USER } object_name
| { SELECT | DROP | SYSAUTH | ALL }
ON MLMODEL object_name
| { VIEW | EXECUTE | ALTER | DROP | SYSAUTH | ALL }
ON PIPELINE object_name
| { VIEW | DROP | SYSAUTH | ALL }
ON PIPELINE FUNCTION object_name
| { VIEW | SELECT | ALTER | DROP | SYSAUTH | ALL }
ON VIEW object_name
| { VIEW | SELECT | ALTER | LOAD | DROP | DELETE
| SYSAUTH | INSERT | ALL }
ON TABLE object_name
| { VIEW | SELECT | ALL }
ON TABLE sys.system_catalog_table
}
FROM { [ USER | GROUP ] object_name | PUBLIC }
::=
DATABASE | TABLE | VIEW | USER | GROUP
::=
SCHEMA | TABLE | VIEW | MLMODEL | PIPELINE | PIPELINE FUNCTION | USER | GROUP
::=
TABLE | VIEW
```
When you revoke the `VIEW` privilege on a system or database object, the database implicitly revokes all privileges on the specified object from the user.
If you revoke the `VIEW` privilege on an associated object type, the system revokes the privileges for that object type. For example, grant the `DROP TABLE` privilege to the user by using the `GRANT DROP TABLE ON DATABASE` SQL statement. Due to implicit granting by the system, this action causes the user to have `DROP TABLE`, `VIEW TABLE`, and `VIEW` privileges. If you revoke the `VIEW TABLE` privilege using the `REVOKE VIEW TABLE ON DATABASE` SQL statement, then the system revokes the privileges for the associated type. In this case, the user only retains the `VIEW` privilege on the database.
**Example**
This example revokes the SELECT privilege on a table from an untrusted group.
```sql SQL theme={null}
REVOKE SELECT ON TABLE company_data FROM GROUP untrusted;
```
For examples of revoking privileges for individual users, see [Revoking Role Membership](#revoke-role-membership).
### Ocient Privileges Reference
These tables describe the privilege options on each object in Ocient and the allowed privileges.
As of version 23.0, Ocient DCL has replaced the `TRUNCATE` privilege with the `DELETE` privilege.
Any `TRUNCATE` privileges, whether manually granted or assigned as part of a user role, should automatically convert to `DELETE` privileges following a system upgrade to version 23.0 or later.
#### Ocient System Privileges
| **Privilege** | **Description** |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| CREATE \[DATABASE, USER, GROUP] | The privilege to create the specified object type. On creation, the creating user inherits all privileges on the object. In the case of the DATABASE object, this is enforced by granting the creating user the newly created database administrator role as described in the Roles section. |
| CREATE \[SCHEMA, TABLE, VIEW] | The privilege to create the specified object type on any database where the user can connect. On creation, the creating user inherits all privileges on the object. In order to apply the privilege, the user has to be connected to a user-defined database. |
| DROP \[SCHEMA, TABLE, VIEW] | The privilege to drop the specified object type on any database where the user can connect. In order to apply the privilege, the user has to be connected to a user-defined database. |
| ALTER \[SCHEMA, TABLE, VIEW] | The privilege to modify the specified object type on any database where the user can connect. In order to apply the privilege, the user has to be connected to a user-defined database. |
| VIEW \[SCHEMA, TABLE, VIEW] | The privilege to see and read information of the specified object type within the system. |
| VIEW QUERIES | The privilege to see the full SQL statement and metadata for all queries within the system. |
| VIEW REDACTED QUERIES | The privilege to see the metadata for all queries with a fully redacted SQL statement within the system. |
| CANCEL QUERIES | The privilege to cancel or kill running queries within the system. |
| SELECT | The privilege to read data on any table or view where the user has the VIEW privilege. |
| SYSAUTH | The privilege to grant and revoke all privileges on the system. |
| USE | The ability to connect to the system. |
| DELETE | The privilege to delete data from and truncate tables within the system. |
#### Database Privileges
| **Privilege** | **Description** |
| -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| CREATE \[SCHEMA, TABLE, VIEW, MLMODEL, PIPELINE, PIPELINE FUNCTION, USER, GROUP] | The privilege to create the specified object type. The user who creates the object inherits all privileges on the object. |
| DROP \[SCHEMA, TABLE, VIEW] | The privilege to drop the specified object type on this database. |
| ALTER \[SCHEMA, TABLE, VIEW] | The privilege to modify the specified object type on this database. |
| VIEW \[SCHEMA, TABLE, VIEW] | The privilege to see and read information of the specified object type within the database. |
| VIEW QUERIES | The privilege to see the full SQL statement and metadata for all queries in this database. |
| VIEW REDACTED QUERIES | The privilege to see the metadata for all queries with a fully redacted SQL statement in this database. |
| CANCEL QUERIES | The privilege to cancel or kill running queries in this database. |
| SELECT | The privilege to read data on any table or view, where the user has the VIEW privilege, in the database. |
| USE | Ability to connect to the database. Users created in this database are implicitly granted this privilege. |
| ALTER | The ability to issue ALTER DATABASE statements on this database. |
| DROP | The ability to drop this database. |
| SYSAUTH | The ability to grant and revoke all privileges on the database. |
| DELETE | The privilege to delete data from and truncate tables in the database. |
#### Schema Privileges
| **Privilege** | **Description** |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| CREATE \[ TABLE \| VIEW \| MLMODEL ] | The privilege to create the specified object type. |
| DROP \[ TABLE \| VIEW ] | The privilege to drop the specified object type within the schema. |
| ALTER \[ TABLE \| VIEW ] | The privilege to modify the specified object type within the schema. |
| VIEW \[ TABLE \| VIEW ] | The privilege to see and read information of the specified object type within the schema. |
| SELECT | The privilege to read data on any table or view, where the user has the VIEW privilege, within the schema. |
| ALTER | The ability to modify the schema. |
| DROP | The privilege to drop the schema and its contents. |
| VIEW | The ability to see and read information about the schema. |
| SYSAUTH | The ability to grant and revoke all privileges on the schema. |
| INSERT | The privilege to insert data into tables in the schema. |
| DELETE | The privilege to delete data from and truncate tables in the schema. |
Granting privileges using DCL statements promotes an implicit schema to an explicit schema. For details, see [Schemas](/schemas).
#### View Privileges
| **Privilege** | **Description** |
| ------------- | ---------------------------------------------------------- |
| VIEW | Ability to see and read schema information about the view. |
| SELECT | Ability to read data from the view. |
| ALTER | Ability to modify the view. |
| DROP | Ability to drop the view. |
| SYSAUTH | Ability to grant privileges on the view. |
#### Table Privileges
| **Privilege** | **Description** |
| ------------- | ----------------------------------------------------------- |
| VIEW | Ability to see and read schema information about the table. |
| SELECT | Ability to read data from the table. |
| ALTER | Ability to modify the table. |
| LOAD | Ability to load data into the table. |
| DROP | Ability to drop the table. |
| DELETE | Ability to delete and truncate the table. |
| SYSAUTH | Ability to grant and revoke privileges on the table. |
| INSERT | Ability to insert data into the table. |
#### Machine Learning Model Privileges
| **Privilege** | **Description** |
| ------------- | --------------------------------------------------------- |
| ALTER | Ability to rename the model. |
| SELECT | Ability to read data and descriptive data from the model. |
| DROP | Ability to drop the model. |
| SYSAUTH | Ability to grant and revoke privileges on the model. |
#### Data Pipeline Privileges
| **Privilege** | **Description** |
| ------------- | ------------------------------------------------- |
| VIEW | See and read information schema about a pipeline. |
| EXECUTE | Start and stop the execution of a pipeline. |
| ALTER | Rename and replace a pipeline. |
| DROP | Drop a pipeline. |
| SYSAUTH | Grant and revoke privileges on a pipeline. |
#### Data Pipeline Function Privileges
| **Privilege** | **Description** |
| ------------- | -------------------------------------------------------------------------------------------- |
| VIEW | See and read information schema about a data pipeline function in the system catalog tables. |
| DROP | Drop a data pipeline function. |
| SYSAUTH | Grant and revoke privileges on a data pipeline function. |
#### User Privileges
| **Privilege** | **Description** |
| ------------- | ---------------------------------------------------------- |
| VIEW | Ability to read information about the user. |
| ALTER | Ability to modify the user. |
| DROP | Ability to drop the user. |
| SYSAUTH | Ability to grant rights and revoke privileges on the user. |
#### Group Privileges
| **Privilege** | **Description** |
| ------------- | -------------------------------------------- |
| VIEW | Ability to read information about the group. |
| ALTER | Ability to alter the group. |
| DROP | Ability to drop the group. |
| SYSAUTH | Ability to grant privileges on the group. |
#### System Catalog and Object or View Visibility
The `sys.privileges` table in the system catalog exposes the privileges in the system. This table displays this information:
* Timestamp of the grant
* Grantor
* Grantee
* Privilege granted
* Object type
* Object id
* Grantable
You can grant and revoke System Catalog `VIEW` and `SELECT` privileges just like ordinary tables. By default, everyone has `VIEW` and `SELECT` privileges on all system catalog tables.
You can see the objects within the system catalog tables only if you have sufficient privileges on those objects. These objects require a `VIEW` or `SELECT` privilege or membership in a group or role to provide visibility. When you execute queries against a system catalog table, you do not see or know the existence of objects to which you do not have access.
Views offer a similar functionality because the database does not check privileges to the underlying tables and views after you create a view. You can create a table with sensitive information and restrict visibility by creating a view on top of the table with only certain rows or columns. Someone else with the `SELECT` privilege to the view can query the view, even without any privileges to the underlying table.
## Roles
Similar to groups, users can inherit privileges by being granted one of the predefined roles in Ocient. The names of and privileges assigned to roles in Ocient are predefined by the system. Roles can be applicable to the Ocient System or one of the user-defined databases. The roles in Ocient are as follows:
**System Roles**
* **Security Administrator** — Can read, create, and modify all users and groups.
* **System Administrator** — Can read, create, and modify system objects such as tables, clusters, databases, etc. Can see and delete any queries system-wide.
* **System Analyst** — Read-only access to the entire system. Can see all queries in the system.
**Database Roles**
* **Database Administrator** — Can read, create, and modify database objects such as tables, clusters, databases, etc. This role can also create users for the database. Can see and delete all queries in the database.
* **Database Analyst** — Read-only rights to database objects and data within the database. Can see all queries in the database.
* **Public** — Every user who has access to the database has the Public role by default. You can grant other privileges to this role. This role allows the creation of a schema using the `CREATE SCHEMA` SQL statement and allows the viewing of other roles by default.
For specifics on each Ocient role, see [Default Role Privileges](#default-role-privileges).
### Grant Role Membership
Grants a role to a user or group.
**Syntax**
```sql SQL theme={null}
GRANT ROLE role_name TO { USER | GROUP } user_or_group_name
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------------- | ----------------- | ----------------------------------------------------------------------------------------------------- |
| `role_name` | string | The name of a role to be granted to the specified user or group. Enclose this string in quotes. |
| `user_or_group_name` | string | The name of a user or group to be granted the specified role. |
**Example**
This example grants `user1` the system administrator role.
```sql SQL theme={null}
GRANT ROLE "System Administrator" TO USER user1;
```
### Revoke Role Membership
Revokes a role from a user or group.
**Syntax**
```sql SQL theme={null}
REVOKE ROLE role_name FROM { USER | GROUP } user_or_group_name
```
| **Parameter** | **Data** **Type** | **Description** |
| -------------------- | ----------------- | ------------------------------------------------------------------------------------------------------ |
| `role_name` | string | The name of a role to be revoked for the specified user or group. Enclose this string in quotes. |
| `user_or_group_name` | string | The name of a user or group to have the specified role revoked. |
**Example**
This example revokes the system administrator role from `user1`.
```sql SQL theme={null}
REVOKE ROLE "System Administrator" FROM USER user1;
```
### Default Role Privileges
#### Security Administrator Privileges
| **Target** | **Privileges** |
| ---------------------- | -------------------------------- |
| System | SYSAUTH, CREATE \[ USER ] |
| Schema | SYSAUTH |
| Database | SYSAUTH, CREATE \[ USER, GROUP ] |
| View | SYSAUTH |
| Table | SYSAUTH |
| Machine Learning Model | SYSAUTH |
| Data Pipeline | SYSAUTH |
| Data Pipeline Function | SYSAUTH |
| User | VIEW, ALTER, DROP, SYSAUTH |
| Group | VIEW, ALTER, DROP, SYSAUTH |
#### System Administrator Privileges
| **Target** | **Privileges** |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| System | USE, CREATE \[ DATABASE, USER ], VIEW QUERIES, CANCEL QUERIES |
| Schema | VIEW, ALTER, DROP |
| Database | - USE - ALTER - DROP - CREATE \[ SCHEMA, TABLE, VIEW, MLMODEL, USER, GROUP, PIPELINE, PIPELINE FUNCTION ] |
| View | VIEW, SELECT, ALTER, DROP |
| Table | VIEW, SELECT, ALTER, LOAD, DROP, DELETE, INSERT |
| Machine Learning Model | SELECT, DROP |
| Data Pipeline | VIEW, EXECUTE, ALTER, DROP |
| Data Pipeline Function | VIEW, DROP |
| User | VIEW, ALTER, DROP |
| Group | VIEW, ALTER, DROP |
#### System Analyst Privileges
| **Target** | **Privileges** |
| ---------------------- | ----------------- |
| System | USE, VIEW QUERIES |
| Schema | VIEW |
| Database | USE |
| View | VIEW, SELECT |
| Table | VIEW, SELECT |
| Machine Learning Model | SELECT |
| Data Pipeline | VIEW |
| Data Pipeline Function | VIEW |
| User | VIEW |
| Group | VIEW |
#### Database Administrator Privileges
| **Target** | **Privileges** |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Schema | VIEW, ALTER, DROP, SYSAUTH |
| Database | - USE - ALTER - DROP - CREATE \[ SCHEMA, TABLE, VIEW, MLMODEL, USER, GROUP, PIPELINE, PIPELINE FUNCTION ] - VIEW QUERIES, CANCEL QUERIES - SYSAUTH |
| View | VIEW, SELECT, ALTER, DROP, SYSAUTH |
| Table | VIEW, SELECT, ALTER, LOAD, DROP, DELETE, INSERT, SYSAUTH |
| Machine Learning Model | SELECT, DROP, SYSAUTH |
| Data Pipeline | VIEW, EXECUTE, ALTER, DROP, SYSAUTH |
| Data Pipeline Function | VIEW, DROP, SYSAUTH |
| User | VIEW, ALTER, DROP, SYSAUTH |
| Group | VIEW, ALTER, DROP, SYSAUTH |
#### Database Analyst Privileges
| **Target** | **Privileges** |
| ---------------------- | ----------------- |
| Schema | VIEW |
| Database | USE, VIEW QUERIES |
| View | VIEW, SELECT |
| Table | VIEW, SELECT |
| Machine Learning Model | SELECT |
| Data Pipeline | VIEW |
| Data Pipeline Function | VIEW |
| User | VIEW |
| Group | VIEW |
#### Public Privileges
| **Target** | **Privileges** |
| ---------- | -------------- |
| Database | CREATE SCHEMA |
### Query Visibility
The visibility of queries depends on which database you are logged into and your assigned privileges. Users with no additional VIEW QUERIES or VIEW REDACTED QUERIES privileges can view only queries that they submit themselves.
The VIEW QUERIES privilege allows access to queries for all users in these system catalog tables:
* `sys.queries `
* `sys.completed_queries`
* `sys.plans `
* `sys.active_query_scheduler_info `
* `sys.all_operator_instances `
* `sys.completed_operator_instances `
* `sys.op_inst_debug_info`
The VIEW REDACTED QUERIES privilege allows access to queries for all users in these system catalog tables, but with a redacted SQL statement for queries from other users:
* `sys.queries `
* `sys.completed_queries`
For the initial grant of query privileges, the grantor must have the `Database Administrator` or `System Administrator` role. Use the `WITH GRANT OPTION` keywords to allow a user to further grant this privilege to other users and groups.
#### Login Impacts on Query Visibility
Along with having role privileges, users also must be logged into the appropriate database to view queries:
* If the user logs in to the `SYSTEM` database, the user can see all queries from all databases.
* If the user logs in to a database other than `SYSTEM`, the user can see queries in only that database.
## Related Links
[Database Administration](/database-administration)
[Manage Users, Groups, and Roles](/manage-users-groups-and-roles)
[Object-Type Level Privileges Management](/object-type-level-privileges-management)
# Data Definition Language (DDL) Statement Reference
Source: https://docs.ocient.com/data-definition-language-ddl-statement-reference
Reference for Ocient Data Definition Language (DDL) statements, including CREATE, ALTER, and DROP for databases, tables, views, indexes, and other objects.
DDL statements allow users to run commands and administrative operations on the System. You can execute DDL statements over a database connection to manage nodes, storage spaces, tables and views, system configuration, users and groups, underlying storage segments, and more.
**Quoting Identifiers**
In all DDL statements, identifiers not in double quotes must begin with a letter and can only contain letters, numbers, and underscores. Identifiers are the names of databases, tables, nodes, and so on. For details, see [Identifiers](/identifiers). The Ocient System internally converts identifiers to lower-case. Identifiers in double quotes can contain any characters besides newline and carriage return, can begin with any character, and are not case-adjusted. To use an identifier with the same name as any keyword, it must be in double quotes.
String literals must be enclosed in single quotes. A single quote within a string can be escaped as "\*. \*A string literal can be preceded by e to enable additional escape sequences (for example: `e'\n'`).
DDL statements are supported for these categories:
## [Cluster and Node Management](/cluster-and-node-management)
* **CLUSTER**
* CREATE CLUSTER
* DROP CLUSTER
* ALTER CLUSTER
* ALTER CLUSTER ADD PARTICIPANTS
* ALTER CLUSTER DROP PARTICIPANTS
* ALTER CLUSTER ADD STORAGESPACE
* ALTER CLUSTER REMOVE STORAGESPACE
* ALTER CLUSTER ALTER CONFIG SET
* ALTER CLUSTER ALTER LOG LEVEL SET
* ALTER CLUSTER RENAME
* **STORAGESPACE**
* CREATE STORAGESPACE
* DROP STORAGESPACE
* ALTER STORAGESPACE RENAME
* **NODE**
* DROP NODE
* ALTER NODE
* ALTER NODE ADD ROLE
* ALTER NODE REMOVE ROLE
* ALTER NODE ALTER CONFIG SET
* ALTER NODE RENAME
* ALTER NODE ALTER LOG LEVEL SET
* ALTER NODE ALTER METRIC LEVEL
* ALTER NODE SET ADDRESS
* **CONNECTIVITY POOL**
* CREATE CONNECTIVITY\_POOL
* DROP CONNECTIVITY\_POOL
* ALTER CONNECTIVITY\_POOL
* ALTER CONNECTIVITY\_POOL SET
* ALTER CONNECTIVITY\_POOL RENAME TO
* ALTER CONNECTIVITY\_POOL ADD PARTICIPANTS
* ALTER CONNECTIVITY\_POOL ALTER PARTICIPANT
* ALTER CONNECTIVITY\_POOL DROP PARTICIPANTS
* ALTER CONNECTIVITY\_POOL SET SSO INTEGRATION
* ALTER CONNECTIVITY\_POOL REMOVE SSO INTEGRATION
* SSO INTEGRATION
* CREATE SSO INTEGRATION
* DROP SSO INTEGRATION
* ALTER SSO INTEGRATION
* **SYSTEM**
* ALTER SYSTEM ALTER CONFIG SET
* ALTER SYSTEM RENAME TO
* ALTER SYSTEM ALTER METRIC LEVEL
* ALTER SYSTEM ALTER SECURITY
* ALTER SYSTEM SET DEFAULT STORAGESPACE
## [Schemas](/schemas)
* CREATE SCHEMA
* DROP SCHEMA
* ALTER SCHEMA RENAME
## [Databases](/databases)
* CREATE DATABASE
* DROP DATABASE
* ALTER DATABASE
* ALTER DATABASE RENAME
* ALTER DATABASE SET SSO INTEGRATION
* ALTER DATABASE ALTER SSO INTEGRATION
* ALTER DATABASE REMOVE SSO INTEGRATION
* ALTER DATABASE ALTER SECURITY
## [Tables](/tables)
* CREATE TABLE
* CREATE TABLE AS SELECT (CTAS)
* CREATE TABLE AS SELECT USING LOADERS
* DROP TABLE
* ALTER TABLE
* ALTER TABLE RENAME
* ALTER TABLE RENAME COLUMN
* ALTER TABLE ADD COLUMN
* ALTER TABLE ALTER COLUMN COMPRESSION
* ALTER TABLE ALTER REDUNDANCY
* ALTER TABLE DROP COLUMN
* ALTER TABLE STREAMLOADER\_PROPERTIES
* ALTER TABLE DISABLE INDEX
* ALTER TABLE ENABLE INDEX
* ALTER TABLE ENABLE RETENTION POLICY AGE
* ALTER TABLE DISABLE RETENTION POLICY
* DELETE FROM TABLE
* EXPORT TABLE
* INSERT INTO TABLE
* INSERT INTO TABLE USING LOADERS
* TRUNCATE TABLE
## [Views](/views)
* CREATE VIEW
* DROP VIEW
* ALTER VIEW RENAME
* ALTER VIEW AS
* EXPORT VIEW
## [Indexes](/indexes)
* CREATE INDEX
* DROP INDEX
## [Data Pipelines](/data-pipelines)
* PIPELINE
* CREATE PIPELINE
* DROP PIPELINE
* PREVIEW PIPELINE
* START PIPELINE
* STOP PIPELINE
* ALTER PIPELINE
* ALTER PIPELINE RENAME
* EXPORT PIPELINE
* CREATE PIPELINE FUNCTION
* DROP PIPELINE FUNCTION
## [Distributed Tasks](/distributed-tasks)
* **TASK**
* CREATE TASK
* CANCEL TASK
## [Machine Learning Models](/machine-learning-models)
* CREATE MLMODEL
* ALTER MLMODEL
* DROP MLMODEL
* EXPORT MLMODEL
* REFRESH MLMODEL
## [Users, Groups, and Service Classes](/users-groups-and-service-classes)
* **USER**
* CREATE USER
* DROP USER
* ALTER USER
* ALTER USER SET
* **GROUP**
* CREATE GROUP
* DROP GROUP
* ALTER GROUP
* ALTER GROUP USER
* ALTER GROUP RENAME
* ALTER GROUP SET SERVICE CLASS
* ALTER GROUP ALTER SECURITY
* **SERVICE CLASS**
* CREATE SERVICE CLASS
* DROP SERVICE CLASS
* ALTER SERVICE CLASS
* ALTER SERVICE CLASS RENAME
* ALTER SERVICE CLASS SET
* ALTER SERVICE CLASS RESET
* ALTER QUERY
## [Data Integrity and Storage](/data-integrity-and-storage)
* DRAIN PAGES
* ALTER SEGMENT QUARANTINE
## [Query Analysis](/query-analysis)
* EXPLAIN
* EXPLAIN PIPELINE
## [Query Management](/query-management)
* CANCEL
* KILL
## [Statistics Cache Management](/statistics-cache-management)
# Data Extract Tool
Source: https://docs.ocient.com/data-extract-tool
Use the Ocient Data Extract tool with the JDBC driver to export rows from tables and queries into files for backup, migration, or downstream processing.
The data extract tool is a part of the JDBC driver to unload data. You can execute the tool directly from the JDBC CLI. The tool extracts a result set to delimited or files in the target location. To invoke the JDBC CLI, see the [JDBC Manual](/jdbc-manual).
To use the data extract tool, you must have JDBC version 2.63 or higher.
## Supported Data Extract Formats
The data extract tool supports unloading result sets into files in specific formats. Supported extract formats are:
* CSV — Outputs result sets as text files with fields separated by a chosen delimiter.
* Parquet — Outputs result sets as Parquet files.
## General Command Structure
Here is the general structure of an extract command.
```sql SQL theme={null}
EXTRACT TO [OPTIONS([param=value [,...]])] AS
```
The command is case-insensitive. Each extract command must start with `EXTRACT TO`. The location type `location_type` must be either `LOCAL` for the local machine or `S3` for S3. You can enclose additional options within a pair of parentheses following the keyword `OPTIONS`. The location type is required and there are required options for each location type. For the `LOCAL` location type, the options must define the file prefix `file_prefix`, and for `S3`, the options must define the file prefix `file_prefix`, bucket `bucket`, and endpoint `endpoint`. Next, the query follows the keyword `AS`.
This example is a simple general command structure.
```sql SQL theme={null}
EXTRACT TO LOCAL OPTIONS(
file_prefix="/home/user/out/data_",
file_extension=".csv"
)
AS SELECT c1 FROM sys.dummy10;
```
For supported options, see [Data Extract Options](#data-extract-options).
## Specify Options, Quoting, and Escaping Quotes
Here is the general format of options.
```sql SQL theme={null}
key1 = value1, key2 = value2, ... , keyN = valueN
```
You need to follow certain guidelines when you specify options. Keys (option names) can only consist of alphanumeric characters and are unquoted. Values can be either quoted (with the reserved character `"`) or unquoted. If values are unquoted, they can only contain alphanumeric characters. If the value has a non-alphanumeric character, you must quote it with the reserved character `"`. Note that the single quote character does not work.
```sql SQL theme={null}
OPTIONS(file_prefix = "/path/to/dir/result", header_mode = none, file_extension = ".csv")
```
To use the reserved quote character `"` as an argument, you must escape it with the backslash character `\`. To use `\` as an argument, you must escape it with another `\`. This code illustrates both of these scenarios.
```sql SQL theme={null}
OPTIONS(field_optionally_enclosed_by = "\"", escape = "\\")
```
## Data Extract Options
Use these optional options with the `EXTRACT TO` syntax and the `OPTIONS` keyword to configure the behavior of the extract.
### General Extract Options
This table describes optional options that apply to both the `LOCAL` and `S3` location types.
| **Option** | **Description** | **Default** |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `FILE_TYPE` | The type of the output file for extraction. Supports extraction to a delimited `.csv` file or Parquet `.parquet` file. | `DELIMITED` |
| `FILE_PREFIX` | Dictates the prefix used on the results. When extracting to `LOCAL`, this is the prefix used to determine the path of the results. This value can be a relative or full path. When extracting to S3, this value is the prefix for the key. In either case, the system adds additional file numbers and file extensions to generate the complete filename. | `results-` |
| `FILE_PREFIX_EXISTS` | Determines the behavior if the path specified by the `FILE_PREFIX` option already exists. Supported values are: `FAIL` and `OVERWRITE`. The `FAIL` value throws an error, whereas `OVERWRITE` deletes the contents of the path. | `'FAIL'` |
| `FILE_EXTENSION` | The file extension specified for each output file. | `.csv` |
| `MAX_ROWS_PER_FILE` | If you set this option to a non-zero value, the system splits the results into files with the specified maximum number of rows per file. | `NULL` |
| `COMPRESSION` | Compression type to use for a delimited extract. Supported compression types are: `NONE` — No compression `GZIP` — GZip compression `BZIP2` — bzip2 compression `XZ` — xz compression | `NONE` |
| `RECORD_DELIMITER` | Delimiter to use between records. This supports strings, so special characters can be input using escape characters. UTF-16: `\u[utf-16 value]` or Octal `\[octal value]`. | `\n` |
| `FIELD_DELIMITER` | Delimiter to use between fields within a record. This supports Java strings, so special characters can be input using escape characters. UTF-16: `\u[utf-16 value]` or Octal `\[octal value]`. | `,` |
| `HEADER_MODE` | Dictates how to manage headers in result files. Supported values are `NONE`, `ALL_FILES`, and `FIRST_FILE`.
`NONE` — The tool writes all output files without an additional header. `ALL_FILES` — The tool adds column names as a header in the first row of each output file. Each file has at most `MAX_ROWS_PER_FILE` + 1 total rows. `FIRST_FILE` — The tool adds column names as a header in the first row of the first output file. The tool does not add the header to subsequent files. Each file has at most `MAX_ROWS_PER_FILE` total rows, inclusive of the header in the first file. | `NONE` |
| `NULL_FORMAT` | Format string to use for writing NULL values to the output files. | `""` (empty string) |
| `ENCODING` | Encoding used when writing out data to files. | The default character set of the system, as determined by the [Oracle documentation](https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html). |
| `ESCAPE` | Character used for escaping quoted fields. Set this to the NULL character `\0` to indicate that the escape character is not specified. | `"` |
| `FIELD_OPTIONALLY_ENCLOSED_BY` | Sometimes, you need to surround fields in a character. For example, the field might have a literal comma. Generally, this character is also known as the quote character. Set this option to the NULL character `\0` to indicate that the quote character is not specified. | `"` |
| `BINARY_FORMAT` | The format with which to encode the BINARY data type. Supports `UTF-8`, `Hexadecimal`, and `Base64`. | `Hexadecimal` |
| `COMPRESSION_BLOCK_SIZE` | The number of bytes that comprise each block to be compressed; larger blocks result in better compression at the expense of more RAM usage when compressing. | `4194304` |
| `COMPRESSION_LEVEL` | An integer value \[-1, 9]. Use `-1` for the GZip default compression level, `0` for no compression, or a value \[1-9] where 1 indicates fastest compression and 9 indicates best compression. | `1` |
| `NUM_COMPRESSION_THREADS` | The number of threads to use for compression. | \$(number of cores \* 2) |
| `NUM_FETCH_QUERIES` | The number of parallel queries to execute in the database for data extraction. | `15` |
| `ESCAPE_UNQUOTED_VALUES` | Dictates whether to write escape sequences in unquoted values. Only applicable when `FIELD_DELIMITER` is set to `,`. | `false` |
| `INPUT_ESCAPED` | Dictates whether the input is already escaped. When this option is set to true, the tool does not add escape sequences, and data is written without changes to the output file. Only applicable when `FIELD_DELIMITER` is set to `,`. Ensure that data is properly escaped, otherwise the extract might produce invalid CSV data. | `false` |
| `PARTITION_MODE` | The strategy for partitioning the data. Supported values are: `NONE`, `KEY`, and `RANGE`.
When you set this option to `NONE`, the tool uses standard extraction. When you set this option to `KEY`, the tool creates subdirectories for each unique value specified by the `PARTITION_COLUMNS` option. When you set this option to `RANGE`, the tool splits the data into the number of queries specified by the `NUM_FETCH_QUERIES` option based on the range of values specified in the `PARTITION_COLUMNS` option. | `NONE` |
| `PARTITION_COLUMNS` | The comma-separated list of columns to use for partitioning data when you set the `PARTITION_MODE` option to `KEY` or `RANGE`. The `RANGE` value only allows a single column. See [File Naming Conventions](#file-naming-conventions) for the file path structure for multiple partitioning columns when using the `KEY` value. | `NULL` |
| `QUOTE_ALL_FIELDS` | Dictates whether all written fields are enclosed with quotes. When this option is set to true, the tool encloses all fields with the `FIELD_OPTIONALLY_ENCLOSED_BY` character. | `false` |
| `SUCCESS_MARKER` | Identifies a successful completion of the extract. If you set this option to `true`, the tool creates a file with the `_SUCCESS` suffix in the root output directory when the extract of the entire job completes successfully. | `true` |
| `TARGET_FILE_SIZE_MB` | Specifies the size in megabytes for the target output file. The data extract tool splits the output into files of approximately this size. The tool ignores this option if you set the `MAX_ROWS_PER_FILE` option. | `NULL` |
| `TRANSLATE_CHARACTERS_MODE` | Character Mode to use for translating characters. Supported values are `CHAR` and `HEX`. The tool performs character translation only if you specify `TRANSLATE_CHARACTERS_FROM` and `TRANSLATE_CHARACTERS_TO`. The tool replaces the Nth character in `TRANSLATE_CHARACTERS_FROM` with the Nth character in `TRANSLATE_CHARACTERS_TO` in the extracted records. When `TRANSLATE_CHARACTERS_MODE` is set to CHAR, `TRANSLATE_CHARACTERS_FROM`, and `TRANSLATE_CHARACTERS_TO` must be equal-length strings of UTF-8 characters. For example: `TRANSLATE_CHARACTERS_MODE="CHAR"`, `TRANSLATE_CHARACTERS_FROM="àëï"`, `TRANSLATE_CHARACTERS_TO="aei"`
When `TRANSLATE_CHARACTERS_MODE` is set to `HEX`, `TRANSLATE_CHARACTERS_FROM`, and `TRANSLATE_CHARACTERS_TO` must be comma-separated lists of hexadecimal UTF-8 code points with the same number of list elements. For example: `TRANSLATE_CHARACTERS_MODE="HEX"`, `TRANSLATE_CHARACTERS_FROM="c3a0,c3ab,c3af"`, `TRANSLATE_CHARACTERS_TO="61,65,69"` | `CHAR` |
| `TRANSLATE_CHARACTERS_FROM` | Sequence of UTF-8 characters in the source data to translate to a corresponding character in the `TRANSLATE_CHARACTERS_TO` option. See the `TRANSLATE_CHARACTERS_MODE` option for the expected format. | `""` |
| `TRANSLATE_CHARACTERS_TO` | Sequence of UTF-8 characters to use as a replacement for the characters included in `TRANSLATE_CHARACTERS_FROM`. See the `TRANSLATE_CHARACTERS_MODE` option for the expected format. | `""` |
| `TRIM_TRAILING_ZEROS` | Dictates whether to trim trailing zeros from numeric input fields. | `false` |
| `PARQUET_COMPRESSION` | Compression type to use for a Parquet extract. Supported compression types are: `NONE` — No compression `ZSTD` — ZSTD compression `SNAPPY` — Snappy compression `GZIP` — GZip compression | `SNAPPY` |
| `PARQUET_ROW_GROUP_SIZE_BYTES` | The size in bytes for row groups within a Parquet output file. | `536870912` (512 MB) |
If you do not set either the `MAX_ROWS_PER_FILE` or the `TARGET_FILE_SIZE_MB` options, the data extract tool generates one output file for each partition. For a query without partitions, the tool generates a single output file.
### S3 Extract Options
This table describes the required options that apply only to the `S3` location type. The data extract tool ignores these options when you use the `LOCAL` location type.
| **Option** | **Description** |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `BUCKET` | S3 bucket to use. |
| `ENDPOINT` | Endpoint for S3 upload. For details, see the documentation for [specifying endpoints](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/specifying-endpoints.html). |
This table describes optional options that apply only to the `S3` location type.
| **Option** | **Description** | **Default** |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| `AWS_KEY_ID` | AWS Key ID. If empty, the CLI uses the Java AWS SDK default credentials provider chain documented [here](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/DefaultAWSCredentialsProviderChain.html). | `""` |
| `AWS_SECRET_KEY` | AWS Secret Key. If empty, the CLI uses the Java AWS SDK default credentials provider chain documented [here](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/auth/DefaultAWSCredentialsProviderChain.html). | `""` |
| `REGION` | S3 region to upload to. Ignored when extracting to LOCAL. | `US_EAST_2` |
| `PATH_STYLE_ACCESS` | Whether [path style access](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html) should be used to access a bucket. | `true` for JDBC version 3.4.1 and `false` for JDBC version 3.4.0 and earlier |
## File Naming Conventions
When you use the data extract tool, the tool produces a number of files. The System determines the path of these files using multiple factors:
* File prefix as specified by the `FILE_PREFIX` option
* If the `PARTITION_MODE` option is not set to `NONE`, the file prefix must be a directory and end with a forward slash. The system creates subdirectories in the style for each partition (for example, for the `KEY` partition: `/tmp/extract/col1=val1/col2=val2` or for the `RANGE` partition: `/tmp/extract/val1<=col1
`sys.dummy` creates a virtual table with the specified number for rows. For details, see [Generate Tables Using sys.dummy](/generate-tables-using-sys-dummy).
**Local CSV Extract to the Specified Path**
This example extracts the results of the `SELECT c1 FROM sys.dummy10` SQL query to the local machine at the absolute path `/home/user/out/data_0.csv`. The SQL query returns 10 rows with incremental numbers starting at 1.
```sql SQL theme={null}
EXTRACT TO LOCAL OPTIONS(
file_prefix="/home/user/out/data_",
file_extension=".csv"
)
AS SELECT c1 FROM sys.dummy10;
```
**Local Parquet Extract with Partition by Key**
This example partitions customer data into a Parquet file by the `country` column. This partitioning creates a Hive-style directory structure on the local machine. Use the file path `/home/user/customer_data/` with the `KEY` value for the partition strategy. Specify the target file size to be `256` MB.
The SQL query selects the identifier, name, email, and country from the `customers` table.
```sql SQL theme={null}
EXTRACT TO LOCAL OPTIONS(
FILE_PREFIX = '/home/user/customer_data/',
FILE_TYPE = PARQUET,
PARTITION_MODE = 'KEY',
PARTITION_COLUMNS = 'country',
TARGET_FILE_SIZE_MB = 256
) AS SELECT id, name, email, country FROM customers;
```
The resulting file structure has these file paths.
```
/home/user/customer_data/country=US/part-0000.parquet
/home/user/customer_data/country=CA/part-0000.parquet
...
```
**S3 Parquet Extract with Compression**
This example extracts all sales data from the `today_sales` table to a single Parquet file on S3 using ZSTD compression. Use the S3 bucket named `my-analytics-bucket` with the file path `daily_reports/report.parquet` using the endpoint `s3.us-east-1.amazonaws.com`.
```sql SQL theme={null}
EXTRACT TO S3 OPTIONS(
BUCKET = 'my-analytics-bucket',
FILE_PREFIX = 'daily_reports/report.parquet',
ENDPOINT = 's3.us-east-1.amazonaws.com',
FILE_TYPE = PARQUET,
PARQUET_COMPRESSION = 'ZSTD'
) AS SELECT * FROM today_sales;
```
**S3 Parquet Extract with Partitioning by Range**
This example extracts large event data to S3 by splitting the `event_id` column into `30` parallel queries using the `RANGE` partition strategy. Specify the maximum file size in `1024` megabytes. Override the default row group size using the `PARQUET_ROW_GROUP_SIZE_BYTES` option to specify `268435456` bytes (256 MB).
Use the S3 bucket `iot-data` with the file path `events/2025-09-25/` at endpoint `s3.us-east-1.amazonaws.com`.
The SQL query selects the event identifier, sensor identifier, sensor reading, and timestamp from the `events` table.
```sql SQL theme={null}
EXTRACT TO S3 OPTIONS(
BUCKET = 'iot-data',
FILE_PREFIX = 'events/2025-09-25/',
ENDPOINT = 's3.us-east-1.amazonaws.com',
FILE_TYPE = PARQUET,
PARTITION_MODE = 'RANGE',
PARTITION_COLUMNS = 'event_id',
NUM_FETCH_QUERIES = 30,
TARGET_FILE_SIZE_MB = 1024,
PARQUET_ROW_GROUP_SIZE_BYTES = 268435456
) AS SELECT event_id, sensor_id, sensor_reading, ts FROM events;
```
## Related Links
[Connect Using JDBC](/connect-using-jdbc)
[JDBC Manual](/jdbc-manual)
# Data Formats for Data Pipelines
Source: https://docs.ocient.com/data-formats-for-data-pipelines
Load JSON, DELIMITED, Avro, Parquet, and other formats into Ocient with data pipelines, including field selectors, type interpretation, and NULL handling.
Loading in differs in subtle ways that depend on the data format of the source. Loading runs with a strict interpretation of streaming source with or source data to allow pipelines to achieve maximum performance. For text-based formats like `JSON` and `DELIMITED`, the Ocient System performs no preemptive casting on the data when using a source field selector. For the Kafka streaming source, use the Schema Registry with subjects that contain a group of schema versions, which capture the schema changes over time.
For example, with the JSON string `{ "my_field": 1234 }`, the selector `$my_field` returns the string `"1234"` not the integer `1234`.
When you use transformation functions, keep in mind that the Ocient System treats all data in the `JSON` and `DELIMITED` formats as text data.
While the Ocient System sends data you select to a final target column, the system automatically casts the data in the final step to ensure that the data is compatible with the target column type. See [Data Types for Data Pipelines](/data-types-for-data-pipelines) for supported automatic conversion rules.
Format-specific differences also appear in the pipelines.
## Load ASN.1 Data
You can load data in ASN.1 (Abstract Syntax Notation One) format from binary-encoded ASN.1 files using DER-encoded or BER-encoded files. ASN.1 provides a flexible, schema-driven format commonly used in telecommunications, security, and standardized protocols. This format allows you to extract structured records and map them to relational tables using SQL.
The Ocient System requires `.ber` and `.der` files to contain one or more concatenated DER-encoded or BER-encoded values with the specified record type. The system decodes each record independently and maps it into a record.
### ASN.1 Type Mapping
The system automatically converts all decoded ASN.1 fields to their JSON-equivalent representations.
The ASN.1 schema must consistently use implicit or explicit tagging. You must specify clear tagging so the system can resolve field names during extraction.
| **ASN.1 Type** | **JSON Mapping** | **Description** |
| ----------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `INTEGER` | Number | The number, specified as an integer.
Example: `5` |
| `BOOLEAN` | Boolean | The logical value, specified as a Boolean.
Example: `true` |
| `VisibleString` | String | The ASN.1 type assumes UTF-8 encoding.
Example: `"Data Analyst"` |
| `IA5String` | String | The International Alphabet number 5 (IA5) includes most of the ASCII alphabet but can contain other characters.
Example: `"ABCD"` |
| `UTF8String` | String | The ASN.1 type assumes UTF-8 encoding.
Example: `"abcd"` |
| `OCTET STRING` | Hexadecimal string | The hexadecimal string has the prefix `0x`.
Example: `"0x4fa2"` |
| `BIT STRING` | Hexadecimal string | The hexadecimal string with preserved bit alignment has the prefix `0x`.
Example: `"011110"` |
| `OBJECT IDENTIFIER` | String | The unique identifier for an object using dotted representation.
Example: `"1.2.840.113549"` |
| `ENUMERATED` | Number or symbolic string | The enumerated string, if the data resolves into a list of named items.
Example: `"red"` |
| `ANY` | Hexadecimal string | The hexadecimal string with raw encoded bytes of the embedded value.
Example: `"0x616263"` |
| `SEQUENCE`, `SET` | JSON object | Object with fields that are accessible by their component names.
Example: `WeatherRecord ::= SEQUENCE { temperature INTEGER, humidity INTEGER, cloudy BOOLEAN }` |
| `SEQUENCE OF`, `SET OF` | JSON array | Array of objects where the elements are fully decoded.
Example: `WeatherEvents ::= SEQUENCE OF WeatherRecord` |
| `CHOICE` | JSON object | An object with fields of any type. Identify the active alternative by the key.
Example: `WeatherReport ::= CHOICE { sunny SEQUENCE { uv\_index INTEGER }, rainy SEQUENCE { precipitation INTEGER } }` |
| `DATE` | String | Date in the format `"yyyyMMdd"`. You must explicitly declare the date, or the system must infer it using tagging.
Example: `"20240518"` |
| `TIME` | String | Time in the format `"HHmmss"`.
Example: `"113056"` |
| `DATE-TIME` | String | Date and time in the format `"yyMMddHHmmss'Z'"`. This format supports only UTC. You must include `'Z'` as a literal.
Example: `"250920101508'Z'"` |
To access fields, use dot notation for access: `$sequence.fieldName`. For arrays (such as `SEQUENCE OF`), use bracket notation: `$sequenceOf[].fieldElement`.
Default values and optional fields follow standard ASN.1 rules. If you omit a field, the system evaluates it as `NULL`.
### ASN.1 Loading Example
Assume you have the `personnel_records.asn` file in the ASN.1 data format. The file contains the definition of a personnel record `Example.PersonnelRecord`. The ASN.1 file contains data for the personnel record, child, personnel name, employee number of the personnel, and the date.
```none Text theme={null}
Example DEFINITIONS IMPLICIT TAGS ::=
BEGIN
PersonnelRecord ::= [APPLICATION 0] SET {
name [0] Name,
title [1] VisibleString,
number [2] EmployeeNumber,
dateOfHire [3] Date,
nameOfSpouse [4] Name,
children [5] SEQUENCE OF ChildInformation DEFAULT {}
}
ChildInformation ::= SET {
name [0] Name,
dateOfBirth [1] Date
}
Name ::= [APPLICATION 1] SEQUENCE {
givenName [0] VisibleString,
initial [1] VisibleString,
familyName [2] VisibleString
}
EmployeeNumber ::= [APPLICATION 2] INTEGER
Date ::= [APPLICATION 3] VisibleString
END
```
Create a table to contain the personnel record. The table contains a subset of the data:
* `first_name` — First name
* `initial` — Initial of the middle name
* `family_name` — Last name
* `title` — Job title
* `number` — Employee number
* `date_of_hire` — Hire date
```sql SQL theme={null}
CREATE TABLE personnel_records(
first_name VARCHAR NOT NULL,
initial VARCHAR NOT NULL,
family_name VARCHAR NOT NULL,
title VARCHAR NOT NULL,
number BIGINT NOT NULL,
date_of_hire DATE NOT NULL
);
```
Create the data pipeline `personnel_pipeline` to load the personnel record into the `personnel_records` table using an S3 bucket. Specify the bucket, endpoint, access key identifier, secret access key, and filter options to find the ASN.1 DER-encoded file `personnel_records.der` in the specified file path. Use the URL file path `http://cos/filepath/asn1/personnel_records.asn` and record type `Example.PersonnelRecord`. Access the `name` sequence using dot notation for the first name, middle initial, and last name fields. The pipeline definition transforms the hire date to the `'yyyyMMdd'` format.
```sql SQL theme={null}
CREATE PIPELINE personnel_pipeline
SOURCE S3
BUCKET 'misc'
ENDPOINT 'http://cos'
ACCESS_KEY_ID ''
SECRET_ACCESS_KEY ''
FILTER_GLOB 'user/asn1/personnel_records.der'
EXTRACT
FORMAT 'asn.1'
SCHEMA {
URL 'http://cos/filepath/asn1/personnel_records.asn'
RECORD_TYPE 'Example.PersonnelRecord'
}
INTO personnel_records
SELECT
$name.givenName AS first_name,
$name.initial as initial,
$name.familyName as family_name,
$title as title,
$number as number,
TO_DATE($dateOfHire, 'yyyyMMdd') as date_of_hire;
```
## Load Avro Data
The Ocient System enables you to load data in the format. You can use a streaming source with a file-based source only. Load an inline schema definition or use a schema configuration. Use a schema inference from files with embedded schemas.
Field selectors in Avro follow the same format as selectors in JSON and formats.
The Ocient System treats Avro selectors as lowercase. To use case-sensitive selectors, you must enclose the selector in double quotation marks. For example, `$"testSelector"`.
### Inline Schema
Specify a JSON string in the Avro schema format in the `INLINE` option of the schema definition of the `CREATE PIPELINE` SQL statement.
Inline schemas assume that all records follow the defined schema exactly. These schemas do not support schema evolution.
For Kafka messages, use the `SCHEMA_REGISTRY_ID_LOCATION` option to denote whether there is an embedded schema identifier. For inline schemas, the `'none'` value indicates that no embedded schema identifier is present.
### Schema Inference from a File
The system can infer the schema from a file that has embedded schemas. The file is a named object container file. Use the `INFER_FROM` option in the `CREATE PIPELINE` SQL statement to specify sampling one file.
### Schema Registry
For loading from a Kafka streaming source, use the schema configuration with the `SUBJECT` option in the `CREATE PIPELINE` SQL statement to specify the name of the subject for the data pipeline. The default value is `-value`, where `` is the name of the Kafka topic. The Ocient System follows the schema registry configuration from the Confluent platform.
### Schema Evolution
When you create a data pipeline, the pipeline has a fixed target schema (specified by the `SELECT` clause). Individual files might have different schemas. The target schema must be backward-transitive compatible with the other schemas. Individual files or Kafka messages might have different schemas.
If the other schemas change, the system automatically attempts to fit data into the target schema. In this case, the other schemas must be forward compatible with the target schema. The system ignores changes to any unused fields from the target schema.
To manually change the schema, you must first stop the execution of the data pipeline by using the `STOP PIPELINE` SQL statement. Then, use the `ALTER PIPELINE` SQL statement to modify the schema. You can add a field, remove a field, or change the precision of a data type. For details, see the [ALTER PIPELINE](/data-pipelines#alter-pipeline) SQL statement.
Multiple schemas impact the performance of the data pipeline execution. For best performance, use a single schema for all data.
### Avro Type Mapping
The Ocient System converts these Avro data types to Ocient SQL types. This table shows the respective conversions.
| **Avro Type** | **Ocient SQL Type** |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `null` | `NULL` |
| `boolean` | `BOOLEAN` |
| `int` | `INT` |
| `long` | `BIGINT` |
| `float` | `FLOAT` |
| `double` | `DOUBLE` |
| `bytes` | `VARBINARY` |
| `string` | `VARCHAR` |
| `record` | Select subfields of the record using the standard pipeline selector syntax, e.g., `$myrecord.subfield`. |
| `enum` | `VARCHAR` |
| `array` | `ARRAY` |
| `map` | Select entries of the map using the key with the standard pipeline selector syntax, e.g., `$mymap.key`. |
| `fixed` | `HASH` |
| `decimal` | `DECIMAL` |
| `big-decimal` | `DECIMAL` |
| `uuid` | `UUID` |
| `date` | `DATE` |
| `time-*` | `TIME` |
| `timestamp-*` | `TIMESTAMP` |
| `local-timestamp-*` | `TIMESTAMP` |
| `duration` | The system converts duration to a record with integer subfields for `months`, `days`, and `milliseconds`. |
| `union` | The system converts a union between `NULL` and another type to a nullable version of that type. In contrast, the system converts a union containing multiple non-`NULL` types to a string. |
### Avro Loading Examples
Create the `users` table with these columns:
* `id` — Universally Unique IDentifier (UUID) of the user
* `firstname` — First name of the user
* `lastname` — Last name of the user
* `birthyear` — Year of birth
* `groups` — List of groups where the user belongs
```sql SQL theme={null}
CREATE TABLE users(
id UUID NOT NULL,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
birthyear INT,
groups VARCHAR(255)[] NOT NULL DEFAULT 'char[]'
);
```
These examples use this table as the target table for the load.
**Load Avro Data from Files**
Assume you have user data in Avro format in multiple files in the `/data/users` directory. Create the `users_pipeline` data pipeline for the Avro files `*.avro` containing user data. The schema configuration instructs the system to infer from one file using the `INFER_FROM` option. Access the array of strings for the `groups` column.
```sql SQL theme={null}
CREATE PIPELINE users_pipeline
SOURCE filesystem
FILTER '/data/users/*.avro'
EXTRACT
FORMAT avro
SCHEMA {
INFER_FROM 'sample_file'
}
INTO users
SELECT
$id AS id,
$firstname AS firstname,
$lastname AS lastname,
$birthyear AS birthyear,
$groups[] AS groups;
```
**Load Avro Data from an Inline Schema Definition**
Assume you have user data in Avro format in multiple files in the `/data/users` directory. Create the `users_pipeline` data pipeline for the Avro files `*.avro` containing user data. The schema configuration instructs the system to use an inline schema definition with the `INLINE` option. Access the array of strings for the `groups` column.
```sql SQL theme={null}
CREATE PIPELINE users_pipeline
SOURCE filesystem
FILTER '/data/users/*.avro'
EXTRACT
FORMAT avro
SCHEMA {
INLINE '{
"type": "record",
"name": "User",
"namespace": "test.users",
"fields": [
{ "name": "id", "type": { "type": "string", "logicalType": "uuid" } },
{ "name": "firstname", "type": "string" },
{ "name": "lastname", "type": "string" },
{ "name": "birthyear", "type": ["null","int"], "default": null },
{ "name": "groups", "type": { "type": "array", "items": "string" } }
]
}'
}
INTO users
SELECT
$id AS id,
$firstname AS firstname,
$lastname AS lastname,
$birthyear AS birthyear,
$groups[] AS groups;
```
**Load Avro Data Using a Kafka Schema Registry Configuration**
Assume you have user data in Avro format in a Kafka topic. Create the `users_pipeline` data pipeline for the user data. The schema registry configuration instructs the system to access the subject `'users-value'` at the registry location `'value'` using the registry URL `'https://schema-registry.company.com'`. The configuration specifies the access credentials using the `CONFIG` option:
* Credentials source
* User authentication that includes the username and password
* Location of the truststore
* Password for the truststore
Access the array of strings for the `groups` column.
```sql SQL theme={null}
CREATE PIPELINE users_pipeline
SOURCE
KAFKA
BOOTSTRAP_SERVERS '192.168.0.1:9092'
TOPIC 'users'
EXTRACT
FORMAT avro
SCHEMA {
SUBJECT 'users-value'
SCHEMA_REGISTRY_ID_LOCATION 'value'
URL 'https://schema-registry.company.com'
CONFIG '{
"basic.auth.credentials.source": "USER_INFO",
"basic.auth.user.info": "sr_user:sr_password",
"ssl.truststore.location": "/etc/ssl/truststore.jks",
"ssl.truststore.password": "testpassword"
}'
}
INTO users
SELECT
$id AS id,
$firstname AS firstname,
$lastname AS lastname,
$birthyear AS birthyear,
$groups[] AS groups;
```
For details about the schema registry configuration, see the [Confluent Documentation](https://docs.confluent.io/).
## Load Binary Data
The Ocient System loads the binary data format using a fixed record length to split a binary stream into chunks that represent records. Each record is available in the `SELECT` portion of a pipeline definition using a special binary extract syntax `$"[5,8]"`. This operates similarly to a substring function, beginning at byte `5` and taking `8` bytes from that location. The starting index is a 1-based offset, consistent with other SQL arrays and offsets. You can use this syntax to select specific bytes within a record to parse together as a unit.
### Binary Selector
| **Selector** | **Description** | **Examples** |
| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `$"[,]"` | **Extract Bytes** — Extracts the bytes beginning at the `` and returning `` total bytes to extract from the start index. `` is 1-based. | `abc123.45xyz` `$"[4,6]" -> "123.45"` This example illustrates the operation using ascii characters, but the Binary Selector returns BINARY data, byte arrays, that may be used in special ways by fixed width processing functions described in [Binary Data Transformations](/transform-data-in-data-pipelines#binary-data-transformation-functions). |
**Example**
The Binary Selector takes 8 bytes starting at offset 11 on the fixed-width binary record. Consistent with SQL functions in the Ocient System, the first argument value `11` is the 1-based offset into the byte array.
```sql SQL theme={null}
$"[11, 8]"
```
The Binary Selector returns `BINARY` data, not `VARCHAR`.
Special `BINARY` transformation functions can operate on this `BINARY` data. However, if you cast data to the `VARCHAR` type by using `CHAR()`, then functions like `INT` operate on this data as `VARCHAR` data, not binary data.
When you load binary data into `VARCHAR` columns, the Ocient System automatically converts from binary to character data using the configured `CHARSET_NAME` before final loading.
The Ocient System supports special transformation functions that operate uniquely on binary data. With these functions, you can convert binary representations from mainframe systems such as packed decimals, zoned decimals, big and little endian integers (signed and unsigned), and floating point values. For more details, see [Binary Data Transformation Functions](/transform-data-in-data-pipelines).
For a complete list of supported options for `DELIMITED` and `CSV` data formats, see [Binary Extract Options](/data-pipelines#binary-extract-options).
### Binary Loading Example
If each record in your fixed-width binary schema includes these fields, you can use the `SUBSTRING` function and the transforms shown in this example.
| **Column** | **Start Index** | **Record Length** | **Source Data Type** | **Ocient Target Data Type** |
| ------------ | --------------- | ----------------- | ---------------------------------- | --------------------------- |
| first\_name | 1 | 20 | Character | VARCHAR |
| last\_name | 21 | 20 | Character | VARCHAR |
| age | 41 | 4 | Big Endian signed 4-byte integer | INT |
| total\_spent | 45 | 10 | Packed Decimal | DECIMAL(10,2) |
| user\_id | 55 | 8 | Little Endian unsigned 8-byte long | BIGINT |
Each record includes 62 bytes, so the record length `RECORD_LENGTH` is 62. The encoding of this file is CP500 instead of the default IBM1047 code page. The `CREATE PIPELINE` SQL statement specifies this encoding.
```sql SQL theme={null}
CREATE PIPELINE binary_users_pipeline
SOURCE
S3 ...
FORMAT
BINARY
RECORD_LENGTH 62
CHARSET_NAME 'cp500'
INTO public.users
SELECT
$"[1, 20]" as first_name,
$"[21, 20]" as last_name,
INT($"[41, 4]") as age,
DECIMAL($"[45, 10]", 'packed', 2) as total_spent,
BIGINT($"[55, 8]", 'unsigned', 'little') as user_id;
```
This SQL statement:
* Uses the `BINARY SELECTOR` to extract names and load them into the respective columns. The Ocient System automatically decodes the values using `cp500` and loads them into a `VARCHAR` column. An explicit cast such as `CHAR($"[1, 20]") as first_name` works equivalently.
* Indicates the extraction of four bytes that represent age from bytes 41-44. The statement instructs the casting of these bytes as an integer `INT`. This function uses the default endianness (big) and treats the bytes as signed. Unsigned values can overflow target columns because integral types are all signed.
* Extracts the 10 bytes for `total_spent` using the `BINARY SELECTOR`, and converts the values using the `packed` decimal option for the `DECIMAL` cast. The casting requires specifying the number of decimal points in the source data. In this case, there are 2 decimal points, which match the number in the target column.
* Extracts the 8 bytes that represent `user_id` using the `BINARY SELECTOR` and casts these bytes to a `BIGINT` while interpreting the bytes as unsigned with the little endian representation.
## Load Delimited and CSV Data
When you load data from delimited or CSV files, the Ocient System tokenizes the data during loading. The system detects records and fields in the input data during pipeline execution. You can reference fields and use them in combination with transformation functions before the system stores values in the column of a target table.
Files must be located in these allowed directories:
* `/tmp` directory
* The temporary directory you configure using the `streamloader.extractorEngineParameters.tempDir` configuration option (default path is `/var/opt/ocient/tmp`).
* The directory list specified by the `streamloader.extractorEngineParameters.configurationOption.filesystem.access.directories `configuration option (default is an empty list).
Files cannot be located in these blocked directories:
* `/etc`
* `/bin`
* `/sbin`
* `/lib`
* `/lib64`
* `/usr`
* `/boot`
* `/proc`
* `/sys`
* `/run`
* `/root`
* `/var/lib`
* `/var/log`
* `/var/run`
* `/var/cache`
Referencing fields of the source data for the formats happens by using a field index. The index is a number that follows the dollar sign `$`. To maintain consistency with SQL array semantics, the field indexes start at 1.
Reference the first field of tokenized source records for the `DELIMITED` and `CSV` formats as `$1`.
For the `BINARY` format, `$0` represents the entire record. In this case, you must specify `$0` in combination with the `SUBSTRING` function to extract specific bytes from the source data.
For a complete list of supported options for `DELIMITED` and `CSV` data formats, see [Delimited and CSV Extract Options](/data-pipelines#delimited-and-csv-extract-options).
### Delimited Loading Example
Use this example delimited data.
```none Text theme={null}
iphone|60607|viewed|502|293.99|[shopping,news]
```
For this example row, this table shows the field references for each value in the row.
| **Field Reference** | **Value** |
| ------------------- | ---------------------- |
| \$1 | iphone |
| \$2 | 60607 |
| \$3 | viewed |
| \$4 | 502 |
| \$5 | 293.99 |
| \$6\\\[] | \\\['shopping','news'] |
To load this data in a pipeline with the `DELIMITED` data format, this `CREATE PIPELINE` statement specifies the `|` character for the field delimiter. This statement loads data into AWS S3. The `SELECT` statement uses fields 1, 2, 3, 5, and 6 of the source data. The statement specifies that the system should not load field 4 to the target table. Field 6 is an array of data matching the default array settings for delimited data. You can indicate this with the array brackets like `$6[]` to load into a `CHAR[]` typed column.
The outer casting functions in this example are optional and shown for completeness. If they are omitted, the pipeline automatically casts the source fields to the target column type.
```sql SQL theme={null}
CREATE PIPELINE delimited_pipeline
SOURCE s3
...
FORMAT delimited
FIELD_DELIMITERS ['|']
...
SELECT
CHAR($1) as device_model,
INT($2) as zip,
INT($3) as amount,
DOUBLE($5) as price,
CHAR[]($6[]) as categories;
```
## Load JSON Data
The data pipeline syntax enables the load of JSON data, including nested scalars, arrays, and points `ST_POINT`.
**Strict Loading and Transformations**
When you use transformation functions, remember that the Ocient System treats all data in `JSON` and `DELIMITED` format as text data, not the `logical` data type.
For example, if you specify the JSON string `{ "my_timestamp": 1709208000000 }`, the selector `$my_timestamp` returns the string `"1709208000000"` and not the integer `1709208000000`.
As a result, if you cast this data into a timestamp column, such as `TIMESTAMP($my_timestamp) as created_at`, the Ocient System returns an error. The conversion fails because the cast function assumes you are specifying `TIMESTAMP(VARCHAR)`, which assumes a format like `YYYY-MM-DD HH🇲🇲ss[.SSSSSSSSS]`.
To correct this issue, cast the value explicitly to make use of the `TIMESTAMP(BIGINT)` function that treats the argument as milliseconds after the epoch as in `TIMESTAMP(BIGINT($my_timestamp)) as created_at`.
### Supported JSON Selectors
JSON selectors consist of `$` followed by a dot-separated list of JSON keys. If a key refers to an array, it is followed by a set of brackets `[]` to correspond to its dimensionality. If the square brackets contain an index, like `[1]`, then the selector refers to an array element.
The Ocient System treats JSON selectors as lowercase. To use case-sensitive selectors, you must enclose the selector in double quotation marks. For example, `$"testSelector"`. With case-sensitive selectors having multiple JSON keys, each key needs double quotation marks. For example, `$"testData"."Responses"."SuccessResponse"`.
For special characters (any identifier that starts with any character other than a letter or contains any character that is not a letter, number, or an underscore) or reserved SQL keywords (such as `SELECT`), you must enclose such selectors in double quotation marks. For example, if you have a JSON document `{ "test-field": 123 }`, then the selector for the query should be `$"test-field"`.
The Ocient System does not support identifiers with a backslash as the last character in the key name.
This table shows the selector and provides its description. The cells in the last column of the table show an example for each selector. First, the cell shows example data in JSON format. Then, the cell shows the use of the selector and its output after the arrow.
| **Selector** | **Description** | **Examples** |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `$a` | **Scalar** — Refers to key `a` at the top of a JSON document, where the value of `a` is a scalar. | `{ "first_name": "Chris" }`
`$first_name -> "Chris"` |
| `$a[]` | **Array** — Refers to key `a` at the top of a JSON document, where the value of `a` is a one-dimensional array. | `{ "names": ["Chris", "Joe"] }` `$names[] -> ["Chris","Joe"]` |
| `$a[1]` | **Array Element Selection** — Selects a single element from the array `a` at the top of a JSON document, where the value of `a` is a one-dimensional array. Also works on multi-dimensional arrays. Indexes start at 1. | `{ "names": ["Chris", "Joe"] }` `$names[2] -> "Joe"` |
| `$a[][]` | **Multi-dimensional Array** — Refers to key `a` at the top of a JSON document, where the value of `a` is a two-dimensional array. | `{ "coordinates": [ [87.31, 18.25],[65.22, 19.41]] }` `$coordinates[][] -> [[87.31,18.25],[65.22,19.41]]` |
| `$a.b.c` | **Nested Selector** — Drills into the value at key `a`, then value at key `b`, and refers to the value at key `c`, where none of the values are arrays. | `{ "user": { "name": "Chris" } }` `$user.name -> "Chris"` |
| `$a[].b` | **Array Projection** — A projection applies a JSON selector on all elements in an array, returning an array. Array brackets in the notation indicate which items are the arrays. The `a[]` is an array. The `b` selector is applied to each element in the array `a`. | `{` `"users": [` `{` `"name": "Chris",` `"orders": [` `{ "order_id": 1,` `"subtotal": 19.29 },` `{ "order_id": 2,` `"subtotal": 16.71 }` `]` `},` `{` `"name": "Joe",` `"orders": [` `{ "order_id": 3,` `"subtotal": 17.29 },` `{ "order_id": 4,` `"subtotal": 22.49 }` `]` `}` `]` `}` `$users[].name -> ["Chris", "Joe"]` |
| `$a.b[].c.d[]` | **Multi-level Array Projection** — Applies selectors to each element in the specified arrays and allows multiple levels of objects and arrays for the selection of an N-dimensional array of values. The values of `b` and `d` are arrays, resulting in two-dimensional arrays. The selector `c.d[]` is projected into the elements in the array `b`. | `{` `"users": [` `{` `"name": "Chris",` `"orders": [` `{ "order_id": 1,` `"subtotal": 19.29 },` `{ "order_id": 2,` `"subtotal": 16.71 }` `]` `},` `{` `"name": "Joe",` `"orders": [` `{ "order_id": 3,` `"subtotal": 17.29 },` `{ "order_id": 4,` `"subtotal": 22.49 }` `]` `}` `]` `}` `$users[].orders[].order_id -> [[1,2],[3,4]]` |
| `$a.b[1].c.d[]` | **Array Slice** — Selects the first element from the array `b` and drills into `c` and then the array `d`. JSON array selectors have an index that starts at 0. | `{` `"users": [` `{` `"name": "Chris",` `"orders": [` `{ "order_id": 1,` `"subtotal": 19.29 },` `{ "order_id": 2,` `"subtotal": 16.71 }` `]` `},` `{` `"name": "Joe",` `"orders": [` `{ "order_id": 3,` `"subtotal": 17.29 },` `{ "order_id": 4,` `"subtotal": 22.49 }` `]` `}` `]` `}` `$users[1].orders[].subtotal -> [17.29,22.49]` |
| `$a.{b,c}` | **Tuple Selector** — Selects the values from an object as a tuple. You must cast the values to an appropriate `TUPLE` data type. | `{ "user": { "first_name": "John", "last_name": "Doe" }}` `$user.{first_name,last_name} -> <<"John","Doe">>` |
| `$a[].{b,c}` | **Array of Tuples Selector** — Selects the values from an array of objects as an array of tuples. You must cast the values to an appropriate `TUPLE[]` data type. | `{ "users": [ { "first_name": "John", "last_name": "Doe" }, { "first_name": "Steve", "last_name": "Smith" } ]}` `$users[].{first_name,last_name} -> [<<"John","Doe">>,<<"Steve","Smith">>]` |
| `$a[_]` | **Flatten Array Selector** — Selects the values of an array and flattens the dimension indicated by the underscore by one level. | `{` `a: {` `b: [` `{c: [1,2,3] },` `{c: [4,5,6] }` `]` `}` `}` `$a.b[_].c -> [1,2,3,4,5,6]` |
| `$a[!]` | **Compact Array Selector** — Selects the values of an array and removes any NULL values from the array at this level in the array. | `{` `a: {` `b: {` `c: [1,null,2,null,3]` `}` `}` `}` `$a.b.c[!] -> [1,2,3]` |
For more examples of using JSON selectors in data pipelines, see [JSON Selectors Examples in Data Pipelines](/json-selectors-examples-in-data-pipelines).
### NULL and Empty Handling for JSON Scalars
The Ocient System handles all JSON NULL, empty, and missing values in the same way. The system loads these values as `NULL`. These values fail to load into non-nullable columns.
Provide an explicit default in the pipeline using `IF_NULL` or `COALESCE` or use the `COLUMN_DEFAULT_IF_NULL` option to accept the configured column default instead of attempting to load `NULL` values.
### NULL and Empty Handling for JSON Arrays
The Ocient System handles NULL, empty, and missing values the same way for arrays as for scalars. The system converts a value that is NULL, empty, or missing to NULL and loads it as `NULL`.
Provide an explicit default in the pipeline or use the `COLUMN_DEFAULT_IF_NULL` option to accept the configured column default instead of attempting to load `NULL`.
### NULL and Empty Handling for JSON Tuples
All the rules for handling NULL, empty, and missing elements that apply to scalars and arrays also apply to tuples. If any part of the selector is NULL, empty, or missing, data pipeline loading converts that value to `NULL`.
Additionally, because you can apply functions to tuple elements (and not array elements), you can use the `NULL_IF` function to convert a tuple element to `NULL`. For example, `tuple<>($a.name, NULL_IF($a.hometown, 'N/A') )` indicates to the pipeline that the string `'N/A'` signifies `NULL` for the `hometown` element but not for the `name` element.
## Load Parquet Data
The data pipeline functionality enables loading Parquet files with this configuration.
**File Configuration**
* Files should have row groups of less than 128 MB. Larger row groups can impact memory usage during loading, and row groups of 512 MB can cause loading failures on 1 TB or more data sets.
* Encoding fields in a Parquet file reduces the space of the file on disk but can impact memory usage during loading. Enable encoding on fields that you expect to have less than 256 unique values and for fields that contain short strings. You do not have to encode other fields.
**Multiple Files**
* You can load row groups of multiple Parquet files in parallel. For large data sets, load the data set as multiple files.
* Loading files with differing schemas is not supported.
Use selectors as you do when loading JSON data to specify data to load.
You must select a leaf element, an array, or a tuple with your selector. This is stricter than using JSON selectors, which can directly select array fields and JSON object fields.
Example: `{"a": [1,2,3], "b": {"c": 1}}`
You can extract with any of the selectors in JSON: `$a, $a[], $b, $b.c`
However, Parquet only allows for the selectors: `$a[], $b.c`
This example assumes this schema:
```
// List (list non-null, elements nullable)
required group my_list (LIST) {
repeated group list {
optional binary element (UTF8);
}
}
```
The selector must be `$my_list[]`, which includes the array syntax.
For details, see [Parquet Selectors Examples in Data Pipelines](/parquet-selectors-examples-in-data-pipelines).
When you use the `FORMAT PARQUET` option with an AWS S3 source, the `ENDPOINT` option is required in the `CREATE PIPELINE` SQL statement.
Auto-casting in Parquet does not support the automatic conversion to `VARCHAR` columns. You must explicitly cast data to the `CHAR` data type when you convert Parquet data that is not string data to a `VARCHAR` column or `VARCHAR` function argument.
The Ocient System treats Parquet selectors as lowercase. To use case-sensitive selectors, you must enclose the selector in double quotation marks. For example, `$"testSelector"`.
### Schema Evolution
The Ocient System supports schema evolution when you load a set of Parquet files.
Specifically, if the pipeline selects a set of Parquet files where an individual file might have more or fewer columns than another, the system attempts to merge those schemas together to support loading without requiring you to create the pipeline again.
For example, the `test_table` table has three columns.
```sql SQL theme={null}
CREATE TABLE test_table (
col_a INT NULL,
col_b VARCHAR NULL,
col_c VARCHAR NULL
);
```
You have two Parquet files with these schemas:
```none Text theme={null}
message file1_schema {
OPTIONAL INT32 col_a;
OPTIONAL BYTE_ARRAY col_b (UTF8);
}
message file2_schema {
OPTIONAL BYTE_ARRAY col_b (UTF8);
OPTIONAL BYTE_ARRAY col_c (UTF8);
}
```
However, you must specify how to handle the schema evolution within the `EXTRACT` SQL statement. You can choose to sample the first file only for its schema or sample the entire data set to merge the schemas together. This DDL statement samples on one file.
```sql SQL theme={null}
EXTRACT
FORMAT parquet
SCHEMA (INFER_FROM sample_file)
```
The disadvantage is that sampling multiple files can potentially take a long time (scaling with the number of files in the data set) when you execute the `CREATE PIPELINE` and `START PIPELINE` SQL statements. If you know that all of the Parquet files have the same schema, use this syntax.
The Ocient System does not support the case where a column within the schema changes type. For example, if `col_a` is an `INT` type in one file and a `VARCHAR` type in another.
The default behavior of schema evolution infers the schema from one file. Use this syntax to infer from one file.
```sql SQL theme={null}
EXTRACT
FORMAT parquet
SCHEMA (INFER_FROM sample_file)
```
### Parquet Type Mapping
Parquet data types are separated into primitive and logical types. The Ocient System converts these types to Ocient SQL types. See these tables for the respective conversions.
| **Parquet Primitive Type** | **Ocient SQL Type** |
| -------------------------- | ------------------- |
| `BOOLEAN` | `BOOLEAN` |
| `INT32` | `INT` |
| `INT64` | `BIGINT` |
| `INT96` | `TIMESTAMP` |
| `FLOAT` | `FLOAT` |
| `DOUBLE` | `DOUBLE` |
| `BYTE_ARRAY` | `VARCHAR` |
| `FIXED_LEN_BYTE_ARRAY` | `VARCHAR` |
| **Parquet Logical Types** | **Ocient SQL Type** |
| ------------------------- | ------------------- |
| `STRING` | `VARCHAR` |
| `UTF8` | `VARCHAR` |
| `ENUM` | `VARCHAR` |
| `UUID` | `UUID` |
| `INT8` | `TINYINT` |
| `INT16` | `SMALLINT` |
| `INT32` | `INT` |
| `INT64` | `BIGINT` |
| `UINT8` | `SMALLINT` |
| `UINT16` | `INT` |
| `UINT32` | `BIGINT` |
| `UINT64` | `BIGINT` |
| `DECIMAL` | `DECIMAL` |
| `DATE` | `DATE` |
| `TIME` | `TIME` |
| `TIME_MILLIS` | `TIME` |
| `TIME_MICROS` | `TIME` |
| `TIMESTAMP` | `TIMESTAMP` |
| `TIMESTAMP_MILLIS` | `TIMESTAMP` |
| `TIMESTAMP_MICROS` | `TIMESTAMP` |
| `DURATION` | `BIGINT` |
| `JSON` | `VARCHAR` |
| `BSON` | `VARCHAR` |
* The `INTERVAL` data type is not supported.
* The `UINT64` data type can overflow the `BIGINT` conversion.
* The `DURATION` data type conversion to `BIGINT` preserves the underlying units. For example, the number of microseconds stays as microseconds in the `BIGINT` data type.
Further, Parquet contains nested types that the Ocient System also converts to SQL types, as shown in this table.
| **Parquet Nested Types** | **Ocient SQL Type** |
| ------------------------ | ------------------- |
| `LIST` | `TYPE[]` |
| `TUPLE` | `TUPLE` |
### Parquet Loading Example
Create a data pipeline that loads Parquet files using an AWS S3 bucket. Specify the bucket, endpoint, access key identifier, secret access key, and filter options to find all Parquet files in the specified file path. Use the `parquet_base_table` table to store the loaded data. Retrieve the integer, text, floating point, double, integer, JSON, and BSON fields.
```sql SQL theme={null}
CREATE PIPELINE testpipeline
SOURCE S3
BUCKET 'testbucket'
ENDPOINT 'https://endpoint'
ACCESS_KEY_ID ''
SECRET_ACCESS_KEY ''
FILTER_GLOB '/data/*/2024/*/*.parquet'
PREFIX '/data/orders/2024/11/'
EXTRACT
FORMAT PARQUET
INTO parquet_base_table
SELECT $int32_field AS int32_field,
$utf8_field as utf8_field,
$float_field as float_field,
$double_field as double_field,
$int64_field as int64_field,
$json_field as json_field,
$bson_field as bson_field;
```
### Parquet File-Partitioned Data
With Parquet, you can load file-partitioned data from Parquet files using the file path structure. Use the filter set in the file path using the naming standards.
Assume files with these file paths.
```shell Shell theme={null}
s3://data/orders/2024/11/dt=2024-11-24/file.parquet
.../dt=2024-11-25/file.parquet
.../dt=2024-11-26/file.parquet
...
```
Load the data values in the Parquet file partitions using the `METADATA` function with the Hive partition syntax and the specified partition key `dt` from the file paths.
```sql SQL theme={null}
SELECT int32_field,
utf8_field,
float_field,
double_field,
int64_field,
json_field,
bson_field,
METADATA('hive_partition','dt') AS file_date;
```
For details about this syntax, see [Load Metadata and File-Based Partitioned Data in Data Pipelines](/load-metadata-and-file-based-partitioned-data-in-data-pipelines).
## Load XML Data
You can load data in XML format into the Ocient System. The system supports XML tags, basic elements, nested elements, and CDATA, but it does not support XML arrays and attributes.
### Supported XML Selectors
Like JSON selectors, you can select XML data using the `$` symbol followed by a list of dot-separated JSON keys.
The system treats JSON selectors as lowercase. To use case-sensitive selectors, you must enclose the selector in double quotation marks, such as `$"testSelector"`. With case-sensitive selectors having multiple JSON keys, each key needs double quotation marks, such as `$"testData"."Responses"."SuccessResponse"`.
The system does not support JSON array and tuple selectors.
### XML Loading Example
Assume an XML file with this data.
```xml XML theme={null}
Barbara SmithNew York12345127.0.0.1]]>
```
Create a table to contain the IP address record:
* `name` — Name
* `city` — Name of the city
* `zip` — Zip code
* `personal_ip` — IP address
```sql SQL theme={null}
CREATE TABLE example_xml(
name VARCHAR NOT NULL,
city VARCHAR NOT NULL,
zip VARCHAR NOT NULL,
personal_ip IPV4 NOT NULL
);
```
Create a data pipeline `xml_pipeline` that loads the XML file `test.xml` using an AWS S3 bucket. Specify the bucket, endpoint, access key identifier, secret access key, and filter options to find the XML file in the specified path. Use the `example_xml` table to store the loaded data. Use JSON selectors to parse the file and data in each XML tag.
The system parses the `CDATA` section in the `note` tag as the literal string `Personal IP 127.0.0.1`. Use the `SUBSTRING` function to extract the IP address and then transform it into an IPV4 type with the `IPV4` function. For details, see the [SUBSTRING](/character-and-binary-functions#substring) and [IPV4](/network-type-functions#ipv4) functions.
```sql SQL theme={null}
CREATE PIPELINE xml_pipeline
SOURCE S3
BUCKET 'testbucket'
ENDPOINT 'https://endpoint'
ACCESS_KEY_ID ''
SECRET_ACCESS_KEY ''
FILTER_GLOB '/data/text.xml'
EXTRACT
FORMAT XML
INTO example_xml
SELECT
$"root"."person"."name" as name,
$"root"."address"."city" as city,
$"root"."address"."zip" as zip,
IPV4(SUBSTRING($"root"."person"."note", 16, 9)) as personal_ip;
```
## Related Links
[JSON Selectors Examples in Data Pipelines](/json-selectors-examples-in-data-pipelines)
[Data Pipelines Reference](/data-pipelines)
[Load Metadata and File-Based Partitioned Data in Data Pipelines](/load-metadata-and-file-based-partitioned-data-in-data-pipelines)
# Data Integrity and Storage
Source: https://docs.ocient.com/data-integrity-and-storage
How Ocient maintains data integrity at exabyte scale with checksums, segment redundancy, parity, fault tolerance, and storage cluster configuration.
provides several capabilities to check on the quality of data on a node and to quarantine segment groups that are problematic for any reason. Also, you can manage pages by converting them to segments. Related to data integrity is the ability to rebuild tasks. For details, see [Distributed Tasks](/distributed-tasks).
## ALTER SEGMENT QUARANTINE
`ALTER SEGMENT QUARANTINE` isolates segment groups from segment generation or queries. Use this SQL statement if segments are causing unexpected results or crashes. The segments can be un-quarantined by setting `quarantine_level` to `none`.
**Syntax**
```sql SQL theme={null}
-- To quarantine a single segment group:
ALTER SEGMENT QUARANTINE FOR { }
WHERE SEGMENT_GROUP_ID = seg_id
-- To quarantine multiple segment groups:
ALTER SEGMENT QUARANTINE FOR { }
WHERE SEGMENT_GROUP_ID in ( seg_id [,...] )
::=
segment_generation | query | all | none
```
| **Parameter** | **Data type** | **Description** |
| ------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `seg_id` | numeric | The identification numbers for segment groups. Depending on your `ALTER SEGMENT QUARANTINE` statement, the Ocient System quarantines the specified segment groups for having an existing quarantine removed. For details about finding abnormal segments, see the [Guide to Rebuilding Segments](/guide-to-rebuilding-segments). |
### Using Quarantine Levels ( `` )
You can place quarantines at these segment levels.
| **Level** | **Description** |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `segment_generation` | Isolates the specified segments from segment generation. This statement prevents corrupt data from causing problems while still leaving the data available for future analysis. |
| `query` | Isolates segment groups from subsequent queries. Data that is quarantined at the query level is not returned by database queries. This can be useful to prevent corrupt data from causing query problems while leaving it available for future analysis. |
| `all` | Isolates the specified segments from segment generation and subsequent queries. |
| `none` | Removes any quarantines from the specified segments. |
**Examples**
This example quarantines a single segment group from `segment_generation`.
```sql SQL theme={null}
ALTER SEGMENT QUARANTINE FOR segment_generation WHERE SEGMENT_GROUP_ID = 123456789;
```
This example quarantines multiple segment groups from `segment_generation`.
```sql SQL theme={null}
ALTER SEGMENT QUARANTINE FOR segment_generation WHERE SEGMENT_GROUP_ID IN (1,2,3,4,5);
```
This example removes a quarantine from a single-segment group.
```sql SQL theme={null}
ALTER SEGMENT QUARANTINE FOR none WHERE SEGMENT_GROUP_ID = 123456789;
```
This example removes a quarantine from multiple segment groups.
```sql SQL theme={null}
ALTER SEGMENT QUARANTINE FOR none WHERE SEGMENT_GROUP_ID IN (1,2,3,4,5);
```
This example quarantines at the `query` level.
```sql SQL theme={null}
ALTER SEGMENT QUARANTINE FOR query WHERE SEGMENT_GROUP_ID = 123456789;
```
This example removes a quarantine at the `query` level.
```sql SQL theme={null}
ALTER SEGMENT QUARANTINE FOR none WHERE SEGMENT_GROUP_ID = 123456789;
```
This example quarantines at both the query and segment-group levels.
```sql SQL theme={null}
ALTER SEGMENT QUARANTINE FOR all WHERE SEGMENT_GROUP_ID = 123456789;
```
## DRAIN PAGES
The `DRAIN PAGES` SQL statement instructs the Ocient System to immediately convert buffered pages into segments on one or more Loader Nodes. During normal operation, the system converts pages to segments automatically based on internal thresholds and timeouts, so the `DRAIN PAGES` statement is usually needed only in special circumstances. For example, draining pages can be useful before performing planned maintenance on Loader Nodes.
The SQL statement targets all Loader Nodes by default. You can optionally scope the operation to a specific storage scope or table, and you can restrict it to a subset of Loader Nodes.
The `DRAIN PAGES` statement forces the immediate restructuring of buffered data into durable segments, which can affect system resource utilization and loading performance. Contact Ocient Support before using this SQL statement.
**Required Privileges**
* To drain all pages or drain pages for a specific storage scope, you must have `UPDATE` privileges on the system.
* To drain pages for a specific table, you must have `UPDATE` privileges on the system or `DELETE` privileges on the database that contains the table.
**Syntax**
```sql SQL theme={null}
DRAIN PAGES
[ FOR { SCOPE UUID = scope_uuid
| TABLE UUID = table_uuid } ]
[ WITH LOADERS loader_name [, loader_name [, ...] ] ]
```
| **Parameter** | **Type** | **Description** |
| ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `scope_uuid` | string | The Universally Unique IDentifier (UUID) of a storage scope. When you specify this value, the system converts only pages that belong to this storage scope. This value is mutually exclusive with the `table_uuid` value. To find storage scope UUIDs, query the [sys.storage\_scopes](/system-catalog#sys-storage_scopes) system catalog table. |
| `table_uuid` | string | The UUID of a table. When you specify this value, the system converts only pages that belong to this table. This value is mutually exclusive with the `scope_uuid` value. To find table UUIDs, query the [sys.tables](/system-catalog#sys-tables) system catalog table. |
| `loader_name` | string | The name of a Loader Node. When you specify one or more loader names, the system sends the drain request only to those nodes.
By default, the system sends the request to all Loader Nodes. |
**Examples**
**Drain All Pages**
This example converts all buffered pages to segments across every Loader Node.
```sql SQL theme={null}
DRAIN PAGES;
```
**Drain Pages for a Storage Scope**
This example converts only pages associated with the storage scope identified by the UUID `a1b2c3d4-e5f6-7890-abcd-ef1234567890`.
```sql SQL theme={null}
DRAIN PAGES
FOR SCOPE UUID = 'a1b2c3d4-e5f6-7890-abcd-ef1234567890';
```
**Drain Pages for a Table**
This example converts only pages associated with the table identified by the UUID `12345678-abcd-ef01-2345-6789abcdef01`.
```sql SQL theme={null}
DRAIN PAGES
FOR TABLE UUID = '12345678-abcd-ef01-2345-6789abcdef01';
```
**Drain Pages on Specific Loader Nodes**
This example sends the drain request to the `loader-node-1` and `loader-node-2` Loader Nodes.
```sql SQL theme={null}
DRAIN PAGES
WITH LOADERS 'loader-node-1', 'loader-node-2';
```
**Drain Pages for a Table on a Specific Loader Node**
This example converts only pages associated with the table identified by the UUID `12345678-abcd-ef01-2345-6789abcdef01` on the `loader-node-1` Loader Node.
```sql SQL theme={null}
DRAIN PAGES
FOR TABLE UUID = '12345678-abcd-ef01-2345-6789abcdef01'
WITH LOADERS 'loader-node-1';
```
## Related Links
[Errors and Warnings](/errors-and-warnings)
# Data Manipulation Language (DML) Statement Reference
Source: https://docs.ocient.com/data-manipulation-language-dml-statement-reference
Reference Data Manipulation Language (DML) statements in Ocient to insert, delete, truncate, and manage transactional changes to data in tables.
DML statements let you add, remove, and manage the data stored in tables. You can write and execute DML statements like any other SQL statements in the System. The SELECT SQL statement is sometimes considered a DML statement, and the Ocient System includes it in the Data Query Language (DQL). For details, see the [Data Query Language (DQL) Statement Reference](/data-query-language-dql-statement-reference).
Supported DML SQL statements are:
* DELETE FROM TABLE
* INSERT INTO TABLE
* TRUNCATE TABLE
## DELETE FROM TABLE
Removes rows from the specified table.
You can use the `WHERE` clause to specify the rows to remove. If a `DELETE` SQL statement lacks the `WHERE` clause, then the database deletes all rows in the table.
To use this statement, you must have the `DELETE` privilege for the table.
For details and examples, see [Remove Records from an Ocient System](/remove-records-from-an-ocient-system).
`DELETE` actions cannot be undone.
If a `DELETE` operation fails during execution, the database rolls back the changes and returns to its original state.
Due to limitations of the JDBC API, the reported modified row count might not be accurate for `DELETE` operations that are larger than two billion rows.
**Syntax**
```sql SQL theme={null}
DELETE FROM table_name [ WITH cte ] [ WHERE ]
```
| **Parameter** | **Type** | **Description** |
| ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `table_name` | string | The name of the table, specified as a string, indicates where to delete rows. |
| `cte` | string | A common table expression that defines temporary data for the `DELETE` statement. For details about using common table expressions, see [WITH](/data-query-language-dql-statement-reference#with). |
| `` | None | A logical combination of predicates that filter the rows to delete based on one or more columns. For details, see the [WHERE](/data-query-language-dql-statement-reference#where) clause. The `DELETE` SQL statement removes all rows from a table if you do not include the `WHERE` clause. |
**Examples**
**Delete Rows from the Table with Filter Criteria**
This `DELETE` SQL statement removes all rows in the `movies` table that have a budget of less than `10000`.
```sql SQL theme={null}
DELETE FROM movies WHERE budget < 10000;
```
**Delete Rows from the Table Using a Common Table Expression**
This example uses a common table expression using the `WITH` keyword to find rows representing all transactions that occurred before 2022 that are less than \$100. The `DELETE` SQL statement receives the results from the common table expression. Then, the database executes this statement to delete the corresponding rows.
```sql SQL theme={null}
DELETE FROM transactions
WITH old_transactions AS (
SELECT
transaction_id
FROM
transactions
WHERE transaction_date < '2022-01-01'
AND amount < 100
)
WHERE transaction_id IN (
SELECT transaction_id
FROM old_transactions );
```
## INSERT INTO TABLE
`INSERT INTO` inserts rows into a table in the current database using literal values, column references, function executions, computed expressions, or column default values.
This SQL statement requires the `INSERT` privilege for the relevant table.
Due to limitations of the JDBC API, the reported modified row count might not be accurate for insert operations that are larger than two billion rows.
**Syntax**
```sql SQL theme={null}
INSERT INTO table_name [ ( col1, col2 [, ...] ) ]
[ WITH cte ] { query | [ DEFAULT VALUES | VALUES [ ] }
::=
( row1_exp1, row1_exp2 [, ...] ),
( row2_exp1, row2_exp2 [, ...] )
[, ...]
```
Using `DEFAULT VALUES` inserts a single row where each target column is populated with its column defaults (as defined in the column definition) instead of an explicit `VALUES` list.
For table columns that do not each have a defined default value, the inserted row is NULL. If the column has no default and also has the `NOT NULL` constraint, the insert operation generates an error.
| **Parameter** | **Type** | **Description** |
| ------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `table_name` | string | The name of the table for insertion. |
| `col1, col2 [, ... ]` | string | A list of specific columns to insert specific values.
This column list defaults to all columns in the table if you do not specify any column names.
The `INSERT` statement can use a subset of the table columns. Any columns not included in the statement are populated with their column default value in their column definition. If the column definition does not specify a default, the inserted row is NULL. If the column has no default and also has the `NOT NULL` constraint, the insert operation generates an error. |
| `cte` | string | A common table expression that defines temporary data for the `INSERT` statement. For details about using common table expressions, see [WITH](/data-query-language-dql-statement-reference). |
| `query` | string | A `SELECT` query that defines values or a table and any of its columns that should be inserted into the specified `table_name`. |
| `row1_exp1, row1_exp2 [, ...]` | string | The expressions to insert into columns in the table. This list must match the number of columns specified in the INSERT statement. Similarly, each expression must match the data type of the column that corresponds to its position.
Expressions can be any of the following:
**Literals**: `1`, `3.14`, '`abc`', `DATE '2024-01-01'`, etc.
**Column references:** If your `INSERT` statement includes a common table expression using a `WITH` clause, you can reference columns from the separate table in that clause.
**Function executions**: `ABS(-5)`, `NOW()`, `ST_DISTANCE`, etc.
**Computed expressions**: `price * quantity`, `COALESCE(x, 0)`, etc.
**Column default values**: Use the keyword `DEFAULT` to insert a default value specified in the column definition. If the column definition does not specify a default, the inserted row is NULL. If the column has no default and also has the `NOT NULL` constraint, the insert operation generates an error. |
**Examples**
**Insert Values from One Column**
This example inserts the columns from `system.table_b` into `system.table_a`.
```sql SQL theme={null}
INSERT INTO system.table_a SELECT * FROM system.table_b;
```
**Insert Values from Multiple Columns**
This example inserts the column `system.table_b.id_col_b` into `system.table_a.id_col_a` and `system.table_b.int_col_b` into `system.table_a.int_col_a`.
```sql SQL theme={null}
INSERT INTO system.table_a (id_col_a, int_col_a)
SELECT id_col_b, int_col_b FROM system.table_b;
```
**Insert Literal Values**
Create a table with product, quantity, and date of sale information with these non-nullable columns:
* `product` — Product identifier
* `quantity` — Quantity of the product sold
* `sale_date` — Date of sale
```sql SQL theme={null}
CREATE TABLE sales (
product INT NOT NULL,
quantity INT NOT NULL,
sale_date DATE NOT NULL
);
```
Insert three rows of literal values that represent different sales.
```sql SQL theme={null}
INSERT INTO sales (product, quantity, sale_date)
VALUES
(1, 10, '2023-01-15'),
(2, 5, '2023-01-20'),
(1, 8, '2023-02-05');
```
**Insert Values Using a Common Table Expression**
In this example, a common table expression performs calculations on the `sales` table before inserting rows into the `monthly_sales_summary` table.
The example uses the `monthly_sales_summary` table created by this `CREATE TABLE` statement with these non-nullable columns:
* `product_id` — Product identifier
* `month` — Month part of the date
* `total_quantity` — Total quantity of the product
```sql SQL theme={null}
CREATE TABLE monthly_sales_summary (
"product_id" INT NOT NULL,
"month" DATE NOT NULL,
"total_quantity" INT NOT NULL
);
```
The common table expression following the `WITH` keyword extracts the month from the sale date `sale_date` and calculates the sum of the quantity sold `total_quantity` of the product from the `sales` table before inserting this data. Then, the `INSERT` SQL statement specifies to insert the data into the `monthly_sales_summary` table.
```sql SQL theme={null}
INSERT INTO monthly_sales_summary (product_id, month, total_quantity)
WITH monthly_totals AS (
SELECT
product,
DATE_TRUNC('month', sale_date) AS month,
SUM(quantity_sold) AS total_quantity
FROM
sales
GROUP BY
product,
DATE_TRUNC('month', sale_date)
)
SELECT
product,
month,
total_quantity
FROM
monthly_totals;
```
**Insert Columns Using Default Values**
This code utilizes the `customers` table with these columns:
* `customer_id` — Customer identifier
* `name` — Customer name
* `status` — Customer status with the default `active` status
* `created_at` — Created date
```sql SQL theme={null}
CREATE TABLE customers (
customer_id INT,
name VARCHAR(100),
status VARCHAR(20) DEFAULT 'ACTIVE',
created_at TIMESTAMP
);
```
Use the `DEFAULT VALUES` keyword to insert one row of default values into the table. For columns that lack a defined default value, the operation inserts a NULL row.
```sql SQL theme={null}
INSERT INTO customers DEFAULT VALUES;
```
The resulting row contains all NULL values except for the `status` column, which has the `active` default value.
```sql SQL theme={null}
SELECT * FROM customers;
```
Output
```sql SQL theme={null}
| customer_id | name | status | created_at |
| ----------- | ----- | ------ | ---------- |
| | | ACTIVE | |
```
Alternatively, you can insert default values by using the `DEFAULT` keyword as one of the row values in the `INSERT` statement.
```sql SQL theme={null}
INSERT INTO customers (customer_id, name, status, created_at)
VALUES (1, 'Alice', DEFAULT, NULL);
```
Output
```sql SQL theme={null}
| customer_id | name | status | created_at |
| ----------- | ----- | ------ | ---------- |
| | | ACTIVE | |
| 1 | Alice | ACTIVE | |
```
### INSERT INTO TABLE USING LOADERS
Specify one or more Loader Nodes for executing the `INSERT INTO` SQL statement. If you do not use this option, the Ocient System uses all Loader Nodes that are live to execute the SQL statement.
This statement is useful for managing loading operations, particularly when balancing multiple loads of different sizes and resource requirements. Alternatively, this statement can also help simplify small batch loads by sourcing the data from a single Loader Node.
**Syntax**
```sql SQL theme={null}
INSERT INTO TABLE table_name USING LOADERS streamloader [, ... ]
query
```
| **Parameter** | **Type** | **Description** |
| -------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `streamloader` | string | A unique name for the Loader Node. Identify the names of Loader Nodes from the `sys.nodes` table by using this query: `SELECT name FROM sys.nodes;` If the name of the streamloader contains special characters, you must enclose it in quotes, such as `"stream-loader1"`. |
For the query to execute successfully, the specified names must:
* Identify nodes that are live.
* Identify nodes that have the Loader role.
**Examples**
This example inserts the column `system.table_b.id_col_b` into `system.table_a.id_col_a` and `system.table_b.int_col_b` into `system.table_a.int_col_a`. Use the Loader Node named `stream-loader1` to execute this SQL statement.
```sql SQL theme={null}
INSERT INTO system.table_a (id_col_a, int_col_a)
USING LOADERS "stream-loader1"
SELECT id_col_b, int_col_b FROM system.table_b;
```
In this example, execute the same SQL statement with two Loader Nodes named `stream-loader2` and `stream-loader3`.
```sql SQL theme={null}
INSERT INTO system.table_a (id_col_a, int_col_a)
USING LOADERS "stream-loader2","stream-loader3"
SELECT id_col_b, int_col_b FROM system.table_b;
```
## TRUNCATE TABLE
`TRUNCATE TABLE` removes some or all records from an existing table in the current database. The system deletes the truncated data, but the table and its schema remain intact in the system even if all data is deleted. If the entire table is truncated, Global Dictionary Compression tables remain in place.
To truncate a table, you must have the `DELETE` privilege for the table.
To remove a subset of rows from a table, you can use the [DELETE FROM TABLE](#delete-from-table) SQL statement.
For details and examples of using `TRUNCATE`, see [Remove Records from an Ocient System](/remove-records-from-an-ocient-system).
This action cannot be undone and results in data loss.
**Syntax**
```sql SQL theme={null}
TRUNCATE TABLE table_name
TRUNCATE TABLE table_name WHERE segment_group_id =
TRUNCATE TABLE table_name WHERE segment_group_id in (, ...)
```
| **Parameter** | **Type** | **Description** |
| ------------------ | -------- | ---------------------------------- |
| `table_name` | string | The name of the table to truncate. |
| `segment_group_id` | numeric | Identifier of the segment group. |
**Examples**
This example truncates an existing table in the current database and schema named `students`.
```sql SQL theme={null}
TRUNCATE TABLE students;
```
This example truncates an existing table in the current database named `us.students`.
```sql SQL theme={null}
TRUNCATE TABLE us.students;
```
This example truncates a single segment group from an existing table in the current database named `students`.
```sql SQL theme={null}
TRUNCATE TABLE students WHERE segment_group_id = 123456789;
```
This example truncates a number of segment groups from an existing table in the current database named `us.students`.
```sql SQL theme={null}
TRUNCATE TABLE us.students WHERE segment_group_id IN (1,2,3,4,5);
```
## Related Links
[Data Query Language (DQL) Statement Reference](/data-query-language-dql-statement-reference)
[Data Definition Language (DDL) Statement Reference](/data-definition-language-ddl-statement-reference)
[Transactional Control Language (TCL) Statement Reference](/transaction-control-language-tcl-statement-reference)
[Commands Supported by the Ocient JDBC CLI Program](/commands-supported-by-the-ocient-jdbc-cli-program)
[Ocient Python Module (pyocient)](/ocient-python-module-pyocient)
# Data Pipeline Behavior Considerations
Source: https://docs.ocient.com/data-pipeline-behavior-considerations
Understand how Ocient data pipelines handle file resumption, Kafka offsets, exactly-once semantics, deduplication, and database and table dependencies.
Data pipelines enable you to load data from your chosen source into the . For details about the syntax, see [Data Pipelines](/data-pipelines). When you use data pipelines to load data, consider how to resume a pipeline with file loading, restart the pipeline with loading, and review pipeline dependencies.
### Resume a Pipeline with File Loading
In many cases, a file-based pipeline stops executing before completion. You cannot resume a pipeline in a `COMPLETED` status.
To resume a pipeline, use the `START PIPELINE` SQL statement. Before you resume a pipeline, the status of the pipeline must be `CREATED`, `FAILED`, or `STOPPED`. When a pipeline resumes, individual files remain in their most recent status as defined in the `sys.pipeline_files` system catalog table. For `BATCH` pipelines, the System does not add new files to the eligible file list when the pipeline resumes.
If you modify the contents of files during the loading process, the Ocient System might experience issues with deduplication that cause duplicated rows or missing data. Avoid modifying files after you start a pipeline for the first time.
Creating new files on your data source does not impact deduplication logic.
The `START` operation groups files using their `extractor_task_id` and `stream_source_id` identifiers. The `stream_source_id` uniquely identifies partitions (i.e., an ordered list of files), and `extractor_task_id` identifies the batch that loads a group of partitions.
#### File Statuses
The Ocient System considers files with the statuses `LOADED`, `LOADED_WITH_ERRORS`, or `SKIPPED` to be in the terminal status, whereas other file statuses are still in process.
* **Completed Batches** — If all the files in a particular batch have terminal status, then the pipeline does not attempt to reload the batch. These files have been completely processed, so the Ocient System ignores modifications to these files.
* **In-Process Batches** — If at least one file in a particular batch does not have terminal status, then the pipeline reloads the entire batch. The pipeline reprocesses the in-process batches and relies on row deduplication to prevent duplication of rows in the target tables.
* Modifications to files in an in-process batch can but are not guaranteed to be picked up by a restart.
* Modifications to any files in this batch with the `LOADED`, `LOADED_WITH_ERRORS`, or `SKIPPED` statuses might cause issues with deduplication, leading to duplicate or missed data.
* **Pending Files** — The Ocient System does not assign all `PENDING` files to a partition. The pipeline attempts to load these files after reloading any in-progress batches.
#### Load Duplicate Data from Files
Sometimes you might want to load the same data multiple times. If you want to load a second copy of the source data, you can either:
* Drop and recreate the pipeline to reset the `sys.pipeline_files` system catalog table.
* Create a second pipeline with a new name and the same configuration.
When you truncate the target tables and restart the pipeline, the Ocient System does not reload the data.
### Restart with Kafka Loading
Ocient relies on the offset management and consumer group behavior in Kafka to deliver exactly-once loading semantics and to control the Ocient pipeline behavior.
#### Kafka Offsets and Consumer Group Identifiers
If you set the `WRITE_OFFSETS` option to `true` (default value is `true`), the Kafka consumers commit offsets back to Kafka after data is considered durable in the database. The Kafka Broker stores these offsets as the last committed offset for the group identifier `group.id`.
For each pipeline, the group identifier defaults to `____`, where the `` is the identifier of your system, `` is the name of your database, and `` is the name of the data pipeline. In most use cases, you should not manually change the `group.id` field for a pipeline.
Any Kafka pipeline that has the same `group.id` starts consuming from its last committed offset, or if you do not set the value, the pipeline uses the Kafka `auto.offset.reset` policy to determine where to start. For details, see [Kafka offset management](https://docs.confluent.io/platform/current/clients/consumer.html#offset-management).
If you want to start loading from the beginning of a topic, configure an unused `group.id` field (or use a `group.id` field that did not commit any of its offsets back) and ensure the `auto.offset.reset` Kafka configuration is appropriately set in the `CONFIG` option.
#### Kafka Pipeline Deduplication
The committed offset of a Kafka partition lags slightly behind the rows that have been loaded into Ocient. These lags do not cause an issue with data duplication. If you stop a pipeline before it can commit its most recent durable offset to Kafka, restarting the same pipeline starts loading from the last committed offset. However, the database deduplicates records sent twice for the same pipeline.
Ocient deduplicates Kafka data for the specified combination of pipeline identifier, Kafka topic, and the Kafka partition number.
While the consumer group offsets manage where the pipeline resumes loading, the Ocient System enforces the exactly-once loading of a Kafka partition only if you stop or restart a pipeline with the same pipeline identifier.
If you drop a pipeline and create a new one with the same name, the Ocient System creates a new pipeline identifier. This action does not deduplicate data against data loaded in the original pipeline. To preserve deduplication, instead of dropping the pipeline, use the `CREATE OR REPLACE PIPELINE` SQL statement with the original pipeline name and the pipeline correctly deduplicates against the original data.
Do not run multiple pipelines concurrently with the same consumer group identifier. This action leads to unpredictable data duplication. If you want to increase the number of consumers that read from a Kafka topic, increase the value of the `CORES` parameter.
#### Load Duplicate Data on Kafka
Sometimes you might want to load the same data multiple times. If you want to load a second copy of the source data from Kafka, you can either:
* Drop the pipeline, recreate it with the same name, and reset the consumer group offsets manually.
* Create a new pipeline with a different name and load from the beginning of the topic.
### Pipeline Database Dependency
Each pipeline belongs to a database. You cannot drop a database that has a running pipeline. To drop a database, ensure that all pipelines in the database are in a non-running status.
### Pipeline Table Dependency
Each pipeline has a target table. You cannot drop a table that has a running pipeline. To drop a table, ensure that all pipelines that are loading data into the table are in a non-running status.
## Related Links
[Load Data](/load-data)
[Data Pipeline Load of CSV Data from S3](/data-pipeline-load-of-csv-data-from-s3)
[Data Pipeline Load of Parquet Data from S3](/data-pipeline-load-of-parquet-data-from-s3)
[Transform Data in Data Pipelines](/transform-data-in-data-pipelines)
[Load Metadata and File-Based Partitioned Data in Data Pipelines](/load-metadata-and-file-based-partitioned-data-in-data-pipelines)
[Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference)
[Identifiers](/identifiers)
# Data Pipeline Load of CSV Data from S3
Source: https://docs.ocient.com/data-pipeline-load-of-csv-data-from-s3
Load CSV data from AWS S3 into Ocient using a data pipeline. This tutorial covers database, table, and pipeline creation, execution, and monitoring.
A common setup for loading files in a batch into is to load from a bucket on S3 with time-partitioned data. Often, you must perform a batch load repeatedly to load new files.
Ocient uses data pipelines to transform each document into rows in one or more different tables. The loading and transformation capabilities use a simple SQL-like syntax for transforming data. This tutorial guides you through a simple example load using a small data set in CSV format. The data in this example comes from a test set for the Business Intelligence tool.
## Prerequisites
This tutorial assumes that:
1. The Ocient System has network access to S3 from the Loader Nodes.
2. An Ocient System is installed and configured with an active Storage Cluster (See the [Ocient Application Configuration](/ocient-application-configuration) guide).
## Step 1: Create a New Database
Connect to a SQL Node using the [Commands Supported by the Ocient JDBC CLI Program](/commands-supported-by-the-ocient-jdbc-cli-program). Then, execute the `CREATE DATABASE` SQL statement for a database named `metabase`.
```sql SQL theme={null}
CREATE DATABASE metabase;
```
## Step 2: Create Table
Create the `orders` table in the new database. First, connect to that database (e.g., `connect to jdbc:ocient://sql-node:4050/metabase`), and then execute this `CREATE TABLE` SQL statement that specifies to create a table with these columns and a clustering index based on the `user_id` and `product_id` columns:
* `created_at` as a timestamp that is not nullable.
* `id`, `user_id`, and `product_id` as integers that are not nullable.
* `subtotal`, `tax`, `total`, and `discount` as floating point numbers.
* `quantity` as an integer.
```sql SQL theme={null}
CREATE TABLE public.orders (
created_at TIMESTAMP TIME KEY BUCKET(30, DAY) NOT NULL,
id INT NOT NULL,
user_id INT NOT NULL,
product_id INT NOT NULL,
subtotal DOUBLE,
tax DOUBLE,
total DOUBLE,
discount DOUBLE,
quantity INT,
CLUSTERING INDEX idx01 (user_id, product_id)
);
```
The database creates the `orders` table, and you can begin loading data.
## Step 3: Create a Data Pipeline
Create data pipelines using the `CREATE PIPELINE` SQL statement. To load data, you first create a pipeline with the definition of the source, data format, and transformation rules using a SQL-like declarative syntax. Then, you execute the `START PIPELINE` SQL statement to start the load. You can observe progress and status using system tables and views.
Each Ocient pipeline defines a single data source and the target table or tables into which data loads. A data source includes the location of the source and filters on the source to define the specific data set to load. This example loads data from a data source located in a directory within the S3 bucket.
First, inspect the data that you plan to load. Each document has a format similar to this example CSV file named `orders.csv`.
```none Text theme={null}
id,user_id,product_id,subtotal,tax,total,discount,created_at,quantity
1,1,14,37.65,2.07,39.72,null,2019-02-11T21:40:27.892Z,2
2,1,123,110.93,6.1,117.03,null,2018-05-15T08:04:04.580Z,3
3,1,105,52.72,2.9,49.2,6.42,2019-12-06T22:22:48.544Z,2
...
```
In this case, Ocient automatically transforms the data to the target columns using some sensible conventions. In other cases, loads require some transformation. Most transformations are identical to functions that already exist in the SQL dialect of the Ocient System.
Create a pipeline named `orders_pipeline` for the orders data set from your database connection prompt. Use the S3 data source with endpoint `https://s3.us-east-1.amazonaws.com`, bucket `ocient-docs`, and filter `metabase_samples/csv/orders.csv`. Specify the CSV format with one header line. Load the data into the `public.orders` table. The `SELECT` part of the SQL statement maps the fields in the CSV file to the target columns in the created table.
```sql SQL theme={null}
CREATE PIPELINE orders_pipeline
SOURCE
S3
ENDPOINT 'https://s3.us-east-1.amazonaws.com'
BUCKET 'ocient-docs'
FILTER 'metabase_samples/csv/orders.csv'
EXTRACT
FORMAT csv
NUM_HEADER_LINES 1
INTO public.orders
SELECT
$1 as id,
$2 as user_id,
$3 as product_id,
$4 as subtotal,
$5 as tax,
$6 as total,
$7 as discount,
$8 as created_at,
$9 as quantity;
```
The pipeline has three main sections:
* `SOURCE` — In this case, load data from S3. Specify the endpoint and bucket. The `FILTER` parameter identifies the file or files to load. The load uses a single CSV file. Options exist to add wildcards or regular expressions to isolate different file sets.
* `EXTRACT` — Set the format to CSV files and note that there is one header line in the file. This specification skips that row when the Ocient System processes the file. Many other options exist for delimited data such as a record delimiter and field delimiter.
* `INTO ... SELECT` — Choose the target table `public.orders` and select the fields from the CSV file. The numeric index identifies each file field. Importantly, similar to other SQL syntax, the first field in the file is `$1`, not `$0`. Each field maps to a target column using the `as` syntax.
After you successfully create the `orders_pipeline` pipeline, execute the `START PIPELINE` SQL statement.
```sql SQL theme={null}
START PIPELINE orders_pipeline;
```
## Step 4: Observe the Load Progress
With your pipeline running, data immediately begins to load from the S3 files that you defined. If there are many files in each file group, the load process first sorts the files into batches, partitions them for parallel processing, and assigns them to Loader Nodes.
You can check the pipeline status and progress by querying `information_schema.pipeline_status` or by executing `SHOW PIPELINE_STATUS`
```sql SQL theme={null}
SHOW PIPELINE_STATUS;
```
*Output*
```sql SQL theme={null}
database_name pipeline_name table_names status status_message percent_complete duration_seconds files_processed files_failed files_remaining records_processed records_loaded records_failed
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
metabase orders_pipeline ["public.orders"] RUNNING Started processing pipeline orders_pipeline 0.0 2.025824 0 0 1 0 0 0
```
After the status of the pipeline changes to `COMPLETED`, all data is available in the target table.
After a few seconds, the data is available for query in the `public.orders` table.
```sql SQL theme={null}
SELECT COUNT(*) FROM public.orders;
```
*Output*
```sql SQL theme={null}
count(*)
--------------------
18760
```
You can drop the pipeline with the `DROP PIPELINE orders_pipeline;` SQL statement. Execution of this statement leaves the data in your target table, but removes metadata about the pipeline execution from the system.
## Related Links
[Data Pipelines Reference](/data-pipelines)
[Load Delimited and CSV Data](/data-formats-for-data-pipelines#load-delimited-and-csv-data)
[Data Types for Data Pipelines](/data-types-for-data-pipelines)
[Transform Data in Data Pipelines](/transform-data-in-data-pipelines)
[Manage Errors in Data Pipelines](/manage-errors-in-data-pipelines)
# Data Pipeline Load of JSON Data from HDFS
Source: https://docs.ocient.com/data-pipeline-load-of-json-data-from-hdfs
Load JSON data from HDFS into the Ocient System using a data pipeline. Preview the data load, execute the pipeline, and monitor its progress.
The data pipeline functionality enables the loading of data from . You can load various file types stored in HDFS into the System.
The Ocient System uses data pipelines to transform each document into rows in one or more different tables. The loading and transformation capabilities use a simple SQL-like syntax for transforming data. This tutorial guides you through a simple example of loading data in the JSON format.
## HDFS Advanced Source Options
Besides the specified options in the [HDFS Source Options](/data-pipelines#hdfs-source-options) section, you can also specify these options that are available for file system sources:
* COMPRESSION\_METHOD
* START\_FILENAME
* END\_FILENAME
* START\_CREATED\_TIMESTAMP
* END\_CREATED\_TIMESTAMP
* START\_MODIFIED\_TIMESTAMP
* END\_MODIFIED\_TIMESTAMP
* SORT\_BY
* SORT\_DIRECTION
* SORT\_REWRITE
For the `CONFIG` source option, the most useful properties are the ones with the `dfs.client` prefix. For the full property reference, see [HDFS Default](https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml) and [Core Default](https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/core-default.html). Only properties that affect client connections and read operations apply to data pipeline loading. This table describes some common properties.
| **Property Name** | **Property Description** |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dfs.client.use.datanode.hostname` | Set this property to `true` when you have datanodes and namenodes in the HDFS cluster configured to connect to each other using local IP addresses, but loading occurs externally and requires externally valid hostnames instead. The default value is `false`. |
| `dfs.client.retry.max.attempts` | Configure to change the number of times the loading process retries network requests to namenodes before throwing an error. You can increase this value when network connections are unstable. The default value is 10. |
| `dfs.client.socket-timeout` | Configure to change the timeout (in milliseconds) for all sockets used internally in HDFS loading. You can increase this value when network connections are unstable. The default value is 60000 (60 seconds). |
## HDFS Loading Example
Follow these steps to load JSON data from an HDFS source into the Ocient System.
### Step 1: Create a New Database
Connect to a SQL Node using the [Commands Supported by the Ocient JDBC CLI Program](/commands-supported-by-the-ocient-jdbc-cli-program). Then, execute the `CREATE DATABASE` SQL statement to create the `geo` database.
```sql SQL theme={null}
CREATE DATABASE geo;
```
### Step 2: Create a New Table in the Database
Create the `locations` table in the `public` schema to store location data with a name, zip code, and a point with latitude and longitude:
* `name` — Location name as a not nullable string
* `zipcode` — Zip code as an integer
* `location` — Location latitude and longitude as a point
```sql SQL theme={null}
CREATE TABLE public.locations (
name VARCHAR(255) NOT NULL,
zipcode INT NOT NULL,
location POINT
);
```
### Step 3: Preview and Create a Data Pipeline
Preview the `locations` data pipeline to load JSON data from HDFS. This data pipeline uses the HDFS endpoint `hdfs-namenode:9000`, which consists of the namenode and port number, and the `/locations/2026/**/*.json` filter to load data from JSON files. The pipeline selects the name, zip code, and point data. For the point data construction, see [ST\_POINT](/point-constructors#st_point).
```sql SQL theme={null}
PREVIEW PIPELINE locations
SOURCE hdfs
ENDPOINT 'hdfs-namenode:9000'
FILTER '/locations/2026/**/*.json'
EXTRACT
FORMAT json
INTO locations
SELECT
$name AS name,
$zipcode AS zipcode,
ST_POINT($longitude, $latitude) AS location;
```
Create the `locations` data pipeline to load JSON data from HDFS.
```sql SQL theme={null}
CREATE PIPELINE locations
SOURCE hdfs
ENDPOINT 'hdfs-namenode:9000'
FILTER '/locations/2026/**/*.json'
EXTRACT
FORMAT json
INTO locations
SELECT
$name AS name,
$zipcode AS zipcode,
ST_POINT($longitude, $latitude) AS location;
```
After you successfully create the `locations` pipeline, execute the `START PIPELINE` SQL statement to start the data pipeline.
```sql SQL theme={null}
START PIPELINE orders_pipeline;
```
### Step 4: Observe the Load Progress
With your pipeline running, data begins to load immediately from the JSON files. If there are many files in each file group, the load process first sorts the files into batches, partitions them for parallel processing, and assigns them to Loader Nodes.
You can check the pipeline status and progress by querying the `information_schema.pipeline_status` system catalog table or executing the `SHOW PIPELINE_STATUS` SQL statement.
```sql SQL theme={null}
SHOW PIPELINE_STATUS;
```
Output
```sql SQL theme={null}
database_name pipeline_name table_names status status_message percent_complete duration_seconds files_processed files_failed files_remaining records_processed records_loaded records_failed
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
geo locations ["public.locations"] RUNNING Started processing pipeline locations 0.0 2.025824 0 0 1 0 0 0
```
After the status of the pipeline changes to `COMPLETED`, all data is available in the target table.
After a few seconds, the data is available for query in the `public.locations`table.
```sql SQL theme={null}
SELECT COUNT(*) FROM public.locations;
```
*Output*
```sql SQL theme={null}
count(*)
--------------------
25605
```
You can drop the pipeline with the `DROP PIPELINE locations;` SQL statement. Execution of this statement leaves the data in your target table, but removes metadata about the pipeline execution from the system.
## Related Links
[Data Pipelines Reference](/data-pipelines)
[Load JSON Data](/data-formats-for-data-pipelines#load-json-data)
[Data Types for Data Pipelines](/data-types-for-data-pipelines)
[Transform Data in Data Pipelines](/transform-data-in-data-pipelines)
[Manage Errors in Data Pipelines](/manage-errors-in-data-pipelines)
# Data Pipeline Load of JSON Data from Kafka
Source: https://docs.ocient.com/data-pipeline-load-of-json-data-from-kafka
Stream JSON data from Kafka topics into Ocient with data pipelines. Set up the database, table, pipeline, and SQL transformations for real-time analytics.
A common setup for streaming data into is to load JSON data from an topic.
Ocient uses data pipelines to transform each document into rows in one or more different tables. The loading and transformation capabilities use a simple SQL-like syntax for transforming data. This tutorial guides you through a simple example load using a small data set in JSON format. The data in this example comes from a test set for the Business Intelligence tool.
## Prerequisites
This tutorial assumes that:
1. The Ocient System has network access to a Kafka broker from the SQL and Loader Nodes.
2. An Ocient System is installed and configured with an active Storage Cluster (see the [Ocient Application Configuration](/ocient-application-configuration) guide).
## Step 1: Create a New Database
Connect to a SQL Node using the [Commands Supported by the Ocient JDBC CLI Program](/commands-supported-by-the-ocient-jdbc-cli-program). Then, execute the `CREATE DATABASE` SQL statement to create the `metabase` database.
```sql SQL theme={null}
CREATE DATABASE metabase;
```
## Step 2: Create Table
Create the `orders` table in the new database. First, connect to that database (e.g., `connect to jdbc:ocient://sql-node:4050/metabase`), and then execute this `CREATE TABLE` SQL statement that specifies to create a table with these columns and a clustering index based on the `user_id` and `product_id` columns:
* `created_at` as a timestamp that is not nullable.
* `id`, `user_id`, and `product_id` as integers that are not nullable.
* `subtotal`, `tax`, `total`, and `discount` as floating point numbers.
* `quantity` as an integer.
```sql SQL theme={null}
CREATE TABLE public.orders (
created_at TIMESTAMP TIME KEY BUCKET(30, DAY) NOT NULL,
id INT NOT NULL,
user_id INT NOT NULL,
product_id INT NOT NULL,
subtotal DOUBLE,
tax DOUBLE,
total DOUBLE,
discount DOUBLE,
quantity INT,
CLUSTERING INDEX idx01 (user_id, product_id)
);
```
The database creates the `orders` table, and you can begin loading data.
## Step 3: Create a Data Pipeline
Create data pipelines using the `CREATE PIPELINE` SQL statement. To load data, you first create a pipeline with the definition of the source, data format, and transformation rules using a SQL-like declarative syntax. Then, you execute the `START PIPELINE` command to start the load. You can observe progress and status using system tables and views.
Each Ocient pipeline defines a single data source and the target table or tables into which data loads. A data source includes the location of the source and filters on the source to define the specific data set to load. This example loads data from two data sources, where each source is located in a directory on the same S3 bucket.
First, inspect the data that you plan to load. Each document has a format similar to this example.
```json JSON theme={null}
{"id": 1, "user_id": 1, "product_id": 14, "subtotal": 37.65, "tax": 2.07, "total": 39.72, "discount": null, "created_at": "2019-02-11T21:40:27.892Z", "quantity": 2}
{"id": 2, "user_id": 1, "product_id": 123, "subtotal": 110.93, "tax": 6.1, "total": 117.03, "discount": null, "created_at": "2018-05-15T08:04:04.580Z", "quantity": 3}
```
In this case, Ocient automatically transforms the data to the target columns using some sensible conventions. In other cases, loads require some transformation. Most transformations are identical to functions that already exist in the SQL dialect of the Ocient System.
Create a pipeline named `orders_pipeline` for the orders data set from your database connection prompt. Specify the Kafka source with broker address `192.168.0.1:9092` (replace this example Kafka broker address with your address) and topic `orders`. Load the data into the `public.orders` table. The `SELECT` part of the SQL statement maps the JSON fields to the target columns in the created table.
```sql SQL theme={null}
CREATE PIPELINE orders_pipeline
SOURCE
KAFKA
BOOTSTRAP_SERVERS '192.168.0.1:9092'
TOPIC 'orders'
EXTRACT
FORMAT json
INTO public.orders
SELECT
$id as id,
$user_id as user_id,
$product_id as product_id,
$subtotal as subtotal,
$tax as tax,
$total as total,
$discount as discount,
$created_at as created_at,
$quantity as quantity;
```
The pipeline has three main sections:
* `SOURCE` — Loads data from Kafka. Specify the address of the bootstrap servers and topic. Options exist to set Kafka consumer configurations.
* `EXTRACT` — Sets the format to JSON.
* `INTO ... SELECT` — Targets the `public.orders` table and selects the chosen fields from the JSON records. In this case, all data is available at the top level of the JSON records, so the example references the fields by the attribute name (e.g., `$id`, `$user_id`, etc.). For nested data, reference the nested fields using dot notation (e.g., `$order.user.first_name`). Each field maps to a target column using the `as` syntax.
After you successfully create this pipeline, execute the `START PIPELINE` SQL statement.
```sql SQL theme={null}
START PIPELINE orders_pipeline;
```
## Step 4: Confirm that Loading is Operating Correctly
With the pipeline in place and running, data immediately begins loading off of the Kafka topics that are configured in the pipeline. If you do not have data in the Kafka topics yet, now is a good time to start producing data into the topics.
### Produce Test Data into Kafka
For test purposes, [kafkacat](https://github.com/edenhill/kcat) is a helpful utility that makes it easy to produce records into a topic. For example, if you have a file of sample data `orders.jsonl` in a JSONL format (newline-delimited JSON records), you can run this command to send those records into your Kafka broker. Specify your broker IP address instead of `` and your topic name ``.
```shell Shell theme={null}
kafkacat -b :9092 -t -T -P -l orders.jsonl
```
Save an example document to your file system to use for this test. For this example, you can download an example file from [https://ocient-docs.s3.amazonaws.com/metabase\_samples/jsonl/orders.jsonl](https://ocient-docs.s3.amazonaws.com/metabase_samples/jsonl/orders.jsonl) and save it to `~/orders.jsonl`.
Assuming the broker is running at the IP address `10.0.0.3`, send data into the `orders` topic defined in the pipeline definition by executing this command.
```shell Shell theme={null}
kafkacat -b 10.0.0.3:9092 -t orders -T -P -l orders.jsonl
```
This command pushes the entire JSONL file of messages into Kafka with one record per line. As these records are produced into Kafka, the running pipeline begins to load them into Ocient.
## Step 5: Observe the Load Progress
With your pipeline running, data immediately begins to load from the Kafka topic. The pipeline creates parallel Kafka consumers for each partition. If there are more partitions than processing cores available, the pipeline automatically handles spreading consumers across available processing cores and Loader Nodes.
You can check the pipeline status and progress by querying `information_schema.pipeline_status` or executing the `SHOW PIPELINE_STATUS` SQL statement.
```sql SQL theme={null}
SHOW PIPELINE_STATUS;
```
*Output*
```sql SQL theme={null}
database_name pipeline_name table_names status status_message percent_complete duration_seconds files_processed files_failed files_remaining records_processed records_loaded records_failed
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
metabase orders_pipeline ["public.orders"] RUNNING Started processing pipeline orders_pipeline 0.0 2.025824 0 0 1 0 0 0
```
After a few seconds, the data is available for query in `public.orders`.
```sql SQL theme={null}
SELECT COUNT(*) FROM public.orders;
```
*Output*
```sql SQL theme={null}
count(*)
--------------------
18760
```
Unlike a batch file load, Kafka pipelines run continuously, so they never change to a status of `COMPLETED`. To examine progress, you can use the information schema and system catalog tables. Key details are in `information_schema.pipelines`, `information_schema.pipeline_status`, and `sys.pipeline_partitions`.
For example, this statement shows the status and key metrics for duration, loaded records, and failed records.
```sql SQL theme={null}
SELECT
pipeline_name,
status,
status_message,
duration_seconds,
records_loaded,
records_failed
FROM
information_schema.pipeline_status;
```
*Output*
```sql SQL theme={null}
pipeline_name status status_message duration_seconds records_loaded records_failed
--------------------------------------------------------------------------------------------------------------------------------
orders_pipeline RUNNING Started processing pipeline orders_pipeline 10.089936 18760 0
```
In this example, there are no errors. The `sys.pipeline_errors` system catalog table captures any errors that occur during the pipeline process.
You can drop the pipeline with the `DROP PIPELINE orders_pipeline;` SQL statement. Execution of this statement leaves the data in your target table, but removes metadata about the pipeline execution from the system.
## Related Links
[Data Pipelines Reference](/data-pipelines)
[Load JSON Data](/data-formats-for-data-pipelines#load-json-data)
[Data Types for Data Pipelines](/data-types-for-data-pipelines)
[Transform Data in Data Pipelines](/transform-data-in-data-pipelines)
[Manage Errors in Data Pipelines](/manage-errors-in-data-pipelines)
# Data Pipeline Load of Parquet Data from S3
Source: https://docs.ocient.com/data-pipeline-load-of-parquet-data-from-s3
Load time-partitioned Parquet files from AWS S3 into Ocient tables with data pipelines and SQL transformations. Includes setup, execution, and monitoring.
A common setup for loading files in a batch into the System is to load from a bucket on S3 with time-partitioned data. Often, you must perform a batch load repeatedly to load new files.
The Ocient System uses data pipelines to transform each document into rows in one or more different tables. The loading and transformation capabilities use a simple SQL-like syntax for transforming data. This tutorial guides you through a simple example load using a small data set in format. The data in this example comes from a test set for the Business Intelligence tool.
## Parquet Loading Recommendations
Follow this set of recommendations for an optimal loading experience of Parquet files.
**File Configuration**
* Files should have row groups of less than 128 MB. Larger row groups can impact memory usage during loading, and row groups of 512 MB can cause loading failures on 1 TB or more data sets.
* Encoding fields in a Parquet file reduces the space of the file on disk but can impact memory usage during loading. Enable encoding on fields that you expect to have less than 256 unique values and for fields that contain short strings. You do not have to encode other fields.
**Multiple Files**
* You can load row groups of multiple Parquet files in parallel. For large data sets, load the data set as multiple files.
* Loading files with differing schemas is not supported.
## Prerequisites
This tutorial assumes that:
1. The Ocient System has network access to S3 from the Loader Nodes.
2. An Ocient System is installed and configured with an active Storage Cluster. For details, see [Ocient Application Configuration](/ocient-application-configuration).
## Parquet Loading Example
Follow these steps to load Parquet data into the Ocient System.
### Step 1: Create a New Database
Connect to a SQL Node using the [Commands Supported by the Ocient JDBC CLI Program](/commands-supported-by-the-ocient-jdbc-cli-program). Then, execute the `CREATE DATABASE` SQL statement to create the `metabase` database.
```sql SQL theme={null}
CREATE DATABASE metabase;
```
### Step 2: Create a New Table in the Database
Create the `orders` table in the new database. First, connect to that database (e.g., `connect to jdbc:ocient://sql-node:4050/metabase`), and then execute this `CREATE TABLE` SQL statement that specifies to create a table with these columns and a clustering index based on the `user_id` and `product_id` columns:
* `created_at` as a timestamp that is not nullable.
* `id`, `user_id`, and `product_id` as integers that are not nullable.
* `subtotal`, `tax`, `total`, and `discount` as floating point numbers.
* `quantity` as an integer.
```sql SQL theme={null}
CREATE TABLE public.orders (
created_at TIMESTAMP TIME KEY BUCKET(30, DAY) NOT NULL,
id INT NOT NULL,
user_id INT NOT NULL,
product_id INT NOT NULL,
subtotal DOUBLE,
tax DOUBLE,
total DOUBLE,
discount DOUBLE,
quantity INT,
CLUSTERING INDEX idx01 (user_id, product_id)
);
```
The database creates the `orders` table, and you can begin loading data.
### Step 3: Preview and Create a Data Pipeline
Create data pipelines using the `CREATE PIPELINE` SQL statement. To load data, you first create a pipeline with the definition of the source, data format, and transformation rules using a SQL-like declarative syntax. Then, you execute the `START PIPELINE` SQL statement to start the load. You can observe progress and status using system catalog tables and views.
Each Ocient pipeline defines a single data source and the target table or tables into which data loads. A data source includes the location of the source and filters on the source to define the specific data set to load. This tutorial loads data from two data sources, where each source is located in a directory on the same S3 bucket.
First, inspect the data that you plan to load. Each document has a JSON format similar to this example.
```json JSON theme={null}
{"id": 1, "user_id": 1, "product_id": 14, "subtotal": 37.65, "tax": 2.07, "total": 39.72, "discount": null, "created_at": "2019-02-11T21:40:27.892Z", "quantity": 2}
{"id": 2, "user_id": 1, "product_id": 123, "subtotal": 110.93, "tax": 6.1, "total": 117.03, "discount": null, "created_at": "2018-05-15T08:04:04.580Z", "quantity": 3}
```
Inspecting the file with Pandas, you can see this schema with details.
```none Parquet Schema Description theme={null}
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 18760 non-null int64
1 user_id 18760 non-null int64
2 product_id 18760 non-null int64
3 subtotal 18760 non-null float64
4 tax 18760 non-null float64
5 total 18760 non-null float64
6 discount 1915 non-null float64
7 created_at 18760 non-null datetime64[ns, UTC]
8 quantity 18760 non-null int64
```
In this case, Ocient automatically transforms the data to the target columns using some sensible conventions. In other cases, loads require some transformation. Most transformations are identical to functions that already exist in the SQL syntax of the Ocient System.
Prior to creating a pipeline, you can use the `PREVIEW PIPELINE` SQL statement to create your pipeline iteratively. This statement returns a result set that shows the final values that would be loaded but does not load the data into the target table.
Preview the `orders_pipeline` pipeline for the `orders` data set from your database connection prompt. Use the S3 data source with endpoint `https://s3.us-east-1.amazonaws.com`, bucket `ocient-docs`, and filter `metabase_samples/parquet/orders.parquet`. Specify the `parquet` format. Load the data into the `public.orders` table. The `SELECT` part of the SQL statement maps the fields in the Parquet file to the target columns in the created table. In this example, limit the result set to the first five records in the data source.
```sql SQL theme={null}
PREVIEW PIPELINE orders_pipeline
SOURCE
S3
ENDPOINT 'https://s3.us-east-1.amazonaws.com'
BUCKET 'ocient-docs'
FILTER 'metabase_samples/parquet/orders.parquet'
LIMIT 5
EXTRACT
FORMAT parquet
INTO public.orders
SELECT
$id as id,
$user_id as user_id,
$product_id as product_id,
$subtotal as subtotal,
$tax as tax,
$total as total,
$discount as discount,
$created_at as created_at,
$quantity as quantity;
```
*Output*
```sql SQL theme={null}
id user_id product_id subtotal tax total discount created_at quantity
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
1 1 14 37.65 2.07 39.72 NULL 2019-02-11 21:40:27.892000000 2
8 1 123 110.93 6.1 117.03 NULL 2018-05-15 08:04:04.580000000 3
8 1 105 52.72 2.9 49.2 6.42 2019-12-06 22:22:48.544000000 2
8 1 94 109.22 6.01 115.23 NULL 2019-08-22 16:30:42.392000000 6
8 1 132 127.88 7.03 134.91 NULL 2018-10-10 03:34:47.309000000 5
Fetched 5 rows
```
With this preview, you can confirm that the results of the pipeline match your requirements. If there is an issue, you can update the statement and run the `PREVIEW PIPELINE` statement again until it meets your needs.
Next, create the pipeline named `orders_pipeline` for the `orders` data set from your database connection prompt. The pipeline has three main sections:
* `SOURCE` — Loads data from S3. Set the S3 endpoint, bucket name, and filter for the Parquet files.
* `EXTRACT` — Sets the format to Parquet.
* `INTO ... SELECT` — Targets the `public.orders` table and selects the chosen fields from the Parquet records. In this case, all data is available at the top level of the Parquet records, so the example references the fields by the attribute name (e.g., `$id`, `$user_id`, etc.). For nested data, reference the nested fields using dot notation (e.g., `$order.user.first_name`). Each field maps to a target column using the `as` syntax.
```sql SQL theme={null}
CREATE PIPELINE orders_pipeline
SOURCE
S3
ENDPOINT 'https://s3.us-east-1.amazonaws.com'
BUCKET 'ocient-docs'
FILTER 'metabase_samples/parquet/orders.parquet'
EXTRACT
FORMAT parquet
INTO public.orders
SELECT
$id as id,
$user_id as user_id,
$product_id as product_id,
$subtotal as subtotal,
$tax as tax,
$total as total,
$discount as discount,
$created_at as created_at,
$quantity as quantity;
```
After you successfully create this pipeline, execute the `START PIPELINE` SQL statement to start the load.
```sql SQL theme={null}
START PIPELINE orders_pipeline;
```
### Step 4: Observe the Load Progress
With your pipeline running, data begins to load immediately from the S3 files that you defined. If there are many files in each file group, the load process first sorts the files into batches, partitions them for parallel processing, and assigns them to Loader Nodes.
You can check the pipeline status and progress by querying the `information_schema.pipeline_status` system catalog table or executing the `SHOW PIPELINE_STATUS` SQL statement.
```sql SQL theme={null}
SHOW PIPELINE_STATUS;
```
*Output*
```sql SQL theme={null}
database_name pipeline_name table_names status status_message percent_complete duration_seconds files_processed files_failed files_remaining records_processed records_loaded records_failed
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
metabase orders_pipeline ["public.orders"] RUNNING Started processing pipeline orders_pipeline 0.0 2.025824 0 0 1 0 0 0
```
After the status of the pipeline changes to `COMPLETED`, all data is available in the target table.
After a few seconds, the data is available for query in the `public.orders` table.
```sql SQL theme={null}
SELECT COUNT(*) FROM public.orders;
```
*Output*
```sql SQL theme={null}
count(*)
--------------------
18760
```
You can drop the pipeline with the `DROP PIPELINE orders_pipeline;` SQL statement. Execution of this statement leaves the data in your target table, but removes metadata about the pipeline execution from the system.
## Related Links
[Data Pipelines Reference](/data-pipelines)
[Load JSON Data](/data-formats-for-data-pipelines#load-json-data)
[Data Types for Data Pipelines](/data-types-for-data-pipelines)
[Transform Data in Data Pipelines](/transform-data-in-data-pipelines)
[Manage Errors in Data Pipelines](/manage-errors-in-data-pipelines)
# Data Pipeline Loading Errors
Source: https://docs.ocient.com/data-pipeline-loading-errors
Reference of Ocient data pipeline error codes and messages, with parameter descriptions and recommended actions for resolving load and parsing failures.
This table captures error codes and their corresponding error messages that you can encounter when you load data using data pipelines in the System. Also, the table contains the definitions of the parameters in the error messages, descriptions that explain the error messages, and actions you can take to resolve the errors.
| **Code** | **Error Message** | **Message Parameters** | **Description** | **Resolution** |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OLD00 | Key `key` for class `class` must be set to a non-NULL value. Details: `details` | `key`: The key of the missing property. `class`: The class that has the missing property. `details`: Additional information about the error. | This error occurs when the loading process reads the pipeline definition missing a required property. | Specify a non-NULL value for the specified key in the pipeline definition. |
| OLD01 | Value `value` is not acceptable with the key `key` for class `class`. Expected `example`. Details: `details` | `value`: The value that you set for the specified pipeline definition key. `key`: The pipeline definition key with an incorrect value. `class`: The class that contains the property. `example`: An example or description of the correct value. `details`: Additional information about the error. | This error occurs when the loading process reads the pipeline definition that contains a key with an incorrect value. | Specify the correct value for the setting corresponding to the specified key in the pipeline definition. |
| OLD02 | No class with name `class` exists in the pipeline builder packages. Pipeline cannot run. | `class`: The class that cannot be found. | This error occurs when the loading process reads the pipeline definition that contains an unknown class. | Ensure that the class exists and belongs to a package specified in the `'engine.builder.packages'` configuration option. |
| OLE00 | Failed to extract record with index `index` from `sourceName`. Details: `details` | `index`: The index of the record (index starts at 1) in the source where the error occurred. `sourceName`: The name of the source resource where the error occurred. `details`: Additional information about the error. | This error occurs when the extraction of a record fails. | Provide the correct source data in the accurate format, extract configuration, or compression method. |
| OLE01 | `dataExtract` cannot be extracted from `sourceData`. Details: `details` | `dataExtract`: The data to extract. `sourceData`: The source data for the extraction. `details`: Additional information about the error | This error occurs when the extraction of data from a record fails. | Provide the correct source data in the accurate format, extract configuration, compression method, or transform configuration. |
| OLE02 | The source data has encountered invalid data or character sets. If invalid data is expected in the load, turn off the VALIDATE\_CHARACTERS option or use the REPLACE\_INVALID\_CHARACTERS option instead. | None | This error occurs when the pipeline has the VALIDATE\_CHARACTERS option turned on and the load encounters invalid data. | If you want to skip files that contain invalid data, turn on the TOLERATE file error mode. If you expect invalid data in the load, turn off the VALIDATE\_CHARACTERS option. You can replace invalid data with the REPLACE\_INVALID\_CHARACTERS option. |
| OLM00 | The `message` is too large. `modification` | `message`: The type of message that is too large.
`modification`: An example or description of a modification to limit the payload size of the message. | This error occurs when an internal communication fails because the message size exceeds the maximum size set by the system. | Modify the corresponding command to limit the payload size of the message. |
| OLO00 | Failed to connect to `sourceType` source because the specified `locationType` `location` was not found. Details: `details` | `sourceType`: The type of the source. `locationType`: The type of the data location argument that was not found. `location`: The value of the data location argument that was not found. `details`: Additional information about the error. | This error occurs when the pipeline cannot find the source data (e.g., cannot find the configured bucket or file path). | In the pipeline definition, specify an existing data location in the source. |
| OLO01 | Failed to connect to `sourceType` source because the access credentials are unauthorized. Details: `details` | `sourceType`: The type of source where access is denied. `details`: Additional information about the error. | This error occurs when the pipeline cannot connect to the source due to invalid credentials. | Specify credentials in the pipeline definition with access to the specified source or configure the source to provide access to the pipeline. |
| OLO10 | File list is empty at the `sourceType` source provided. The locations searched are: `location`. Details: `details` | `sourceType`: The type of the source. `location`: The value of the data location argument that was not found. | This error occurs when the pipeline cannot find the source data (e.g., the file path is empty). | If an empty file list was expected, set the `expect.empty.file.list` configuration option to `true` by executing `ALTER SYSTEM ALTER CONFIG SET 'streamloader.extractorEngineParameters.configurationOption.expect.empty.file.list' = 'true';`. Then, restart the pipeline. |
| OLO50 | File `fileName` was not found. | `fileName`: The name of the missing file. | This error occurs when the pipeline is configured to fail on missing files, and it cannot find a file in the list. | Handle the missing file using your own process or configure the pipeline to skip missing files instead. |
| OLS00 | Failed to load transformed value `value` to sink after `transformName`. Details: `details` | `value`: The value that the Loader Node could not load to the sink. `transformName`: The name of the executed transform. `details`: Additional information about the error. | This error occurs when the Loader Node cannot load a transformed value to the sink. For example, the transformed value might be too large for the sink column. | Check that the sink column is configured correctly or check that the transforms in the column are composed properly to return values that can load to the sink. |
| OLS97 | No table with name `tableName` exists in sink at `ipAddress`:`port`. The available tables are: `existingTables`. | `tableName`: The fully specified name of the specified table. `ipAddress`: The IP address for the Loader Node of the Ocient sink. `port`: The external TCP port for the Loader Node of the Ocient sink. `existingTables`: The list of existing tables in the same database and schema as the specified table. | This error occurs when no table with the specified name exists in the sink, but the database and schema of the table do exist. | Specify an existing table in the pipeline definition or create a table with the specified name. |
| OLS98 | The column name `columnName` does not exist. The columns available to the pipeline from the `tableName` table are: `existingColumns`. | `columnName`: The name of the column that was not found. `tableName`: The table that was searched. `existingColumns`: The columns in the table that are available to the pipeline. | This error occurs when the target table in the sink does not contain all the columns specified in the pipeline or a column specified as a transform target is not declared in the sink definition of the pipeline. (The database ignores deleted columns. This error does not occur when you load data to a deleted column.) | Specify an existing column in the pipeline definition or add the corresponding column to the target table. |
| OLS99 | Failed to connect to sink at `ipAddress`:`port`. Check that a streamloader at that address is reachable. | `ipAddress`: The IP address for the Loader Node of the Ocient sink. `port`: The external TCP port for the Loader Node of the Ocient sink. | This error occurs when the pipeline cannot connect to its Ocient sink using a Loader Node. | Check that the Loader Node at the specified host and port is reachable and that the host and port of the Ocient sink are configured properly. |
| OLT00 | Cannot perform operation `operationName` because the inputs are `inputType`. Expected inputs are `expectedType`. | `operationName`: The name of the operation that cannot be performed because its inputs are the wrong type. (usually the name of a transform) `inputType`: The type of inputs that the operation received. `expectedType`: The type of inputs that the operation expects to receive. | This error occurs when transforms in a column are not composed correctly. | Add, remove, or replace transforms such that each transform receives input of the correct type and that the Loader Node loads data of the correct type into the target column. |
| OLT01 | Failed to transform value `value` using `transformName`. Details: `details` | `value`: The value that was not transformed. `transformName`: The name of the failed transform. `details`: Additional information about the error. | This error occurs when a transformation fails. | Correct the source data or modify the transform to fit the source data. Alternatively, start the pipeline with a higher error limit so the load skips the failing record. |
| OLT02 | Value `value` is not an acceptable `parameterName` for `transformName`. Expected `example`. | `value`: The incorrect value for the specified parameter. `parameterName`: The name of the specified parameter. `transformName`: The name of the transform that is not configured correctly. `example`: An example or description of the correct value. | This error occurs when the parameter of the transform is not configured correctly. | Correct the parameter of the transform. |
| OLT03 | Failed to transform value `value` using `transformName` because the value is `valueDescription`. Expected `example`. | `value`: The value that was not transformed. `transformName`: The name of the failed transform. `valueDescription`: A feature or description of the incorrect value for this transform. `example`: An example or description of the correct value. | This error occurs when a transformation fails because the data is not correct for the transform. | Correct the source data, modify the transform configuration, or use a different transform. |
| OLT04 | Failed to match value `value` to format `format` in `transformName` because `valuePart` at position `valuePartPosition` does not match pattern `pattern`. Expected `example`. | `value`: The value that was not parsed with the transform format. `format`: The transform format. `transformName`: The name of the failed transform. `valuePart`: The part of the value that was unmatched. `valuePartPosition`: The position (index starts at 1) of the part unmatched in the value. `pattern`: The pattern in the transform format that did not match part of the value. `example`: An example or description of the correct value. | This error occurs when a transformation fails because the value does not match the specified transform format. | Correct the source data or modify the transform format to fit the source data. |
| OLTM0 | Failed to transform `value` value using `transformName`. `details`. | `value`: The value that was not transformed. `transformName`: The name of the failed transform. `details`: Additional information about the error. | This error occurs when an EXPLODE transformation fails. | Correct the source data or modify the transform to fit the source data. Alternatively, start the pipeline with a higher error limit so the load skips the failing record. |
| OL998 | An error occurred in library `library`: `details` | `library`: The name of the library where the error occurred. `details`: Additional information about the error. | This error occurs when the Ocient System detects an error from an internal library. | Diagnose and address the error using the details provided by the library. |
| OL999 | An error occurred in class `class`: `details` | `class`: The class that threw the exception. `details`: Additional information about the error. | This error occurs when the Ocient System detects a general error. | If the details of the message are not helpful for you to resolve the error, then contact Ocient Support. |
## Related Links
[Errors and Warnings](/errors-and-warnings)
[Monitor Data Pipelines](/monitor-data-pipelines)
# Data Pipelines
Source: https://docs.ocient.com/data-pipelines
Overview of Ocient data pipelines, the SQL-based ETL framework with CREATE PIPELINE DDL commands for ingesting and transforming streaming and batch data.
Data pipelines enable you to load data from your chosen source into the . You can preview a data pipeline using the `PREVIEW PIPELINE` SQL statement to test the creation statement and any required data transformation. Then, you can create a data pipeline using the `CREATE PIPELINE` statement. To manage the load, use the `START PIPELINE` statement to start the load and the `STOP PIPELINE` statement to stop it. You can evolve the schema of a data pipeline using the `ALTER PIPELINE` statement. You can also rename a data pipeline using the `ALTER PIPELINE RENAME` statement. To see the full definition of a created pipeline, use the `EXPORT PIPELINE` statement. When you finish with the load, you can use the `DROP PIPELINE` statement to remove the data pipeline. You can create user-defined data pipeline functions using the `CREATE PIPELINE FUNCTION` statement and remove the function using the `DROP PIPELINE FUNCTION` statement. Also, you can administer privileges for data pipelines and data pipeline functions. For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
## CREATE PIPELINE
`CREATE PIPELINE` defines a data pipeline that you can execute with the `START PIPELINE` SQL statement. Specify the type of load, data source, and data format.
You must have the `ALTER` privilege on the pipeline. For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
**Syntax**
```sql SQL theme={null}
CREATE [ OR REPLACE ] [ BATCH | CONTINUOUS | TRANSACTIONAL ] PIPELINE [ IF NOT EXISTS ] pipeline_name
[ ]
[ BAD_DATA_TARGET ]
SOURCE ( | | | )
[ MONITOR ( | ) ]
[ LOOKUP lookup_source ] [ ... ]
EXTRACT
( | |
| |
| |
)
[ ]
[ INSERT ] INTO destination_table_name
SELECT
expression as col_alias_target,
expression2 as col_alias_target2,
...
[ WHERE filter_expression ]
[ [ INSERT ] INTO destination_table_name_n
SELECT
expression_n as col_alias_target_n,
expression2_n as col_alias_target2_n,
...
[ WHERE filter_expression_n ] ] [ ... ]
/********************/
/* ADVANCED OPTIONS */
/********************/
advanced_pipeline_options ::=
[ CORES processing_cores ]
[ PARTITIONS file_partitions ]
[ BATCH_SIZE number_of_rows ]
[ RECORD_NUMBER_FORMAT record_number_format ]
/***************************/
/* BAD_DATA_TARGET OPTIONS */
/***************************/
kafka_bad_data_target ::=
KAFKA
BOOTSTRAP_SERVERS bootstrap_servers
TOPIC topic_name
[ CONFIG config_option ]
/******************/
/* SOURCE OPTIONS */
/******************/
s3_source ::=
S3
BUCKET bucket_name
( FILTER | FILTER_GLOB | FILTER_REGEX | OBJECT_KEY ) specifiers
[ REGION region ]
[ ENDPOINT endpoint ]
[ ENABLE_PATH_STYLE_ACCESS enable_path_style_access ]
[ ACCESS_KEY_ID access_key_credentials ]
[ SECRET_ACCESS_KEY secret_key_credentials ]
[ SESSION_TOKEN session_token ]
[ ROLE_ARN role_arn ]
[ ASSUME_ROLE_CONFIG assume_role_config]
[ MAX_CONCURRENCY parallel_connections ]
[ READ_TIMEOUT num_seconds ]
[ REQUEST_DEPTH num_requests ]
[ REQUEST_RETRIES num_retries ]
[ HEADERS headers ]
filesystem_source ::=
FILESYSTEM
( FILTER | FILTER_GLOB | FILTER_REGEX ) specifiers
hdfs_source ::=
HDFS
( FILTER | FILTER_GLOB | FILTER_REGEX ) specifiers
ENDPOINT endpoint
[ CONFIG hdfs_config ]
kafka_source ::=
KAFKA
BOOTSTRAP_SERVERS bootstrap_servers
TOPIC topic_name
[ WRITE_OFFSETS write_offsets ]
[ CONFIG config_option ]
[ AUTO_OFFSET_RESET ( 'latest' | 'earliest' )
file_based_source_options ::=
[ PREFIX prefix ]
[ COMPRESSION_METHOD 'gzip' ]
[ SORT_BY ( 'filename' | 'created' | 'modified' )
[ SORT_DIRECTION ( ASC | DESC ) ] ]
[ SORT_REWRITE sort_rewrite ]
[ START_FILENAME start_filename ]
[ END_FILENAME end_filename ]
[ START_CREATED_TIMESTAMP start_created_timestamp ]
[ END_CREATED_TIMESTAMP end_created_timestamp ]
[ START_MODIFIED_TIMESTAMP start_modified_timestamp ]
[ END_MODIFIED_TIMESTAMP end_modified_timestamp ]
/******************/
/* MONITOR OPTIONS */
/******************/
sqs_monitor ::=
SQS
QUEUE_URL queue_url
[ REGION region ]
[ ENDPOINT endpoint ]
[ ACCESS_KEY_ID access_key_id ]
[ SECRET_ACCESS_KEY secret_access_key ]
kafka_monitor ::=
KAFKA
BOOTSTRAP_SERVERS bootstrap_servers
TOPIC topic
AUTO_OFFSET_RESET ( 'latest' | 'earliest' )
[ GROUP_ID group_id ]
[ MESSAGE {
FILENAME file_selector
TIMESTAMP timestamp_selector
SIZE size_selector
} ]
[ CONSUMER {
MAX_MESSAGES max_messages
TIMEOUT consumer_timeout
} ]
general_monitor_options ::=
[ POLLING_INTERVAL polling_interval ]
[ BATCH {
MAX_FILES max_files
TIMEOUT batch_timeout
LOOKBACK lookback
} ]
/*******************/
/* LOOKUP OPTIONS */
/*******************/
lookup_options ::=
CONNECTION_TYPE connection_type
CONNECTION_STRING connection_string
LOOKUP_SCHEMA lookup_schema
LOOKUP_TABLE lookup_table
[ REFRESH_PERIOD refresh_period ]
[ CONFIG config_json ]
/*******************/
/* EXTRACT OPTIONS */
/*******************/
general_extract_options ::=
[ CHARSET_NAME charset_name ]
[ COLUMN_DEFAULT_IF_NULL column_default_if_null ]
[ NULL_STRINGS null_strings ]
[ TRIM_WHITESPACE trim_whitespace ]
[ VALIDATE_CHARACTERS validate_characters ]
[ REPLACE_INVALID_CHARACTERS replace_invalid_characters ]
[ REPLACEMENT_CHARACTER replacement_character ]
delimited_extract_options ::=
FORMAT ( 'delimited' | 'csv' )
[ COMMENT_CHAR comment_char ]
[ EMPTY_FIELD_AS_NULL empty_field_as_null ]
[ ESCAPE_CHAR escape_char ]
[ FIELD_DELIMITER field_delimiter ]
[ FIELD_OPTIONALLY_ENCLOSED_BY enclosure_char ]
[ HEADERS delimited_headers ]
[ NUM_HEADER_LINES num_header_lines ]
[ NUM_FOOTER_LINES num_footer_lines ]
[ RECORD_DELIMITER record_delimiter ]
[ SKIP_EMPTY_LINES skip_empty_lines ]
[ OPEN_ARRAY open_array_char ]
[ CLOSE_ARRAY close_array_char ]
[ ARRAY_ELEMENT_DELIMITER array_delimiter ]
[ OPEN_OBJECT open_object_char ]
[ CLOSE_OBJECT close_object_char ]
[ STRIP_ARRAY_ELEMENT_QUOTES strip_array_element_quotes ]
[ STRIP_FIELD_QUOTES strip_field_quotes ]
[ TRIM_ARRAY_ELEMENTS trim_array_elements]
asn1_extract_options ::=
FORMAT 'asn.1'
SCHEMA {
URL url_asn1
RECORD_TYPE record_type
}
avro_extract_options ::=
FORMAT 'avro'
[ SCHEMA {
[ INLINE inline_string ]
[ INFER_FROM 'sample_file' ]
[ URL url_avro ]
[ CONFIG config_avro ]
[ SUBJECT subject ]
[ SCHEMA_REGISTRY_ID_LOCATION ( 'header_or_value' | 'value' | 'none' ) ]
} ]
binary_extract_options ::=
FORMAT 'binary'
RECORD_LENGTH length_in_bytes
[ ENDIANNESS ( 'big' | 'little' ) ]
[ AUTO_TRIM_PADDING auto_trim_padding ]
[ PADDING_CHARACTER padding_character ]
json_extract_options ::=
FORMAT 'json'
parquet_extract_options ::=
FORMAT 'parquet'
SCHEMA {
INFER_FROM infer_from
}
xml_extract_options ::=
FORMAT 'xml'
```
### Pipeline Identity and Naming
The name of a data pipeline is unique in an System. Reference the pipeline in other SQL statements like `START PIPELINE`, `STOP PIPELINE`, and `DROP PIPELINE` using the name of the pipeline. The SQL statement throws an error if a pipeline with the same name already exists unless you specify the `IF NOT EXISTS` option. You can rename a pipeline with the `ALTER PIPELINE RENAME` SQL statement.
### Update a Pipeline
You can update a pipeline with the `OR REPLACE` clause in the `CREATE PIPELINE` SQL statement. Use this clause when you want to continue loading from the current place in a continuous load, but you need to modify transformations or other settings. If you specify the `OR REPLACE` clause and the pipeline already exists, the database replaces the original pipeline object with the options specified in the new `CREATE OR REPLACE PIPELINE` statement. When you replace an existing pipeline, the pipeline retains its current position in the source data so that data is not duplicated when the pipeline is resumed with a `START PIPELINE` SQL statement. First, you must stop a pipeline before executing the `CREATE OR REPLACE` SQL statement.
### Data Pipeline Modes
You can define pipelines in either batch `BATCH`, continuous `CONTINUOUS`, or transactional `TRANSACTIONAL` mode.
* File sources (e.g., `s3`, `filesystem`) support `BATCH` and `CONTINUOUS` modes. File-based loads default to `BATCH` mode if you do not specify this keyword.
* only supports `CONTINUOUS` mode. Loads with a Kafka source default to `CONTINUOUS` mode if you do not specify this keyword.
* When you execute the `START PIPELINE` SQL statement using a data pipeline in the `BATCH` mode, the system creates a static list of files with the `PENDING` status in the `sys.pipeline_files` system catalog table. With the `CONTINUOUS` mode, the monitor appends new incoming files to the list of files in the `sys.pipeline_files` system catalog table.
* With the `CONTINUOUS` mode, you can apply filters for the data pipeline. The system only uses files in the consumed messages if the filenames match the filters. For this mode, these options are invalid:
* PREFIX
* SORT\_BY
* SORT\_DIRECTION
* SORT\_REWRITE
* START\_CREATED\_TIMESTAMP
* END\_CREATED\_TIMESTAMP
* START\_MODIFIED\_TIMESTAMP
* END\_MODIFIED\_TIMESTAMP
* The `TRANSACTIONAL` mode enables the data pipeline to roll back the interim results of the load if an error occurs during load execution. The system makes all data visible only after the load completes successfully. This mode supports all options that the `BATCH` mode does. For details, see [Transactional Data Pipelines](/transactional-data-pipelines).
### Required Options
You must define certain options in every pipeline. For these options, there is no default value. Optional options need to be present only if you use specific functions. A pipeline must contain the `SOURCE`, `EXTRACT FORMAT`, and `INTO table_name ... SELECT` statements.
* [SOURCE Options](#source-options)
* [EXTRACT Options](#extract-options)
* [Data Formats for Data Pipelines](/data-formats-for-data-pipelines)
* [Transform Data in Data Pipelines](/transform-data-in-data-pipelines)
These options depend on each other: `IF NOT EXISTS` and `OR REPLACE` SQL statements are mutually exclusive.
### SELECT Statement and Data Transformation
Use the `INTO table_name ... SELECT` SQL statement in the `CREATE PIPELINE` SQL statement to specify how to transform the data. The `SELECT` statement includes a set of one or more expressions and a target column name in the form `expression as column_name`. The `expression` part in the statement contains a source field reference (e.g., `$1` or `$my_field.subfield`) and, optionally, the transformation function you want to apply.
If your data is nested in arrays, you can use special transformation functions, such as the [EXPLODE\_OUTER](/special-data-pipeline-transformation-functions) function, to expand the data into individual rows.
For details about data transformation and supported transformation functions, see [Transform Data in Data Pipelines](/transform-data-in-data-pipelines).
For details about data types and casting, see [Data Types for Data Pipelines](/data-types-for-data-pipelines) and [Data Formats for Data Pipelines](/data-formats-for-data-pipelines).
You can also specify metadata values, such as filename, to load in the `SELECT` SQL statement. For details, see [Load Metadata and File-Based Partitioned Data in Data Pipelines](/load-metadata-and-file-based-partitioned-data-in-data-pipelines).
This is an example of a transformation statement snippet.
```sql SQL theme={null}
...
FORMAT json
INTO public.orders
SELECT
TIMESTAMP(BIGINT($created_timestamp)) as ordertime,
metadata('filename') as source_filename,
$order_number as ordernumber,
$customer.first_name as fname,
LEFT($customer.middle_initial,1) as minitial,
$customer.last_name as lname,
$postal_code as postal_code,
$promo_code as promo_code,
$order_total as ordertotal,
DECIMAL($tax,8,2) as tax,
CHAR[]($line_items[].product_name) as product_names,
CHAR[]($line_items[].sku) as skus
```
Optionally, you can filter the load by using the `WHERE` clause in the form `WHERE filter_expression`. This expression should evaluate to a Boolean value or NULL and can include more than one filter expression. The system loads rows that contain data matching the filter criteria when the expression evaluates to `true`. The system does not load the rows when the expression evaluates to `false` or NULL. You can include any transform in the `WHERE` clause as in the `SELECT` clause.
This is an example of a filter snippet that loads order data for customers whose last name starts with the letter `a`. Use the `COALESCE` function to return only non-NULL values.
```sql SQL theme={null}
...
FORMAT json
INTO public.orders
SELECT
TIMESTAMP(BIGINT($created_timestamp)) as ordertime,
metadata('filename') as source_filename,
$order_number as ordernumber,
$customer.first_name as fname,
LEFT($customer.middle_initial,1) as minitial,
$customer.last_name as lname,
$postal_code as postal_code,
$promo_code as promo_code,
$order_total as ordertotal,
DECIMAL($tax,8,2) as tax,
CHAR[]($line_items[].product_name) as product_names,
CHAR[]($line_items[].sku) as skus
WHERE
STARTSWITH(COALESCE($customer.last_name, ''),'a')
```
#### NULL and Default Value Handling
The Ocient System has specific ways to handle NULL and default values in the data pipeline. Consider this information when you prepare data to load and write the `CREATE TABLE` and `CREATE PIPELINE` SQL statements.
To load NULL values, insert the NULL value in the data. In this case, if you specify `NOT NULL` for the target column in the `CREATE TABLE` statement, the data pipeline fails to load.
If you omit a column in the `SELECT` SQL statement, the data pipeline loads the default value for the column. If you do not specify the default value, the pipeline loads a NULL value. If you specify `NOT NULL` for the target column, the data pipeline also fails to load.
You can use the `DEFAULT` keyword to load a default value. In this case, if the column does not have a default value, the pipeline fails to load. If the pipeline loads a NULL into a column with a specified default value, you can use `COALESCE(, DEFAULT)` to insert the default value instead of the NULL value, where `` is the NULL column. You can modify the load of one column at a time in this way.
This table describes the data pipeline behavior for NULL or omitted column values.
| **Value in the Data Pipeline** | **Nullable Target Column** | **Default Value in Target Column** | **Resulting Data Pipeline Behavior** |
| -------------------------------------------- | ------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| NULL | No | Value might or might not be set. | The pipeline uses the default value if the default exists and you specify the `COLUMN_DEFAULT_IF_NULL` option. Otherwise, the pipeline fails. |
| NULL | Yes | Value might or might not be set. | The pipeline uses the default value if the default exists and you specify the `COLUMN_DEFAULT_IF_NULL` option. Otherwise, the pipeline uses the NULL value. |
| Omitted column in the `SELECT` SQL statement | NULL value might or might not be set. | Yes | The pipeline uses the default value. |
| Omitted column in the `SELECT` SQL statement | No | No | The pipeline fails. |
| Omitted column in the `SELECT` SQL statement | Yes | No | The pipeline uses the NULL value. |
### Required Privileges
You must have the `CREATE PIPELINE` privilege on the underlying database and the `VIEW` privilege on each table in the pipeline definition to execute the `CREATE PIPELINE` SQL statement. The table must already exist.
See the `START PIPELINE` SQL statement for the required privileges to execute a pipeline.
For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
### Examples
#### Load JSON Data from Kafka
This example loads JSON data from Kafka using the `CREATE PIPELINE` SQL statement. Use the bootstrap server `192.168.0.1:9092` using the Kafka topic `orders`. Load data into the `public.orders` table. Specify the data to load as these JSON selectors:
* Identifier `$id`
* User identifier `$user_id`
* Product identifier `$product_id`
* Subtotal amount `$subtotal`
* Tax `$tax`
* Total amount `$total`
* Discount amount `$discount`
* Created time `$created_at`
* Quantity `$quantity`
```sql SQL theme={null}
CREATE PIPELINE orders_pipeline
SOURCE KAFKA
BOOTSTRAP_SERVERS '192.168.0.1:9092'
TOPIC 'orders'
EXTRACT
FORMAT json
INTO public.orders
SELECT
$id as id,
$user_id as user_id,
$product_id as product_id,
$subtotal as subtotal,
$tax as tax,
$total as total,
$discount as discount,
$created_at as created_at,
$quantity as quantity;
```
For a complete tutorial, see [Data Pipeline Load of JSON Data from Kafka](/data-pipeline-load-of-json-data-from-kafka).
#### Load Delimited Data from S3
This example loads delimited data in CSV format from S3. Use the [`https://s3.us-east-1.amazonaws.com`](https://s3.us-east-1.amazonaws.com) endpoint with the `ocient-docs` bucket and path `metabase_samples/csv/orders.csv`. Denote path-style access using the `ENABLE_PATH_STYLE_ACCESS` option set to `true`. Specify one header line with the `NUM_HEADER_LINES` option. Load data into the `public.orders` table. Specify the data to load using the column numbers:
* Idenfier
* User identifier
* Product identifier
* Subtotal amount
* Tax
* Total amount
* Discount amount
* Created time
* Quantity
```sql SQL theme={null}
CREATE PIPELINE orders_pipeline
SOURCE S3
ENDPOINT 'https://s3.us-east-1.amazonaws.com'
BUCKET 'ocient-docs'
FILTER 'metabase_samples/csv/orders.csv'
ENABLE_PATH_STYLE_ACCESS true
EXTRACT
FORMAT csv
NUM_HEADER_LINES 1
INTO public.orders
SELECT
$1 as id,
$2 as user_id,
$3 as product_id,
$4 as subtotal,
$5 as tax,
$6 as total,
$7 as discount,
$8 as created_at,
$9 as quantity;
```
For a complete tutorial, see [Data Pipeline Load of CSV Data from S3](/data-pipeline-load-of-csv-data-from-s3).
#### Continuous File Load of Delimited Data in CSV Files
Create a data pipeline that uses continuous file loading with delimited data in CSV files. Specify to use 32 partitions and 16 cores with the `PARTITIONS` and `CORES` options, respectively. The source is S3 with the `http://endpoint.ocient.com` endpoint and `cs_data` bucket. Specify the filter `'*.csv'` to find all files with a filename that matches a glob pattern without subdirectories, for example, `data.csv`. The system filters filenames with subdirectories such as `data/data_sample.csv`.
For continuous file loading, specify the `MONITOR` option to use the Kafka monitor. Specify the `test-broker:9092` bootstrap server, `cfl_kafka_ten_adtech_flat_small` Kafka topic, and reset the offset to the smallest offset using the `earliest` value of the `AUTO_OFFSET_RESET` option. Set the client group identifier to `84079bf1-bdc4-4b10-ba12-41ba6b17dffe`.
The format is `csv` with the record delimiter as the newline character `\n`. Load data in the `public.ad_sessions` table.
The `SELECT` statement identifies the columns to load by number. There are 39 fields in the CSV data. For each column, transform each column using cast functions. For details, see [Scalar Data Conversion Functions](/scalar-data-conversion-functions) for each function. See [Date and Time Functions](/date-and-time-functions) for the `TO_TIMESTAMP` function.
```sql SQL theme={null}
CREATE CONTINUOUS PIPELINE test_continuous_pipeline
PARTITIONS 32
CORES 16
SOURCE S3
ENDPOINT 'http://endpoint.ocient.com/'
BUCKET 'cs_data'
FILTER '*.csv'
MONITOR kafka
BOOTSTRAP_SERVERS 'test-broker:9092'
TOPIC 'cfl_kafka_ten_adtech_flat_small'
AUTO_OFFSET_RESET 'earliest'
GROUP_ID '84079bf1-bdc4-4b10-ba12-41ba6b17dffe'
EXTRACT
FORMAT csv
RECORD_DELIMITER '\n'
INTO public.ad_sessions
SELECT
TO_TIMESTAMP(CHAR($1), 'yyyy-MM-dd HH:mm:ss.SSSSSS', 'java') AS event_date_time,
CHAR($2) AS device_model,
TINYINT($8) AS device_user_age,
BOOLEAN($10) AS device_ad_tracking_disabled,
BINARY($11) AS device_mac,
INT($14) AS ip_zip,
FLOAT($19) AS ip_zip_latitude,
DOUBLE($20) AS ip_zip_longitude,
BIGINT($21) AS session_id,
SMALLINT($32) AS session_response_latency,
DECIMAL($34, 10, 1) AS session_transaction_revenue,
CHAR($39) AS session_app_name
;
```
#### Transactional Load of Delimited Data in CSV Files
Create a data pipeline that uses transactional file loading with delimited data in CSV files. The source is S3 with the `http://endpoint.ocient.com` endpoint and `cs_data` bucket. Specify the filter `'*.csv'` to find all files with a filename that matches a glob pattern without subdirectories, for example, `data.csv`. The system filters filenames with subdirectories such as `data/data_sample.csv`.
The format is `csv`. Load data in the `public.ad_sessions` table.
The `SELECT` statement identifies the columns to load by number. For each column, transform each column using cast functions. For details, see [Scalar Data Conversion Functions](/scalar-data-conversion-functions) for each function. See [Date and Time Functions](/date-and-time-functions) for the `TO_TIMESTAMP` function.
```sql SQL theme={null}
CREATE TRANSACTIONAL PIPELINE test_continuous_pipeline
SOURCE S3
ENDPOINT 'http://endpoint.ocient.com/'
BUCKET 'cs_data'
FILTER '*.csv'
EXTRACT
FORMAT csv
INTO public.ad_sessions
SELECT
TO_TIMESTAMP(CHAR($1), 'yyyy-MM-dd HH:mm:ss.SSSSSS', 'java') AS event_date_time,
CHAR($2) AS device_model,
TINYINT($8) AS device_user_age,
BOOLEAN($10) AS device_ad_tracking_disabled,
BINARY($11) AS device_mac,
INT($14) AS ip_zip,
FLOAT($19) AS ip_zip_latitude,
DOUBLE($20) AS ip_zip_longitude,
BIGINT($21) AS session_id,
SMALLINT($32) AS session_response_latency,
DECIMAL($34, 10, 1) AS session_transaction_revenue,
CHAR($39) AS session_app_name
;
```
### SOURCE Options
#### File-Based Source Options
Options that apply to both the `S3`, `FILESYSTEM`, and `HDFS` sources.
| **Option Key** | **Default** | **Data Type** | **Description** |
| --------------------------------------- | ----------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| FILTER \| FILTER\_GLOB \| FILTER\_REGEX | None | STRING | The expression for filtering files in the directory or child directories to load. If you do not specify the `PREFIX` option, this pattern applies to the full path to the file, except for the Bucket for S3-compatible file sources. If you specify the `PREFIX` option, this pattern applies to the file path portion after the specified prefix value.
Paths include a leading forward slash.
For `FILESYSTEM` sources, this option is required.
For `S3` sources, one of the `FILTER`, `FILTER_GLOB`, `FILTER_REGEX`, or `OBJECT_KEY` keys is required.
Specify one of these options: \* `FILTER_GLOB` or `FILTER` — Regular filename patterns. Supported options include: - `*` indicates unlimited wildcard characters except for the path character, `/`. - `**` indicates wildcard characters, including path separators. - `?` indicates a single wildcard character. \* `FILTER_REGEX` — Regular expression patterns to filter files. Some common patterns include: - `.` matches any character. - `*` matches any 0 or more of the preceding character. - `+` matches a single character. - `[135]` matches any one character in the set. - `[1-5]` matches any one character in the range. - `(a\|b)` matches a or b. ℹ️ When you use the FILTER or FILTER\_GLOB options with a continuous data pipeline, the system supports only basic globbing, and extended, range globbing is not supported.
**FILTER\_GLOB Examples:** List all CSV files in subdirectories named `2024` that are in any subdirectory of the `trades` directory, which is in the root of the bucket. `FILTER_GLOB = '/trades/*/2024/*.csv'` List all CSV files in the bucket in all subdirectories. `FILTER_GLOB = '**/*.csv'`
**FILTER\_REGEX Examples:** List all `json.gz` files in the bucket that contain the name `orders` anywhere in the path. `FILTER_REGEX = '.*orders.*\.json\.gz'` List all files in the bucket in the root path `metrics` or `values` where the date string on the filename is 2000 to 2004. `FILTER_REGEX = '/(metrics\|values)/.*200[0-4].*'` |
| PREFIX | `NULL` | STRING or ARRAY OF STRINGS | Optional.
Specify a prefix within which to apply the filter. When you specify a list of prefixes, the system applies the filter to each one, and the results are unioned together.
Prefixes must be paths to directories, meaning they end with a forward slash. For `FILESYSTEM` sources, paths should be absolute, meaning they begin with a forward slash.
For `S3` sources, use prefixes to reduce the search space when listing objects within the specified `BUCKET`. For maximum performance, use the `PREFIX` option whenever possible, especially when combined with the `FILTER_REGEX` option.
ℹ️This option is not available for continuous data pipelines.
**Examples:** List all CSV files in the `2024` subdirectory of `files`. `PREFIX '/files/2024/' FILTER '**/*.csv'` List all JSON files of subdirectory `2024/09/` in the `orders` directory. `PREFIX '/data/orders/2024/09/' FILTER_REGEX '.*/orders/.*json'` List all JSON files in multiple subdirectories. `PREFIX ['/data/orders/2024/09/', '/data/orders/2024/10/']` |
| COMPRESSION\_METHOD | `NULL` | STRING | Optional.
The method the Ocient System uses to decompress file data. The only supported option is `gzip`. To load uncompressed data, omit the COMPRESSION\_METHOD option.
ℹ️The COMPRESSION\_METHOD option is only applicable to file-based sources. Kafka pipelines automatically decompress data based on the Kafka topic configuration. |
| SORT\_BY | `filename` | STRING | Optional.
The sort criteria for sorting the file list before the load. Supported options are: \* `filename` — Sort files lexicographically by the filename. \* `created` — Sort files based on the file created timestamp. \* `modified` — Sort files based on the file modified timestamp. Sorting files such that the Ocient System sorts the data within the files according to the column in the target table can lead to better query performance.
ℹ️This option is not available for continuous data pipelines. |
| SORT\_DIRECTION | `ASC` | STRING | Optional.
The sort direction, either `ASC` ascending or `DESC` descending, determines the sort order. If you specify this option, you must also specify the SORT\_BY option.
ℹ️This option is not available for continuous data pipelines. |
| SORT\_REWRITE | `NULL` | STRING | Optional.
This option is a sort comparator, allowing files to be renamed during the sort operation using capture groups from the filter regular expression. If you specify this option, you must also specify the `FILTER_REGEX` option.
If you do not specify this option, the system uses the sorting specified by the SORT\_BY option.
ℹ️This option is not available for continuous data pipelines.
Example:
`FILTER_REGEX '(\d+)_(\d+)_(\d+)-order.json'` `SORT_REWRITE '\3-\1-\2.json'` This specification renames the file from `5_6_1999-orders.json` to `1999_5_6.json` by switching the order of the date fields. |
| START\_FILENAME | `NULL` | STRING | Optional.
The filename string that is the lower bound to filter for files lexicographically for batch pipelines. (inclusive) Use the full path of the file, such as `'/dir/load_file.json'`. If the file is located in the top-most directory, start the path with a slash `/`, such as `'/load_file.json'`. You can use this option without the END\_FILENAME option. If you specify the END\_FILENAME option, the value of the START\_FILENAME option must be smaller than the value for the END\_FILENAME option lexicographically. |
| END\_FILENAME | `NULL` | STRING | Optional.
The filename string that is the upper bound to filter for files lexicographically for batch pipelines. (inclusive) Use the full path of the file, such as `'/dir/load_file.json'`. If the file is located in the top-most directory, start the path with a slash `/`, such as `'/load_file.json'`. You can use this option without the START\_FILENAME option. If you specify the END\_FILENAME option, the value of the START\_FILENAME option must be smaller than the value for the END\_FILENAME option lexicographically. |
| START\_CREATED\_TIMESTAMP | `NULL` | TIMESTAMP-formatted STRING | Optional.
The ISO-8601-compliant date or date time that is used as the lower bound (inclusive) to filter files by created timestamp for batch pipelines. The time zone should match the file metadata.
If you specify both, the value for the START\_CREATED\_TIMESTAMP option must be before the value for the END\_CREATED\_TIMESTAMP option.
ℹ️This option is not available for continuous data pipelines. |
| END\_CREATED\_TIMESTAMP | `NULL` | TIMESTAMP-formatted STRING | Optional.
The ISO-8601-compliant date or date time that is used as the lower bound (inclusive) to filter files by created timestamp for batch pipelines. The time zone should match the file metadata.
If you specify both, the value for the START\_CREATED\_TIMESTAMP option must be before the value for the END\_CREATED\_TIMESTAMP option.
ℹ️This option is not available for continuous data pipelines. |
| START\_MODIFIED\_TIMESTAMP | `NULL` | TIMESTAMP-formatted STRING | Optional.
The ISO-8601-compliant date or date time that is used as the lower bound (inclusive) to filter files by modified timestamp for batch pipelines. The time zone should match the file metadata.
If you specify both, the value for the START\_MODIFIED\_TIMESTAMP option must be before the value for the END\_MODIFIED\_TIMESTAMP option.
ℹ️This option is not available for continuous data pipelines. |
| END\_MODIFIED\_TIMESTAMP | `NULL` | TIMESTAMP-formatted STRING | Optional.
The ISO-8601-compliant date or date time that is used as the lower bound (inclusive) to filter files by modified timestamp for batch pipelines. The time zone should match the file metadata.
If you specify both, the value for the START\_MODIFIED\_TIMESTAMP option must be before the value for the END\_MODIFIED\_TIMESTAMP option.
ℹ️This option is not available for continuous data pipelines. |
#### S3 Source Options
You can apply these options to data sources of the `SOURCE S3` type, which include S3 and S3-compatible services.
| **Option Key** | **Default** | **Data Type** | **Description** |
| --------------------------- | --------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| BUCKET | None | STRING | The name of the bucket in AWS S3. |
| OBJECT\_KEY | `NULL` | STRING or ARRAY OF STRINGS | Optional.
Specify an S3 object key(s) to load. You cannot use this option if you specify `PREFIX`, `FILTER`, `FILTER_GLOB`, or `FILTER_REGEX` keys are specified. If you do not specify one of the `FILTER`, `FILTER_GLOB`, or `FILTER_REGEX` keys, this option is required.
Object keys do not include a leading forward slash. Specifying individual objects can be faster than filtering, because the Ocient System avoids listing all the files in a large directory.
Object keys must not include any of the special characters: `*?{}[]`
ℹ️This option is not available for continuous data pipelines.
**Examples:** Load a single object from the designated bucket at the specified object key. `OBJECT_KEY 'order_data/jsonl/orders_20251101.jsonl'` Load a list of objects from the designated bucket at the specified object keys. `OBJECT_KEY ['order_data/jsonl/orders_20251101.jsonl', 'order_data/jsonl/orders_20251201.jsonl']` |
| ACCESS\_KEY\_ID | `''` | STRING | Optional.
The access key identification for AWS credentials. If you specify this option, you must also specify the `SECRET_ACCESS_KEY` option. The Ocient System uses anonymous credentials when you specify an empty value for this option. |
| SECRET\_ACCESS\_KEY | `''` | STRING | Optional.
The secret key for AWS credentials. If you specify this option, you must also specify the ACCESS\_KEY\_ID option. The Ocient System uses anonymous credentials when you specify an empty value for this option. |
| SESSION\_TOKEN | `NULL` | STRING | Optional.
Temporary credentials can be made with a combination with the existing access key identifier and secret key, and an additional session token. You must specify the ACCESS\_KEY\_ID and SECRET\_ACCESS\_KEY options when you use this option. |
| ROLE\_ARN | `NULL` | STRING | Optional.
The Resource Name (ARN) of the role to retrieve temporary credentials. The STS client used to retrieve the temporary credentials specifies the [region](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#automatically-determine-the-aws-region-from-the-environment) loaded from `DefaultAwsRegionProviderChain` and [credentials](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html) loaded from `DefaultCredentialsProvider`. You cannot use this option with the ACCESS\_KEY\_ID and SECRET\_ACCESS\_KEY options. |
| ASSUME\_ROLE\_CONFIG | `{}` | STRING | Optional.
Additional configuration used to configure the `StsAssumeRoleCredentialsProvider` or `AssumeRoleRequest` used to retrieve and refresh temporary credentials with the ROLE\_ARN option. This option is a JSON-formatted string that you can only specify at the same time as the ROLE\_ARN option. The supported configuration options are: `"asyncCredentialUpdateEnabled"`, `"prefetchTimeSeconds"`, `"staleTimeSeconds"` for `StsAssumeRoleCredentialsProvider` and `"durationSeconds"`, `"externalId"`, `"policy"`, `"roleSessionName"`, `"serialNumber"`, `"tokenCode"` for `AssumeRoleRequest`. |
| REGION | `'us-east-1'` | STRING | Optional.
The region that the Ocient System uses for AWS access. If you specify the `ENDPOINT` option, the system ignores this option. |
| ENDPOINT | `NULL` | STRING | Optional.
The endpoint URI for the S3-compatible service API. (e.g., `https://s3.us-east-2.amazonaws.com`)
When unspecified, this option defaults to `https://s3.REGION.amazonaws.com`.
If you provide this option, the Ocient System ignores the `REGION` option. |
| ENABLE\_PATH\_STYLE\_ACCESS | `NULL` | BOOLEAN | Optional.
Whether to use path-style access, where the path includes the bucket name in the URL. For example, `https://s3.us-east-1.amazonaws.com/bucket-name/key-name`. The `false` value denotes virtual-hosted style access, where the URL contains the bucket name as part of the domain name. For example, `https://bucket-name.s3.us-east-1.amazonaws.com/key-name`.
When unspecified, this option defaults to `true` if the `ENDPOINT` option is specified and `false` otherwise. |
| HEADERS | `NULL` | STRING | Optional.
The headers to send with every request. This option is a JSON-formatted string. Represent the chosen header names as keys with corresponding values as scalars or lists of scalars. The system converts scalars that are not strings to strings. During the load, the system maps each element in a list to the header name represented by the corresponding key.
Examples:
`HEADERS '{"x-amz-request-payer": "requester"}'` returns this header for each request: `x-amz-request-payer: requester`.
`HEADERS '{"header-name": ["list", "of", "values"]}'` returns this header for each request: `header-name: list, of, values`. |
| MAX\_CONCURRENCY | 50 | INTEGER | Optional.
Determines the number of parallel connections the Ocient System uses to communicate with the AWS S3 service. ⚠️ This option does not require modification in most cases. Contact Ocient Support to modify these values. |
| READ\_TIMEOUT | 0 (unlimited timeout) | TIME INTERVAL | Optional.
The time until a read operation times out. ⚠️ This option does not require modification in most cases. Contact Ocient Support to modify these values. |
| REQUEST\_DEPTH | 500 | INTEGER | Optional.
The upper boundary of requests that the Ocient System handles concurrently. ⚠️ This option does not require modification in most cases. Contact Ocient Support to modify these values. |
| REQUEST\_RETRIES | 10 | INTEGER | Optional.
Number of times the AWS SDK retries failing requests before the Ocient System throws an error. ⚠️ This option does not require modification in most cases. Contact Ocient Support to modify these values. |
**S3 Credentials Hierarchy**
The S3 source configuration supports this hierarchy to obtain S3 credentials:
* Level 1: Data pipeline configuration (set by using the `ACCESS_KEY_ID` and `SECRET_ACCESS_KEY` options)
* Level 2: [AWS SDK Default Credential Provider Chain ](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html)(set by using the instructions provided in the web page)
* Level 3: Anonymous access (set by default)
If the Ocient System does not obtain the credentials at a level, the system tries a lower level.
You can choose the level to store the credentials, where Level 1 is the highest. Higher levels take precedence for credential storage.
#### FILESYSTEM Source Options
No options exist specific to the file system source (`SOURCE FILESYSTEM`) except for general [file-based source options](#file-based-source-options).
When you load data using `SOURCE FILESYSTEM`, the files must be addressable from all of your Loader Nodes. The Ocient System uses the specified path in the pipeline PREFIX and FILTER options to select the files to load.
A shared view of the files you want to load must be available to all Loader Nodes involved in a pipeline. For example, you can use a Network File System (NFS) mount available to all Loader Nodes at a common path on each node.
**Example**
This example `CREATE PIPELINE` SQL statement snippet contains a `FILESYSTEM` source and filters to all CSV files in the `/tmp/sample-data/` directory on each of the Loader Nodes.
```sql SQL theme={null}
CREATE PIPELINE ...
SOURCE FILESYSTEM
PREFIX '/tmp/sample-data/'
FILTER '**/*.csv'
EXTRACT
FORMAT delimited
INTO public.orders
SELECT
$1 as username,
$2 as subtotal,
...
```
#### HDFS Source Options
You can specify these options for data sources (`SOURCE HDFS`).
For advanced options, see [Data Pipeline Load of JSON Data from HDFS](/data-pipeline-load-of-json-data-from-hdfs).
| **Option Key** | **Default** | **Data Type** | **Description** |
| -------------- | ----------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| ENDPOINT | None | STRING | Required.
The hostname and port number of the namenode server. For example, `'my-hdfs-server:1234'`.
The namenode server manages the file system and regulates access to data. |
| CONFIG | None | JSON-formatted STRING | Optional.
The JSON string that contains HDFS [configuration properties](https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/hdfs-default.xml) to use during the load. The properties are primarily for authentication. You can also use these properties to configure advanced properties such as connection timeouts, parallelism, and network chunk sizes.
**Example:** `CONFIG '{"dfs.client.use.datanode.hostname": true, "dfs.client.socket-timeout": 300000}'` |
#### KAFKA Source Options
You can apply these options to Kafka data sources (`SOURCE KAFKA`).
For compression, you do not need to specify a compression option in Kafka-based pipelines, because the Ocient System handles the compression type automatically. Records produced to the Kafka broker with a `compression.type` setting or with the `compression.type` set on the topic automatically decompress when the loading process consumes the records. The loading process uses built-in headers in Kafka to determine the required decompression during extraction.
| **Option Key** | **Default** | **Data Type** | **Description** |
| ------------------- | ---------------------------------------------------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BOOTSTRAP\_SERVERS | None | STRING | A comma-delimited list of `IP:port` pairs that contain the IP addresses and the associated port numbers of the Kafka Brokers. You can also use a hostname instead of the IP address. **Example:** `BOOTSTRAP_SERVERS = '198.51.100.1:9092,198.51.100.2:9092'` |
| TOPIC | None | STRING | The name of the Kafka topic indicates where to consume records. |
| WRITE\_OFFSETS | `true` | BOOLEAN | Optional.
Indicates whether the Kafka consumer should write its durably-made record offsets to the Kafka Broker. |
| CONFIG | `'{` `"group.id": "____"` `}'` | JSON-formatted STRING | Optional.
The [consumer configuration](https://docs.confluent.io/platform/current/installation/configuration/consumer-configs.html) that the Kafka consumers should use.
Frequently specified configurations include `group.id` and `security.protocol`.
These configurations are fixed and cannot be overridden: `{` `"enable.auto.commit": false,` `"key.deserializer": "org.apache.kafka.common.serialization.ByteArrayDeserializer",` `"value.deserializer": "org.apache.kafka.common.serialization.ByteArrayDeserializer"` `}` |
| AUTO\_OFFSET\_RESET | `'latest'` | STRING | Optional.
Determine which action to take for the Kafka configuration when there is no initial offset in the offset store or the specified offset is out of range.
Supported values are:
`'earliest'` — Automatically reset the offset value to the smallest value.
`'latest'` — Automatically reset the offset value to the largest value. |
| GROUP\_ID | `'____'` | STRING | Optional.
Client group identifier for the Kafka source configuration. |
For the consumer configuration, to create a secure connection from the Kafka consumer to a Kafka Broker, set the `"security.protocol"` key along with any SSL or SASL keys.
If a certificate file is required, you must add it to the truststore used by the on all Loader Nodes. The truststore path must be identical on all Loader Nodes. The Kafka configuration can reference this truststore path.
If you specify the `ssl.certificate.location` or `ssl.ca.location` consumer configuration, you must specify both of these configurations. Otherwise, the system throws an error. For example: `CONFIG '{"auto.offset.reset": "earliest","ssl.certificate.location":"/etc/blab/file1.txt","ssl.ca.location":"/etc/blab/file2.txt"}'`
#### Continuous File Loading Source Options
Specify these options for data pipelines that use `FILESYSTEM` or `S3` sources with the `CONTINUOUS` mode. For a Kafka source, do not use these options.
**General File Monitor Options**
| **Option Key** | **Default** | **Data Type** | **Description** |
| ----------------- | ----------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| MONITOR | None | STRING | The type of monitor. Valid values are: `sqs` or `kafka`. |
| POLLING\_INTERVAL | 10 SECONDS | TIME INTERVAL | Optional.
Unit of time to consume the event topic. Valid value range: 10 to 120 seconds. |
| MAX\_FILES | 100 | INTEGER | Optional.
In the `BATCH` syntax, the maximum number of pending files to collect before starting a batch. Valid value range: 10 to 2000. |
| TIMEOUT | 1 MINUTE | TIME INTERVAL | Optional.
In the `BATCH` syntax, the time to wait before starting a batch. Valid value range: 10 seconds to 30 minutes. |
| LOOKBACK | 1 DAY | TIME INTERVAL | Optional.
In the `BATCH` syntax, the unit of time to look back for file deduplication. Valid value range: 0 to 48 hours. |
**SQS Monitor Options**
Use these options when you use `MONITOR sqs` for .
| **Option Key** | **Default** | **Data Type** | **Description** |
| ------------------- | ----------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| QUEUE\_URL | None | STRING | The URL of the target queue. For example: `http://localhost:32769/000000000000/queue1` |
| REGION | `NULL` | STRING | Optional.
The region for the SQS operation for signing requests.
When unspecified, the region is inferred from `QUEUE_URL` by looking for `sqs.REGION` or `sqs-fips.REGION`. If the region cannot be inferred, it defaults to `us-east-1`. |
| ENDPOINT | `NULL` | STRING | Optional.
The endpoint URL for the client. For example: `http://localhost:32769`
When unspecified, defaults to `https://sqs[-fips].REGION.amazonaws.com` if `REGION` was inferred or specified. Otherwise, this option is required. |
| ACCESS\_KEY\_ID | `''` | STRING | Optional.
Access key identifier for SQS authentication.
If you specify this option, you must also specify the `SECRET_ACCESS_KEY` option. The Ocient System uses anonymous credentials when you specify an empty value for this option. |
| SECRET\_ACCESS\_KEY | `''` | STRING | Optional.
The secret access key for SQS authentication. |
**Kafka Monitor Options**
Use these options when you use `MONITOR kafka` for Kafka.
| **Option Key** | **Default** | **Data Type** | **Description** |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BOOTSTRAP\_SERVERS | None | STRING | The bootstrap servers for the Kafka consumer configuration. The string contains a list of brokers as a comma-separated list of the broker hostnames or broker hostnames and port number combinations, in the format `hostname:port`. |
| TOPIC | None | STRING | The name of the Kafka topic indicates where to consume records. |
| AUTO\_OFFSET\_RESET | `'latest'` | STRING | Optional.
Action to take for the Kafka configuration when there is no initial offset in the offset store or the chosen offset is out of range: `'earliest'` — Automatically reset the offset to the smallest offset. `'latest'` — Automatically reset the offset to the largest offset. |
| GROUP\_ID | `'_____monitor'` | STRING | Optional.
Client group identifier for the Kafka configuration. |
| CONFIG | `'{ "enable.auto.commit": false,` `"group.id": "_____monitor",` `"max.poll.interval.ms": "600000",` `"heartbeat.interval.ms": "6000",` `"session.timeout.ms": "600000" }'` | JSON-formatted STRING | Optional.
The [consumer configuration](https://docs.confluent.io/platform/current/installation/configuration/consumer-configs.html) that the Kafka consumers should use. This option is a JSON-formatted string. Certain values within this configuration are fixed, whereas the Ocient System provides other values with a default value that you can modify. |
| MAX\_MESSAGES | 100 | INTEGER | Optional.
In the `CONSUMER` syntax, the maximum number of messages to poll each time. |
| TIMEOUT | 1000 MILLISECONDS | TIME INTERVAL | Optional.
In the `CONSUMER` syntax, the operation timeout that controls how long the consume request waits for the response. The valid range is: 0 milliseconds to 1 hour. |
| FILENAME | `$"Records"[1].s3.object.key` corresponds to a `s3:ObjectCreated:Put` event. | SELECTOR | Optional.
In the `MESSAGE` syntax, defines the JSON selector for the filename of an incoming message in a monitor. The default value works for `s3:ObjectCreated:*` events. If you override this default configuration, you can parse custom JSON messages. The format must still adhere to S3 standards. For details, see [Amazon Simple Storage Service Event message structure](https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-content-structure.html). The message must be in the JSON format. If you specify this option, then you must specify the other two options in the `MESSAGE` syntax. |
| TIMESTAMP | `$"Records"[1]."eventTime"` corresponds to a `s3:ObjectCreated:Put` event. | SELECTOR | Optional.
In the `MESSAGE` syntax, defines the JSON selector for the last modification timestamp of the file of an incoming message in a monitor. The default value works for `s3:ObjectCreated:*` events. If you override this default configuration, you can parse custom JSON messages. The format must still adhere to S3 standards. For details, see [Amazon Simple Storage Service Event message structure](https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-content-structure.html). The message must be in the JSON format. If you specify this option, then you must specify the other two options in the `MESSAGE` syntax. |
| SIZE | `$"Records"[1].s3.object.size` corresponds to a `s3:ObjectCreated:Put` event. | SELECTOR | Optional.
In the `MESSAGE` syntax, defines the JSON selector for the file size of an incoming message in a monitor. The default value works for `s3:ObjectCreated:*` events. If you override this default configuration, you can parse custom JSON messages. The format must still adhere to S3 standards. For details, see [Amazon Simple Storage Service Event message structure](https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-content-structure.html). The message must be in the JSON format. If you specify this option, then you must specify the other two options in the `MESSAGE` syntax. |
The same Kafka `CONFIG` option override considerations apply. For details, see [KAFKA Source Options](#kafka-source-options).
### LOOKUP Options
You can optionally look up data in a table from an external database. You can include this table in the `SELECT` statement of the `CREATE PIPELINE` SQL statement and perform join operations on its columns. To use the `LOOKUP` keyword, specify the external source name `lookup_source`.
You can look up data in multiple external databases. In this case, use the `LOOKUP` keyword with the source name and corresponding options for each database.
You must provide the appropriate JDBC JAR file for the JDBC connection to external databases. For tables in the Ocient System, this JAR file is not needed.
The Ocient System executes the JDBC code as trusted code. Only provide trusted JAR files to the loading process. The `streamloader.extractorEngineParameters.configurationOption.engine.external.jdbc.jarRootDirectory` configuration parameter specifies the location of the JAR file. For details, see [Configuration Settings for Data Pipelines](/configuration-settings-for-data-pipelines).
| **Option Key** | **Default** | **Data Type** | **Description** |
| ------------------ | ----------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| CONNECTION\_TYPE | None | STRING | The type of connection. Only `'jdbc'` is supported. |
| CONNECTION\_STRING | None | STRING | The string for connection to the external database. For example: `'jdbc:sqlite:/path/to/file'` |
| LOOKUP\_SCHEMA | None | STRING | The schema of the table in the external database. |
| LOOKUP\_TABLE | None | STRING | The name of the table in the external database. |
| REFRESH\_PERIOD | 30 | TIME INTERVAL | Optional.
The time between lookup cache refreshes. |
| CONFIG | `NULL` | JSON-formatted STRING | Optional.
The JSON string that contains additional configuration options. For example: `'{"force_refresh_if_null": false}'`
Supported JSON keys are:
`force_refresh_if_null`, specified as a Boolean that defaults to `true`. When you set this value to `true`, the system triggers a lookup cache refresh for each value missing from the lookup table (to account for a concurrent load). This cache refresh can have a noticeable performance impact. As such, if you expect that some values cannot result in successful lookups, then set this key to the `false` value.
`load_timeout_seconds`, specified as a long integer with no default value. This option is the timeout, in seconds, for a lookup cache refresh.
`driver_class`, specified as a string with no default value. This option is the fully qualified JDBC driver class name. If you specify this option, the system throws an error when the system cannot find this driver or the driver cannot load into the process. If the JAR file for the connection is a JDBC 4 file, the system automatically loads the driver class. Otherwise, you must specify the fully qualified class name (from `Class::getName` in ) using this option, such as `'{"driver_class": "org.test.example.Driver"}'`. |
### EXTRACT Options
#### General Extract Options
You can specify these options on any of the allowed `FORMAT` types.
| **Option Key** | **Default** | **Data Type** | **Description** |
| ---------------------------- | ---------------------------------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| FORMAT | None | STRING | Specifies the format of the files to load. Supported values are: `delimited` `csv` `json` `binary` `asn.1` `parquet` `xml` |
| CHARSET\_NAME | Binary format: `ibm1047` All other formats: `utf-8` | STRING | Optional.
Specifies the character set for decoding data from the source records into character data. Use this character set when you load data into VARCHAR columns or when you apply `CHAR` transformation functions. Defaults to `utf-8` for all formats except BINARY, which defaults to `ibm1047`. You can configure the default value for `BINARY` formatted data using a SQL statement such as: `ALTER SYSTEM ALTER CONFIG SET 'sql.pipelineParameters.extract.binary.defaultCharset' = 'ibm1047'` |
| COLUMN\_DEFAULT\_IF\_NULL | `false` | BOOLEAN | Optional.
Specifies whether pipelines should load the column default value when the result of a series of transforms is NULL.
If you set this option to `false` (the default), the pipeline loads NULL values into columns.
If you set this option to `true`, the pipeline loads the defined default value of the column when the result of the execution of the transformation on the column is NULL. |
| NULL\_STRINGS | Delimited or CSV format: `['null', 'NULL']` JSON format: `[]` | ARRAY OF STRINGS | Optional.
Specifies string values that should represent a NULL value when extracted from the source records. Use this in `csv`, `delimited`, and `json` formats to convert specific values to NULL instead of requiring individual transform function calls to `NULL_IF` with those values. This option applies to source data immediately after extraction. If the result of transformations is one of these strings, you must use `NULL_IF` to transform to NULL with the specified string values. |
| TRIM\_WHITESPACE | `false` | BOOLEAN | Optional.
Specifies whether to trim whitespace from the beginning and end of each string field during extraction. In this case, whitespace is a space, tab, carriage return, or linefeed character.
If the trimmed field value matches one of the values specified by the `NULL_STRINGS` option, the system converts the value in the field to `NULL`. If you set this value to `true` and the `EMPTY_FIELD_AS_NULL` option to `true`, the system converts any field that contains only whitespace to `NULL`.
This option does not trim arrays of strings.
To trim elements in arrays, you can use the `TRIM` transform function or the `TRANSFORM` function with a Lambda expression that uses the `TRIM` function. |
| VALIDATE\_CHARACTERS | `false` | BOOLEAN | Optional.
Specifies whether to detect invalid characters based on the encoding type during extraction. If the system detects invalid characters, the system throws a file-level error for file loads or a record-level error for Kafka loads.
This option is not supported for ASN.1, , and binary formats. |
| REPLACE\_INVALID\_CHARACTERS | `false` | BOOLEAN | Optional.
Specifies whether to replace invalid characters based on the encoding type with the replacement character `U+FFFD`.
This option is not supported for ASN.1, Parquet, and binary formats. |
| REPLACEMENT\_CHARACTER | `�` | STRING | Optional.
Specifies the character that indicates invalid data when you set the REPLACE\_INVALID\_CHARACTERS option to `true`. The default value is the replacement character `U+FFFD`.
This option is not supported for ASN.1, Parquet, and binary formats. |
For ASN.1, , and Parquet extract options, the SCHEMA option is a `MAP` type with a `NULL` default value. This option is optionally specified depending on the format. SCHEMA specifies the syntax of options for schema retrieval.
#### ASN.1 Extract Options
You can specify these options for ASN.1 data record extraction (`FORMAT ASN.1`).
For details about ASN.1-formatted data, see [Load ASN.1 Data](/data-formats-for-data-pipelines#load-asn-1-data).
| **Option Key** | **Default** | **Data Type** | **Description** |
| -------------- | ----------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| URL | None | STRING | In the `SCHEMA` syntax, specify the URL to the ASN.1 schema file in the `.asn` format. |
| RECORD\_TYPE | None | STRING | In the `SCHEMA` syntax, specify the fully qualified name of the record type to parse. The name is the root-level ASN.1 type to extract from each DER-encoded record. (e.g., `Example.PersonnelRecord`) |
#### Avro Extract Options
You can specify these options for Avro data record extraction. The `SCHEMA` options are all optional for object container files (OCF).
For Kafka loads, the schema configuration must include either the `URL` option or the `INLINE` option, but not both.
For file-based loads, the schema configuration can include:
* Either the `INLINE` option or the `INFER_FROM` option, but not both of these options
* Neither the `INLINE` nor the `INFER_FROM` options
For details about loading Avro-formatted data, see [Load Avro Data](/data-formats-for-data-pipelines#load-avro-data).
| **Option Key** | **Default** | **Data Type** | **Description** |
| ------------------------------ | -------------------------------------------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| URL | None | STRING | The URL of the schema registry. |
| CONFIG | None | STRING | The configuration string that includes authentication for accessing the schema registry. |
| SUBJECT | `-value`, where `` is the name of the source Kafka topic | STRING | The custom subject for the schema registry. |
| SCHEMA\_REGISTRY\_ID\_LOCATION | `header_or_value` | STRING | For Kafka loads, the location to store the schema identifier for the schema registry. Supported values are:
`'header_or_value'` — Specifies that the system searches for the schema Universally Unique IDentifier (UUID) in the `__value_schema_id` Kafka header. If the system finds the UUID, the system uses that identifier. Otherwise, the system derives the identifier from the starting bytes of the Kafka message value.
`'value'` — Specifies that the system derives a schema identifier or UUID from the starting bytes of the Kafka message value.
`'none'` — For inline schemas, specifies that there is no embedded schema identifier to skip. |
| INLINE | None | STRING | The JSON specification of the schema declaration as a string. Specify either a JSON string or object. |
| INFER\_FROM | None | STRING | For file-based loads, specifies that the system infers the schema from files. Supported value is: `'sample_file'` — Use a sample file. |
#### BINARY Extract Options
You can apply these options to binary data record extraction (`FORMAT BINARY`).
For details about BINARY-formatted data, see [Load Binary Data](/data-formats-for-data-pipelines#load-binary-data).
The general option `CHARSET_NAME` has a different default value for `FORMAT BINARY`.
| **Option Key** | **Default** | **Data Type** | **Description** |
| ------------------- | ----------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| RECORD\_LENGTH | None | INTEGER | Specifies the fixed size in bytes of each record in the source data. The Ocient System splits the binary data into binary chunks according to this length value and processes them individually. |
| ENDIANNESS | `big` | STRING | Optional.
Specifies the endianness used to interpret multi-byte sequences in various transforms of binary data. Accepted values are `‘big'` and `'little'`. |
| AUTO\_TRIM\_PADDING | `true` | BOOL | Optional.
Determines if padding characters should be trimmed after decoding the binary data into string data. If you set this option to `TRUE`, the Ocient System trims all instances of the `PADDING_CHARACTER` value from the end of a string after the system decodes the string from `BINARY` type. |
| PADDING\_CHARACTER | (space) | STRING | Optional.
The padding character from the string after the system decodes the string from `BINARY` type. You can change the default padding character for `BINARY` formatted data using a SQL statement such as: `ALTER SYSTEM ALTER CONFIG SET 'sql.pipelineParameters.extract.binaryFormat.defaultPaddingCharacter' = '*'` |
The Ocient System trims the default padding character of a space from the end of the text data in binary data.
#### **Delimited and CSV** Extract Options
You can specify these options for delimited and CSV format data record extraction (`FORMAT DELIMITED` or `FORMAT CSV` data formats, which are aliases).
For details about working with delimited and CSV data, see [Load Delimited and CSV Data](/data-formats-for-data-pipelines#load-delimited-and-csv-data).
| **Option Key** | **Default** | **Data Type** | **Description** |
| ------------------------------- | ---------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| FIELD\_DELIMITER | `,` | STRING or ARRAY OF STRINGS | Optional.
Specifies a character or list of possible characters for delimiting fields. The default value sets the field delimiter to only a comma. The value must be one byte. The Ocient System automatically interprets the values you specify as C-style escaped strings. This means you do not need to specify an escape string (`e'some value'`) is not required to specify control characters. This differs from the default string behavior in Ocient. For details, see [String Literals and Escape Sequences](/data-query-language-dql-statement-reference#string-literals-and-escape-sequences). `FIELD_DELIMITER` and `FIELD_DELIMITERS` are aliases. **Examples:** Use a tab character: `FIELD_DELIMITER = '\t'` Use a pipe character: `FIELD_DELIMITER = '\|'` Use either a pipe or a comma character: `FIELD_DELIMITER = [',', '\|']` |
| RECORD\_DELIMITER | `['\r\n', '\n']` | STRING or ARRAY OF STRINGS | Optional.
Specifies the string or an array of strings for delimiting records. The file is split into individual records using this character during processing. Common values include `'\r\n'` and `'\n'`. The value must be one or two bytes. The Ocient System automatically interprets the values you specify as C-style escaped strings. An escape string (`e'some value'`) is not required to specify control characters. This differs from the default strings behavior in Ocient. The system chooses the first specified delimiter and uses that delimiter for the rest of the data. Data with mixed delimiters is not supported. For details, see [String Literals and Escape Sequences](/data-query-language-dql-statement-reference). `RECORD_DELIMITER` and `RECORD_DELIMITERS` are aliases. **Examples:** Use a linefeed character: `RECORD_DELIMITER = '\n'` Use a carriage return and linefeed character sequence: `RECORD_DELIMITER = '\r\n'` |
| NUM\_HEADER\_LINES | `0` | INTEGER | Optional.
Specifies the number of header lines, typically 0 or 1. The Ocient System skips this number of lines and does not load them as data during file processing. Use this option when your data includes a row of header values. |
| NUM\_FOOTER\_LINES | `0` | INTEGER | Optional.
Specifies the number of footer lines, typically 0 or 1. The Ocient System skips this number of lines starting from the end of the file and does not load them as data during file processing. Use this option when your data includes a row of footer values. |
| OPEN\_ARRAY | `[` | STRING | Optional.
Specifies the character that indicates the start of an array in a `csv` or `delimited` field. Use this option to parse array data types. Specify the `CLOSE_ARRAY` option also when using this option. Set this option to NULL or `''` to turn off the detection of these control characters. If you set this option to either of these characters, the system also turns off the detection of these characters for the `CLOSE_ARRAY` option. **Example:** Convert source data such as `val1,"[1,2,3]",val2` to an array when referenced as `$2[]`. `OPEN_ARRAY '['` `CLOSE_ARRAY ']'` `ARRAY_ELEMENT_DELIMITER ','` |
| CLOSE\_ARRAY | `]` | STRING | Optional.
Specifies the character that indicates the end of an array in a `csv` or `delimited` field. Use this option to parse array data types. Specify the `OPEN_ARRAY` option also when using this option. Set this option to NULL or `''` to turn off the detection of these control characters. If you set this option to either of these characters, the system also turns off the detection of these characters for the `OPEN_ARRAY` option. **Example:** Convert source data such as `val1,"{1,2,3}",val2` to an array when referenced as `$2[]`. `CLOSE_ARRAY '}'` `OPEN_ARRAY '{'` `ARRAY_ELEMENT_DELIMITER ','` |
| ARRAY\_ELEMENT\_DELIMITER | `,` | STRING | Optional.
Specifies the character that separates values in an array within a `csv` or `delimited` field. Use this option to parse array data types. Set this option to NULL or `''` to turn off the detection of these control characters. **Example:** Convert source data such as `val1,"[1;2;3]",val2` to an array when referenced as `$2[]`. `ARRAY_ELEMENT_DELIMITER = ';'` |
| OPEN\_OBJECT | `{` | STRING | Optional.
Specifies the character that indicates the start of a tuple in a field. Use this option to parse tuple data types. Specify the `CLOSE_OBJECT` option also when using this option. Set this option to NULL or `''` to turn off the detection of these control characters. If you set this option to either of these characters, the system also turns off the detection of these characters for the `CLOSE_OBJECT` option. |
| CLOSE\_OBJECT | `}` | STRING | Optional.
Specifies the character that indicates the end of a tuple in a field. Use this option to parse tuple data types. Specify the `OPEN_OBJECT` option also when using this option. Set this option to NULL or `''` to turn off the detection of these control characters. If you set this option to either of these characters, the system also turns off the detection of these characters for the `OPEN_OBJECT` option. |
| EMPTY\_FIELD\_AS\_NULL | `true` | BOOLEAN | Optional.
Specifies whether the Ocient System should extract an empty source field as NULL or a missing value. When this option is set to `true`, the Ocient System treats empty fields as NULL. Otherwise, the system treats fields as a missing value. For string-type fields, a missing value is equivalent to an empty string. Define an empty field as two consecutive delimiters (e.g., the second field is empty in `abc,,xyz`). If a field is explicitly an empty string as indicated by quote characters, the Ocient System treats the field as an empty string, not an empty field (e.g., the second field is an empty string in `abc,"",xyz`). The `CHAR($1)` transformation function handles both NULLs and empty strings and passes them through. ⚠️ Beware that the `NULL_IF($1, '')` transformation function directly loads a NULL for both NULLs \*and \*missing values. This transformation can override the behavior of `EMPTY_FIELD_AS_NULL`. |
| FIELD\_OPTIONALLY\_ENCLOSED\_BY | `"` | STRING | Optional.
Also known as the “quote character,” this option specifies the character for optionally enclosing fields. Fields enclosed by this character can include delimiters, the enclosure character, or the escape character. Set this option to NULL or `''` to turn off the detection of these control characters. **Examples:** Use a double quote character: `FIELD_OPTIONALLY_ENCLOSED_BY = '"'` Use a single quote character: `FIELD_OPTIONALLY_ENCLOSED_BY = ''''` |
| ESCAPE\_CHAR | `"` | STRING | Optional.
Specifies the escape character within fields enclosed by the `FIELD_OPTIONALLY_ENCLOSED_BY` option. Use this option to escape the enclosure character or escape character. Set this option to NULL or `''` to turn off the detection of these control characters. **Examples:** Use a double quote as the escape character. `ESCAPE_CHAR = '"'` Use a single quote as the escape character. When you specify the escape character, you often have to use an escape sequence. This action follows standard SQL rules. `ESCAPE_CHAR = ''''` |
| SKIP\_EMPTY\_LINES | `false` | BOOLEAN | Optional.
Specifies whether or not to skip empty lines. |
| COMMENT\_CHAR | `NULL` | STRING | Optional.
Specifies the character used to comment out a record in the source file. The load skips records where the first character of a record is equal to this character. Set this option to NULL or `''` to turn off the detection of these control characters. Example: `COMMENT_CHAR '#'` |
| HEADERS | `NULL` | ARRAY OF STRINGS | Optional.
Specifies the header labels associated with each column in a delimited file. This array of values corresponds to the columns in order from left to right. Use these labels in the `CREATE PIPELINE SELECT` SQL statement to refer to column values. For example, if you specify `HEADERS ['col1', 'col2', col3']`, you can refer to the first column as `$"col1"` instead of `$1` in the `SELECT` statement. |
| STRIP\_ARRAY\_ELEMENT\_QUOTES | `false` | BOOLEAN | Optional.
When you set this option to `true`, the system removes quote characters from array elements, so that, for example, `["str"]` becomes `[str]`. |
| STRIP\_FIELD\_QUOTES | `true` | BOOLEAN | Optional.
When you set this option to `true`, the system removes quote characters from the string, so that, for example, `"str"` becomes `str`. |
| TRIM\_ARRAY\_ELEMENTS | `false` | BOOLEAN | Optional.
When you set this option to `true`, the system removes whitespace characters from the array elements, so that, for example, `" str"` becomes `"str"`. |
#### JSON Extract Options
No options exist for JSON data record extraction (`FORMAT JSON`).
For details about JSON-formatted data, see [Load JSON Data](/data-formats-for-data-pipelines#load-json-data).
#### PARQUET Extract Options
You can specify these options for Parquet data record extraction (`FORMAT ``PARQUET`).
For details about Parquet-formatted data, see [Load Parquet Data](/data-formats-for-data-pipelines#load-parquet-data).
When you use the `FORMAT PARQUET` option with an AWS S3 Source, the `ENDPOINT` option is required.
| **Option Key** | **Default** | **Data Type** | **Description** |
| ------------------ | ------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SCHEMA INFER\_FROM | `sample_file` | STRING | In the `SCHEMA` syntax, specify how to infer the Parquet schema. The supported value is: `sample_file` — Infer from a random file.
**Example:** `SCHEMA (INFER_FROM` `sample_file)` |
#### XML Extract Options
No options exist for the XML format extraction (`FORMAT XML`).
For details about XML-formatted data, see [Load XML Data](/data-formats-for-data-pipelines#load-xml-data).
### Bad Data Targets
Bad data represents records that the Ocient System could not load due to errors in the transformations or invalid data in the source records. You can provide options for a bad data target that the Ocient System uses during pipeline execution to capture the records that are not loaded. The original bytes that the pipeline tried to load are captured in the bad data target along with the metadata about the error, such as the error message or source.
Kafka is the only supported bad data target.
#### Kafka Bad Data Target
When you use Kafka as a bad data target, the Ocient System produces the original bytes of the source record into the Kafka topic of your choice. The Ocient System includes the metadata about the record in the header of the record as it is sent to Kafka. You can configure the Kafka topic on your Kafka Brokers using the retention and partition settings of your choice.
In the event that the Kafka Broker is unreachable when the Ocient System attempts to produce a bad data record to the bad data target, the system logs an error on the Loader Node, and the pipeline continues.
**Example**
This example `CREATE PIPELINE` SQL statement snippet contains a bad data target definition using the `BAD_DATA_TARGET` option.
```sql SQL theme={null}
CREATE PIPELINE ...
BAD_DATA_TARGET
KAFKA
TOPIC 'orders_errors'
BOOTSTRAP_SERVERS '111.11.111.1:9092,111.11.111.2:9092'
CONFIG '{"compression.type": "gzip"}'
SOURCE
...
EXTRACT
...
INTO public.orders
SELECT
$order.billing.name as username,
$order.subtotal as subtotal,
...
```
#### Kafka Bad Data Target Options
| **Option Key** | **Default** | **Data Type** | **Description** |
| ------------------ | ---------------------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BOOTSTRAP\_SERVERS | None | STRING | A comma-delimited list of `IP:port` pairs that contain the IP addresses of the Kafka Brokers and the associated port number. **Example:** `BOOTSTRAP_SERVERS = '111.11.111.1:9092,111.11.111.2:9092'` |
| TOPIC | None | STRING | The name of the Kafka topic where the Ocient System should produce bad data records. |
| CONFIG | `'{` `"compression.type": "none"` `}'` | JSON-formatted STRING | Optional.
The [producer configuration](https://docs.confluent.io/platform/current/installation/configuration/producer-configs.html) that the Kafka producer should use. |
### **Advanced Pipeline Tuning Options**
You can use pipeline tuning options to control the parallelism or batching dynamics of your pipelines. This tuning can throttle the resources used on a pipeline or increase parallel processing across Loader Nodes. These options are advanced settings that might require a detailed understanding of the underlying mechanics of the loading infrastructure in the Ocient System to employ. Due to the inherent nature of each source type, the behavior of these options can differ between file-based and Kafka-based loads. All these options are optional.
\| **Option Key** | **Default** | **Data Type** | **Description** |
\| --- | --- | --- | --- | --- |
\| CORES | The maximum number of CPU cores available on each Loader Node. | INTEGER | Maximum number of processing threads that the Ocient System uses during execution on each Loader Node. The system creates this number of threads on each Loader Node. The Ocient System automatically determines the default value by finding the number of cores of a Loader Node. You can use this option for performance tuning. The calculation for maximum parallelism of a pipeline is: `number_of_loaders * CORES`. **About Kafka Partitions and Parallelism** For Kafka Loads, this option determines the number of Kafka Consumers created on each Loader Node. For Kafka Pipelines, the recommendation is that `number_of_loaders * CORES` equals the number of Kafka topic partitions. If this number exceeds the number of Kafka topic partitions, the work might spread unevenly across Loader Nodes. If this number is less than the number of Kafka topic partitions, some Kafka Consumers might receive uneven amounts of work. In this case, use a value for `number_of_loaders * CORES` that is an even divisor of the number of Kafka topic partitions to avoid a skew in the rates of processing across partitions. |
\| PARTITIONS | Equal to the value of CORES. | INTEGER | Specifies the number of partitions over which to split the file list. Not applicable to Kafka loads. The Ocient System automatically sets a default value based on the configured value for the `CORES` option. You can use this option for performance tuning. The number of partitions determines how many buckets of work the Ocient System generates for each batch of files processed on a Loader Node. The pipeline processes this number of partitions in parallel using the specified number of cores. If you specify fewer partitions than cores, some cores are not fully utilized, and resources are wasted. If you specify more partitions than cores, the Ocient System divides partitions in a round-robin fashion over the available cores. |
\| BATCH\_SIZE | A dynamic value, determined by the Ocient System for each pipeline to maximize performance. | INTEGER | Number of rows in the batch to load at one time. The Ocient System automatically calculates a dynamic value depending on the table columns and the utilization of internal buffers to transfer records to the database backend. You can use this option to turn off the dynamic adjustments for performance tuning. ⚠️ Only change this setting in rare cases where loading performance is slower than expected, and you have a large record size. If this setting is improperly set, pipelines might fail with out-of-memory exceptions. You can configure the default value (for the batch payload target) using a SQL statement such as: `ALTER SYSTEM ALTER CONFIG SET 'streamloader.extractorEngineParameters.configurationOption.osc.batch.payload.target' '65536'` |
\| RECORD\_NUMBER\_FORMAT | For file loads that do not use the [EXPLODE\_OUTER](/special-data-pipeline-transformation-functions#explode_outer) function, the default is \`\[19, 45, 0]\`. For Kafka loads that do not use the \`EXPLODE\_OUTER\` function, the default is \`\[0, 64, 0]\`. For loads that use the \`EXPLODE\_OUTER\` function, the default is the specified load-type-specific default value with 13 subtracted from the record index bits. The system adds these bits to the bits for rows within a record. For example, the default for file loads that use this function is \`\[19, 32, 13]\`. | ARRAY | The 64-bit record number for each record of the load. This number uniquely identifies a row within its partition. The format is an array with three values in the format\`\[, , ]\` The file index bits \`\` value is the number of bits used to represent the file index within a partition. The record index bits \`\` value is the number of bits used to represent the record index within a file. The rows per record index bits \`\` is the number of bits used to represent the row within a record. The system uses this value with the \`EXPLODE\_OUTER\` function. These three values must sum to 64. \*\*Example\*\* \`RECORD\_NUMBER\_FORMAT= \[10, 54, 0]\` Set the number of file index bits to \`10\` and the number of record index bits to \`54\`, allowing up to 2^10 files and 2^54 records per file. The system does not support the \`EXPLODE\_OUTER\` function in this configuration because the rows per record index bits are \`0\`. | |
## DROP PIPELINE
`DROP PIPELINE` removes an existing pipeline in the current database. You cannot remove a pipeline that is running.
You must have the DROP privilege on the pipeline to execute this SQL statement. For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
When you drop a pipeline, the Ocient System also removes the associated system catalog information, such as pipeline errors, events, files, partitions, and metrics.
**Syntax**
```sql SQL theme={null}
DROP PIPELINE [ IF EXISTS ] pipeline_name [, ...]
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pipeline_name` | string | The name of the specified pipeline to remove. You can drop multiple pipelines by specifying additional pipeline names, separated by commas. |
**Examples**
**Remove Existing Data Pipeline**
Remove an existing pipeline named `ad_data_pipeline`.
```sql SQL theme={null}
DROP PIPELINE ad_data_pipeline;
```
**Remove Existing Data Pipeline by Checking for Existence**
Remove an existing pipeline named `ad_data_pipeline` or return a warning if the Ocient System does not find the pipeline in the database.
```sql SQL theme={null}
DROP PIPELINE IF EXISTS ad_data_pipeline;
```
## PREVIEW PIPELINE
`PREVIEW PIPELINE` enables you to view the results of loading data for a specific `CREATE PIPELINE` SQL statement without creating a whole data pipeline and without storing those results in the target table. Using this SQL statement, you can iterate quickly and modify the syntax as needed to achieve your expected results. After you confirm your expected results, you can use the same syntax in the body of the `CREATE PIPELINE` statement with the appropriate source.
A table must exist in the database to serve as the target of your `PREVIEW PIPELINE` statement. This table ensures the pipeline matches the column types of the target table. However, the execution of this statement does not load data into the target table.
### Preview Sources
The `SOURCE INLINE` source type is available only for the `PREVIEW PIPELINE` SQL statement. You cannot create a data pipeline with inline source data. The inline source data limit is 1,000 rows.
Other source types defined in the `CREATE PIPELINE` statement, `S3`, `KAFKA`, and `FILESYSTEM`, are compatible with the `PREVIEW PIPELINE` statement. The extract options vary by the source type to mirror the `CREATE PIPELINE` statement. The database returns 10 records by default.
### Preview Error Handling
Pipeline-level errors cause the `PREVIEW PIPELINE` SQL statement to fail. The Ocient System returns an error and no result set. However, the Ocient System accumulates record-level errors that occur during the execution of this statement in a single warning that the system returns along with the result set. Each line of the warning describes a record-level error in human-readable form or as a JSON blob, depending on the value of the `SHOW_ERRORS_AS_JSON` option. Rows or columns that encounter record-level errors have `NULL` values in the result set.
### Preview Limitations
Limitations of this SQL statement are:
* Before executing a `PREVIEW PIPELINE` SQL statement, you must create a table for the Ocient System to have context for the preview.
* The maximum number of rows a `PREVIEW PIPELINE` SQL statement can return is 1,000 rows.
* The `COLUMN_DEFAULT_IF_NULL` option from the `CREATE PIPELINE` SQL statement has no effect on the `PREVIEW PIPELINE` SQL statement.
* The `PREVIEW PIPELINE` SQL statement does not honor the assignment of a service class based on text matching.
* These source options are not supported:
* `START_FILENAME`
* `END_FILENAME`
* When you execute two duplicate `PREVIEW PIPELINE` statements for a specific Kafka topic, the two statements share a consumer group. If the topic is small, one or both of the result sets might only be a partial result.
* For multiple tables, you can preview only one table at a time. You must specify the name of the table you want to preview using the `FOR` keyword.
* Previewing a continuous data pipeline is not supported.
**Syntax**
```sql SQL theme={null}
PREVIEW PIPELINE pipeline_name
[ MODE mode ]
[ SHOW_ERRORS_AS_JSON show_errors_as_json ]
SOURCE [ INLINE ] (inline_string | | | )
[ LIMIT limit ]
EXTRACT
FORMAT csv
RECORD_DELIMITER record_delimiter
FIELD_DELIMITERS ['delim1', 'delim2', ...]
[ INTERMEDIATE_VALUES intermediate_values ]
[ INSERT ] INTO created_tablename
SELECT
preview_column_formula AS preview_column_name, ...
[ WHERE filter_expression ]
[ [ INSERT ] INTO created_tablename_n
SELECT
preview_column_formula AS preview_column_name, ...
[ WHERE filter_expression ] ] [ ,... ]
[ FOR created_tablename_n ]
```
Though this syntax shows the CSV format, you can also use the `PREVIEW PIPELINE` statement with the other formats.
| **Parameter** | **Data** **Type** | **Description** |
| ------------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pipeline_name` | string | The name of the specified data pipeline for the preview. |
| `created_tablename` | identifier | The identifier for the name of the table that you create before executing the `PREVIEW PIPELINE` SQL statement. |
| `created_tablename_n` | identifier | For multiple tables, the identifier for the name of another table that you create before executing the `PREVIEW PIPELINE` SQL statement. Use the `FOR` keyword to specify which table content to preview. |
| `preview_column_formula` | identifier | The identifier for the formula of the data to load. For example, for the data in the first field of the inline source, use `$1`.
If you need to add a transformation, you can use functions to transform data, such as `CONCAT($1, $2)`, to load the concatenation of the first two fields in the inline source data. |
| `preview_column_name` | identifier | The name of the column in the target table. |
**SQL Statement Options**
| **Option Key** | **Default** | **Data** **Type** | **Description** |
| ---------------------- | ------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SOURCE INLINE | Required | STRING | The string that contains data for the preview of the data pipeline load. For example, source data can be `'oci,ent,ocient\|ware,house,warehouse'`, where `\|` is the record delimiter and `,` is the field delimiter. For special characters, such as `\t`, use an escape sequence such as `e'oci,ent,oci\tent\|ware,house,ware\thouse'`.
This option supports these text-based formats: CSV, JSON, and XML. |
| MODE | `'transform'` | STRING | Indicates whether to perform a validation of the PREVIEW PIPELINE SQL statement.
Valid values are: `'validate'` and `'transform'`.
Set this option to `'validate'` for checking that the creation of the data pipeline succeeds. If the pipeline is valid, the statement produces no output; otherwise, it returns an error.
Set this option to `'transform'` to retrieve a preview of the results of the pipeline. |
| SHOW\_ERRORS\_AS\_JSON | `false` | BOOLEAN | Indicates whether to show errors. Values are `true` or `false`. If the value is `true`, the Ocient System returns record-level errors as JSON blobs rather than human-readable messages. |
| LIMIT | 10 | INTEGER | The number of rows, specified as an integer, to return in the preview results for sources with many rows. The default value is 10 rows. |
| INTERMEDIATE\_VALUES | `false` | BOOLEAN | Indicates whether to capture intermediate values during a transformation sequence. Values are `true` or `false`. If the value is `true`, the Ocient System appends an extra column to the result set. Each value in the column contains a JSON blob that describes the intermediate values processed for each column after each transformation. |
You must specify at least one column name in the `SELECT` part of the syntax. The name of the specified column must match the name of the column in the created table. The number of columns in the `SELECT` part can be less than those in the created table.
For definitions of other extract options, see the `CREATE PIPELINE` SQL statement options in [CREATE PIPELINE](#create-pipeline).
**Examples**
**Preview Pipeline Using CSV Format**
Preview the load of two rows of data. First, create a table to serve as the context for the load. The `previewload` table contains three columns with these data types: string, integer, and Boolean.
```sql SQL theme={null}
CREATE TABLE previewload (col1 VARCHAR, col2 INT, col3 BOOLEAN);
```
Create the preview pipeline `testpipeline` with this data: `'hello,2,true|bye,3,false'`. Specify the CSV extract format, `|` record delimiter, and the `,` field delimiter. Load the data without transformation.
```sql SQL theme={null}
PREVIEW PIPELINE testpipeline
SOURCE INLINE 'hello,2,true|bye,3,false'
EXTRACT
FORMAT CSV
RECORD_DELIMITER '|'
FIELD_DELIMITERS [',']
INTO previewload
SELECT
$1 AS col1,
$2 AS col2,
$3 AS col3;
```
## *Output*
```text Text theme={null}
col1 col2 col3
\--------------------------------------------------------------
hello 2 true
bye 3 false
Fetched 2 rows
```
Delete the `previewload` table.
```sql SQL theme={null}
DROP TABLE previewload;
```
**Preview Pipeline Using CSV Format with Escape Characters**
Preview the load of two rows of data. First, create a table to serve as the context for the load. The `previewload` table contains three columns with these data types: string, integer, and Boolean.
```sql SQL theme={null}
CREATE TABLE previewload (col1 VARCHAR, col2 INT, col3 BOOLEAN);
```
Create the preview pipeline `testpipeline` with this data: `'hello\tworld,2,true|bye\tworld,3,false'`. Specify the CSV extract format, `|` record delimiter, and `,` field delimiter. Load the data without transformation. In this case, the data contains the special character `\t`. You must escape the character by using the escape sequence `e`.
```sql SQL theme={null}
PREVIEW PIPELINE testpipeline
SOURCE INLINE e'hello\tworld,2,true|bye\tworld,3,false'
EXTRACT
FORMAT CSV
RECORD_DELIMITER '|'
FIELD_DELIMITERS [',']
INTO previewload
SELECT
$1 AS col1,
$2 AS col2,
$3 AS col3;
```
## *Output*
```text Text theme={null}
col1 col2 col3
\--------------------------------------------------------------
hello world 2 true
bye world 3 false
Fetched 2 rows
```
Delete the `previewload` table.
```sql SQL theme={null}
DROP TABLE previewload;
```
**Preview Pipeline Using CSV Format with Transformation**
Create a table to serve as the context for the load. The `previewload` table contains three string columns.
```sql SQL theme={null}
CREATE TABLE previewload (col1 VARCHAR, col2 VARCHAR, col3 VARCHAR);
```
Create the preview pipeline `testpipeline` with this data: `'hello,world|bye,world'`. Specify the CSV extract format, `|` record delimiter, and the `,` field delimiter. Load the data with a transformation to concatenate the two strings and return the result in the third column.
```sql SQL theme={null}
PREVIEW PIPELINE testpipeline
SOURCE INLINE 'hello,world|bye,world'
EXTRACT
FORMAT CSV
RECORD_DELIMITER '|'
FIELD_DELIMITERS [',']
INTO previewload
SELECT
$1 AS col1,
$2 AS col2,
CONCAT($1,$2) AS col3;
```
## *Output*
```text Text theme={null}
col1 col2 col3
\---------------------------------------------------------------------------------------------------------------------------------------
hello world helloworld
bye world byeworld
Fetched 2 rows
```
The third column contains the concatenated result of the first two columns.
Delete the `previewload` table.
```sql SQL theme={null}
DROP TABLE previewload;
```
**Preview Pipeline Using the Kafka Source**
Create the `previewload` table with these columns:
* `id` — Non-NULL integer
* `salut` — Non-NULL string
* `name` — Non-NULL string
* `surname` — Non-NULL string
* `zipcode` — Non-NULL integer
* `age` — Non-NULL integer
* `rank` — Non-NULL integer
```sql SQL theme={null}
CREATE TABLE previewload (
id INT NOT NULL,
salut VARCHAR(3) NOT NULL,
name VARCHAR(10) NOT NULL,
surname VARCHAR(10) NOT NULL,
zipcode INT NOT NULL,
age INT NOT NULL,
rank INT NOT NULL);
```
Create the preview pipeline `test_small_kafka_simple_csv`. Specify the `ddl_csv` topic. Indicate that the Kafka consumer should not write its durably-made record offsets to the Kafka Broker by using the `WRITE_OFFSETS` option set to `false`. Specify the bootstrap server as `servername:0000` and configuration options as `"auto.offset.reset": "earliest" `by using the `BOOTSTRAP_SERVERS` and `CONFIG` options, respectively. Limit the returned results to three rows by using the `LIMIT` option. Specify the CSV extract format and `\n` record delimiter by using the `FORMAT` and `RECORD_DELIMITER` extract options, respectively.
```sql SQL theme={null}
PREVIEW PIPELINE test_small_kafka_simple_csv
SOURCE KAFKA
TOPIC 'ddl_csv'
WRITE_OFFSETS false
BOOTSTRAP_SERVERS 'servername:0000'
CONFIG '{"auto.offset.reset": "earliest"}'
LIMIT 3
EXTRACT
FORMAT csv
RECORD_DELIMITER '\n'
INTO previewload
SELECT
INT($1) AS id,
CHAR($2) AS salut,
CHAR($3) AS name,
CHAR($4) AS surname,
INT($5) AS zipcode,
INT($6) AS age,
INT($7) AS rank;
```
***
```text Text theme={null}
id salut name surname zipcode age rank
\-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
105 Mr Jmhsuxofspx Uaofgayjugb 85573 29 2
101 Mr Ijmmtbddkyh Yqbxqnkgidp 52393 43 1
109 Mr Bigohpwfwmr Qcxgakpkoeu 74420 1 3
Fetched 3 rows
```
## START PIPELINE
`START PIPELINE` begins the execution of the specified data pipeline that extracts data and loads it into the target tables specified by the `CREATE PIPELINE` SQL statement.
When you execute the `START PIPELINE` SQL statement, the Ocient System creates a static list of files in the `sys.pipeline_files` system catalog table and marks them with the `PENDING` status. After the system assigns a file to an underlying task, the system marks the file as `QUEUED`. After the system verifies that the file exists, the system marks the file as `LOADING` to signify that a Loader Node has started reading the source data. Finally, upon successfully loading the file, the system transitions the status of the file to the terminal status `LOADED`.
A Kafka pipeline never enters the `COMPLETED` state in the `information_schema.pipeline_status` view. Instead, the pipeline remains running after you start the pipeline until you stop it or the pipeline reaches the specified error limit using the `ERROR LIMIT` option.
You must have the EXECUTE privilege on the pipeline and the INSERT privilege on any table that is a target in the pipeline. For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
**Syntax**
```sql SQL theme={null}
START PIPELINE pipeline_name
[ ERROR
[ LIMIT ]
[ FILE_ERROR (FAIL | SKIP_MISSING_FILE | TOLERATE) ] ]
[ USING LOADERS ]
[ ON COMPLETION (NO_FLUSH | FLUSH_AND_WAIT | FLUSH_AND_RETURN) ]
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------- | ----------------- | ---------------------------------------- |
| `pipeline_name` | string | The name of the specified data pipeline. |
**SQL Statement Options**
| **Option Key** | **Default** | **Data Type** | **Description** |
| ---------------------------------- | ----------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ERROR LIMIT `` | 0 | INTEGER | Error log option that determines the number of record-level errors that can occur during the execution of a pipeline that the load tolerates before the whole pipeline execution fails. `` is a number greater than or equal to -1. When you set `` to -1, the load tolerates an unlimited number of record-level errors. By default, continuous pipelines tolerate an unlimited number of record-level errors, whereas batch pipelines tolerate zero errors.
With multiple target tables, record-level errors are specific to a table. For example, if a transformation for loading one table succeeds but another transformation for loading another table fails, the row corresponding to the successful transformation loads to the first table but not the other. |
| ERROR FILE\_ERROR `` | `FAIL` | STRING | For pipelines that load data from S3 or local file sources, this error configuration option determines how to treat unrecoverable file-level errors. Examples of unrecoverable file-level errors are:
The file is listed when the pipeline starts, but is missing later during the load.
The Gzip file is corrupted and cannot be decompressed.
The file cannot be downloaded from the source.
Record-level error that is not tolerable occurs when tokenizing or transforming data in the file.
`` can be one of these keywords: `FAIL` — Fail the whole pipeline because of a file-level error. `SKIP_MISSING_FILE` — Only tolerate errors that occur due to missing files. If a file exists in the list when the pipeline starts but is missing later during the load, skip the file and continue with the next file. `TOLERATE` — Tolerate all unrecoverable file-level errors. In this mode, the load also tolerates an unlimited number of record-level errors. The `FAILED`, `SKIPPED`, and `LOADED_WITH_ERRORS` file statuses appear in the `sys.pipeline_files` system catalog tables, respectively, and indicate how the pipeline handled the file error. |
| USING LOADERS `loader_names` | `NULL` | LIST OF STRINGS | Specify one or more names of Loader Nodes as a comma-separated list for executing the `START PIPELINE` SQL statement. If you do not use this option, the Ocient System uses all of the Loader Nodes that are active to execute the pipeline. You can find node names in the `sys.nodes` system catalog table. |
| ON COMPLETION `` | `NO_FLUSH` | STRING | Completion type option that specifies the behavior when the pipeline finishes loading. This option determines when the remaining pages are converted into Segments. `NO_FLUSH` — Do not force a flush of pages. Rely on watermarks and timeouts to trigger final conversion to Segments. `FLUSH_AND_WAIT` — Trigger a flush of pages, initiating final conversion to Segments. The pipeline blocks and waits for the conversion to Segments to complete before marking the pipeline as `COMPLETED`. `FLUSH_AND_RETURN` — Trigger a flush of pages, initiating the final conversion to Segments. The Ocient System marks the pipeline as `COMPLETED` immediately following the flush without waiting for conversion to Segments to complete. |
For the query to execute successfully, the specified node names must identify nodes that have:
* `ACTIVE` operational status
* `streamloader` role
When you execute the `START PIPELINE` SQL statement, the Ocient System creates a static list of files only for batch pipelines and a dynamic list for continuous pipelines in the `sys.pipeline_files` system catalog table.
**Examples**
Start an existing pipeline named `ad_data_pipeline` with default settings.
```sql SQL theme={null}
START PIPELINE ad_data_pipeline;
```
Start an existing pipeline named `ad_data_pipeline` with error tolerance (tolerate 10 errors before aborting the pipeline). For details about error tolerance, see [Error Tolerance in Data Pipelines](/error-tolerance-in-data-pipelines).
```sql SQL theme={null}
START PIPELINE ad_data_pipeline
ERROR LIMIT 10;
```
Data pipelines log a message for each pipeline error to the `sys.pipeline_errors` system catalog table, even if you do not specify the ERROR option. Use `BAD_DATA_TARGET` settings to capture the original source data.
Start an existing pipeline named `ad_data_pipeline` using the Loader Node named `stream-loader1`.
```sql SQL theme={null}
START PIPELINE ad_data_pipeline
USING LOADERS "stream-loader1";
```
To resume a pipeline with file loading, see [Data Pipeline Behavior Considerations](/data-pipeline-behavior-considerations).
To restart a Kafka data pipeline, see [Data Pipeline Behavior Considerations](/data-pipeline-behavior-considerations).
For pipeline dependencies, see [Data Pipeline Behavior Considerations](/data-pipeline-behavior-considerations).
## STOP PIPELINE
`STOP PIPELINE` stops the execution of the pipeline and its associated tasks. After you stop a pipeline, you can execute the `START PIPELINE` SQL statement on the pipeline to run the pipeline again. Regardless, the load deduplicates any records previously loaded in the same pipeline.
You must have the EXECUTE privilege on the pipeline to execute this SQL statement. For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
**Syntax**
```sql SQL theme={null}
STOP PIPELINE pipeline_name
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------- | ----------------- | ---------------------------------------- |
| `pipeline_name` | string | The name of the specified data pipeline. |
**Example**
Stop an existing pipeline named `ad_data_pipeline`.
```sql SQL theme={null}
STOP PIPELINE ad_data_pipeline;
```
You can see the status of the parent tasks in the `sys.tasks` system catalog table and see the status of the child tasks in the `sys.subtasks` system catalog table.
## ALTER PIPELINE
`ALTER PIPELINE` evolves the schema of the data pipeline in the `SELECT` clause. For pipelines with multiple tables, specify each `SELECT` clause for tables in the existing pipeline. The `WHERE` clause must match the corresponding clause of the existing pipeline. Use the `FORCE` keyword to change a non-backward-compatible schema or add, modify, or remove the `WHERE` clause. For details about schema evolution, see [Load Avro Data](/data-formats-for-data-pipelines).
To execute this SQL statement, the data pipeline must not be running. You can use the `STOP PIPELINE` SQL statement to stop the execution of the data pipeline.
You must have the ALTER privilege on the pipeline to execute this SQL statement. For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
**Syntax**
```sql SQL theme={null}
ALTER PIPELINE [ IF EXISTS ] pipeline_name
[ INSERT ] INTO table_name
SELECT
$field_name AS field_name [ , ... ]
[ WHERE ... ]
[ INSERT INTO table_nameN SELECT ... ]
[ FORCE ]
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------- | ----------------- | -------------------------------------------- |
| `pipeline_name` | string | The name of the specified pipeline to alter. |
**Examples**
These examples use this table and data pipeline definition. You must stop the execution of the data pipeline before performing schema evolution operations.
Create the `users` table with these columns:
* `id` — Universally Unique IDentifier (UUID) of the user
* `firstname` — First name of the user
* `lastname` — Last name of the user
* `birthyear` — Year of birth
* `groups` — List of groups where the user belongs
```sql SQL theme={null}
CREATE TABLE users(
id UUID NOT NULL,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
birthyear INT,
groups VARCHAR(255)[] NOT NULL DEFAULT 'char[]'
);
```
Assume you have user data in Avro format in multiple files in the `/data/users` directory. Create the `users_pipeline` data pipeline for the Avro files containing user data `*.avro`. The schema configuration instructs the system to infer from all files using the `INFER_FROM` option.
```sql SQL theme={null}
CREATE PIPELINE users_pipeline
SOURCE filesystem
FILTER '/data/users/*.avro'
EXTRACT
FORMAT avro
SCHEMA {
INFER_FROM all_files
}
INTO users
SELECT
$id AS id,
$firstname AS firstname,
$lastname AS lastname,
$birthyear AS birthyear;
```
Start the data pipeline.
```sql SQL theme={null}
START PIPELINE users_pipeline;
```
**Schema Evolution with a Column Addition**
Stop the data pipeline.
```sql SQL theme={null}
STOP PIPELINE users_pipeline;
```
Change the schema of an existing pipeline named `users_pipeline` to add the `groups` column. Access the array of strings within the column.
```sql SQL theme={null}
ALTER PIPELINE users_pipeline
INTO users
SELECT
$id AS id,
$firstname AS firstname,
$lastname AS lastname,
$birthyear AS birthyear,
$groups[] AS groups;
```
Start the data pipeline again.
```sql SQL theme={null}
START PIPELINE users_pipeline;
```
**Check Whether the Data Pipeline to Change Exists for Column Addition**
Stop the data pipeline.
```sql SQL theme={null}
STOP PIPELINE users_pipeline;
```
Change the schema of an existing pipeline named `users_pipeline` to add the `groups` column. Use the `IF EXISTS` keywords to check whether the data pipeline exists. Access the array of strings within the column.
```sql SQL theme={null}
ALTER PIPELINE IF EXISTS users_pipeline
INTO users
SELECT
$id AS id,
$firstname AS firstname,
$lastname AS lastname,
$birthyear AS birthyear,
$groups[] AS groups;
```
Start the data pipeline again.
```sql SQL theme={null}
START PIPELINE users_pipeline;
```
**Schema Evolution with a Column Removal**
Stop the data pipeline.
```sql SQL theme={null}
STOP PIPELINE users_pipeline;
```
Change the schema of an existing pipeline named `users_pipeline` to remove the `birthyear` column.
```sql SQL theme={null}
ALTER PIPELINE users_pipeline
INTO users
SELECT
$id AS id,
$firstname AS firstname,
$lastname AS lastname;
```
Start the data pipeline again.
```sql SQL theme={null}
START PIPELINE users_pipeline;
```
**Schema Evolution with a Column Data Type Modification**
Stop the data pipeline.
```sql SQL theme={null}
STOP PIPELINE users_pipeline;
```
Change the schema of an existing pipeline named `users_pipeline` to narrow the `INT` data type to a `SMALLINT` type for the `birthyear` column using the `SMALLINT` casting function.
```sql SQL theme={null}
ALTER PIPELINE users_pipeline
INTO users
SELECT
$id AS id,
$firstname AS firstname,
$lastname AS lastname,
SMALLINT($birthyear) AS birthyear;
```
Start the data pipeline again.
```sql SQL theme={null}
START PIPELINE users_pipeline;
```
**Schema** **Evolution with the Addition of a Filter Condition**
Stop the data pipeline.
```sql SQL theme={null}
STOP PIPELINE users_pipeline;
```
Change the schema of an existing pipeline named `users_pipeline` to filter the year of birth to be greater than 1950 using the `WHERE` clause. Add the `FORCE` keyword to instruct the data pipeline to evolve the schema with the filter condition.
```sql SQL theme={null}
ALTER PIPELINE users_pipeline
INTO users
SELECT
$id AS id,
$firstname AS firstname,
$lastname AS lastname,
$birthyear AS birthyear,
WHERE
$birthyear > 1950
FORCE;
```
Start the data pipeline again.
```sql SQL theme={null}
START PIPELINE users_pipeline;
```
### ALTER PIPELINE RENAME
`ALTER PIPELINE RENAME TO` SQL statement changes the name of the pipeline object, while retaining its identifier, options, and other metadata. The Ocient System reflects this change in the `sys.pipelines` system catalog table. Then, you must use the new name when you refer to the pipeline in SQL statements.
You must have the ALTER privilege on the pipeline to execute this SQL statement. For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
**Syntax**
```sql SQL theme={null}
ALTER PIPELINE [ IF EXISTS ] pipeline_original_name RENAME TO pipeline_new_name
```
| **Parameter** | **Data** **Type** | **Description** |
| ------------------------ | ----------------- | --------------------------------------- |
| `pipeline_original_name` | string | The name of the existing data pipeline. |
| `pipeline_new_name` | string | The new name of the data pipeline. |
**Example**
Rename an existing pipeline named `ad_data_pipeline` to `renamed_pipeline`.
```sql SQL theme={null}
ALTER PIPELINE ad_data_pipeline RENAME TO renamed_pipeline;
```
## **EXPORT** PIPELINE
`EXPORT PIPELINE` returns the `CREATE PIPELINE` SQL statement used to create the pipeline object. You can use the output of this statement to recreate an identical pipeline when you remove the original pipeline.
The execution of this statement censors sensitive S3 values like `ACCESS_KEY_ID` and `SECRET_ACCESS_KEY` and Kafka [Consumer Configuration](https://docs.confluent.io/platform/current/installation/configuration/consumer-configs.html) password-type fields. The database replaces them with `*`.
To execute this statement, you must have the VIEW privilege on the pipeline and any table the pipeline targets. For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
**Syntax**
```sql SQL theme={null}
EXPORT PIPELINE pipeline_name
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------- | ----------------- | ---------------------------------------- |
| `pipeline_name` | string | The name of the specified data pipeline. |
**Example**
Export an existing pipeline in the database `ad_data_pipeline`.
```sql SQL theme={null}
EXPORT PIPELINE ad_data_pipeline;
```
## CREATE PIPELINE FUNCTION
`CREATE PIPELINE FUNCTION` enables you to define a function for loading data. Define the function behavior using the language. For details bout this language, see [The Apache Groovy Programming Language](https://groovy-lang.org/index.html).
Function arguments and output are strongly typed and immutable.
You can test the execution of your function using the `PREVIEW PIPELINE` SQL statement.
The Ocient System does not support the overload of function names.
**Syntax**
```sql SQL theme={null}
CREATE [ OR REPLACE ] PIPELINE FUNCTION [ IF NOT EXISTS ]
function_name( input_argument [, ...] )
LANGUAGE GROOVY
RETURNS output_argument_definition
IMPORTS [ library_name [, ...] ]
AS $$
groovy_declaration
$$
```
| **Parameter** | **Type** | **Description** |
| ---------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `function_name` | string | A unique identifier for the data pipeline function. |
| `input_argument` | string | The name of one or more input arguments of the function. Specify data types for input arguments according to the support data types defined in [Data Types for Data Pipelines](/data-types-for-data-pipelines). For the data type declaration, use `NOT NULL` where applicable for maximum performance. |
| `output_argument_definition` | string | The type definition of the output from the function. |
| `library_name` | string | The name of one or more Java libraries. You can include libraries by using the `IMPORTS` clause or specifying the fully-qualified class (e.g., `java.lang.Integer`) path in the source definition. |
| `groovy_declaration` | string | The Groovy definition of the function. |
### Install and Enable Third-Party Libraries
You can use the default list of supported third-party libraries or additional third-party libraries that you install.
#### Supported Libraries
Data pipeline functions can import classes from the default list of supported third-party libraries. This table provides the resources for each supported library package.
| **Library Package** | **Resource** |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `java.lang.*` | [java.lang](https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html) |
| `java.util.*` | [java.util](https://docs.oracle.com/javase/8/docs/api/java/util/package-summary.html) |
| `java.nio.ByteBuffer.*` | [ByteBuffer](https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html) |
| `groovy.json.*` | [groovy.json](https://docs.groovy-lang.org/latest/html/gapi/groovy/json/package-summary.html) |
| `groovy.xml.*` | [groovy.xml](https://docs.groovy-lang.org/latest/html/gapi/groovy/xml/package-summary.html) |
| `groovy.yaml.*` | [groovy.yaml](https://docs.groovy-lang.org/latest/html/api/groovy/yaml/package-summary.html) |
| `org.apache.groovy.datetime.extensions.*` | [org.apache.groovy.datetime.extensions](https://docs.groovy-lang.org/latest/html/api/org/apache/groovy/datetime/extensions/package-summary.html) |
| `org.apache.groovy.dateutil` | [org.apache.groovy.dateutil.extensions](https://docs.groovy-lang.org/latest/html/api/org/apache/groovy/dateutil/extensions/package-summary.html) |
| `com.ocient.streaming.data.types.*` | [Data Types for User-Defined Data Pipeline Functions](/data-types-for-user-defined-data-pipeline-functions) |
#### Additional Libraries
You can install and enable additional third-party libraries to import for use in your data pipeline functions.
You must install the JAR package on all Loader Nodes in the `/opt/ocient/current/lib/extractorengine_udt` folder.
Then, add the fully qualified class name in the function import list as part of the `library_name` parameter. For example, to reference the `ByteBuffer` class from the `com.fastbuffer` package, specify `com.fastbuffer.ByteBuffer` in the `library_name` parameter and use the class in the Groovy definition as `var x = new com.fastbuffer.ByteBuffer()`.
### Groovy Data Type Mapping
For the Groovy definition, the Ocient System maps its SQL data type to the corresponding Groovy data type. Your Groovy code should use the Groovy data type defined in this table for any input arguments and output.
| **SQL Data Type** | **Groovy Data Type** |
| -------------------------- | -------------------------------------------------- |
| `BIGINT` | `java.lang.Long` |
| `BINARY(N) or HASH(N)` | `byte[]` |
| `BOOLEAN` | `java.lang.Boolean` |
| `CHAR(N) or VARCHAR(N)` | `java.lang.String` |
| `DATE` | `java.time.LocalDate` |
| `DECIMAL(P,S)` | `com.ocient.streaming.data.types.Decimal` |
| `DOUBLE` | `java.lang.Double` |
| `INT` | `java.lang.Integer` |
| `IPV4` | `java.net.Inet4Address` |
| `IP` | `java.net.Inet6Address` |
| `ST_POINT` | `com.ocient.streaming.data.types.gis.STPoint` |
| `ST_LINESTRING` | `com.ocient.streaming.data.types.gis.STLinestring` |
| `ST_POLYGON` | `com.ocient.streaming.data.types.gis.STPolygon` |
| `FLOAT` | `java.lang.Float` |
| `SMALLINT` | `java.lang.Short` |
| `TIME` | `com.ocient.streaming.data.types.Time` |
| `TIMESTAMP` | `com.ocient.streaming.data.types.Timestamp` |
| `BYTE` | `java.lang.Byte` |
| `TUPLE<>` | `com.ocient.streaming.data.types.OcientTuple` |
| `TYPE[]` | `java.util.List` |
| `UUID` | `java.util.UUID` |
| `VARBINARY(N)` | `byte[]` |
| `VARCHAR(N)` | `java.lang.String` |
**Example**
Create the `sort_function` data pipeline function to sort an array of integers. The function has two input arguments: `value`, a non-NULL array of integers, and `ascending`, the sort order. The function returns a non-NULL array of integers. If `value` is empty, the function throws an error.
The function imports these Java libraries:
* `java.lang.Integer`
* `java.util.ArrayList`
* `java.util.Collections`
* `java.util.Comparator`
* `java.util.List`
Define the Groovy code. Because the input arguments do not change, the example Groovy code first copies the `value` argument, sorts the copied list according to the sort order, and returns the sorted array.
```sql SQL theme={null}
CREATE PIPELINE FUNCTION
sort_function( value INT[] NOT NULL, ascending BOOLEAN NOT NULL)
LANGUAGE GROOVY
RETURNS INT[] NOT NULL
IMPORTS [
'java.lang.Integer',
'java.util.ArrayList',
'java.util.Collections',
'java.util.Comparator',
'java.util.List'
]
AS $$
/* Throw an error if the array is empty */
if (value.isEmpty()){
throw new PipelineFunctionException("Unexpected empty array");
}
/* Make a copy of the list. */
List sorted = new ArrayList<>((List)value);
/* Sort the array elements according to the specified order. */
sorted.sort(ascending ? Comparator.naturalOrder() : Comparator.reverseOrder());
/* Return the sorted array. */
return sorted;
$$;
```
View the creation information about the `sort_function` function using the `sys.pipeline_functions` system catalog table. This statement returns the function name, return type, argument names, data types of the arguments, and the list of imported libraries.
```sql SQL theme={null}
SELECT name, return_type, argument_names, argument_types, imported_libraries
FROM sys.pipeline_functions;
```
## DROP PIPELINE FUNCTION
`DROP PIPELINE FUNCTION` removes an existing pipeline function.
You must have the DROP privilege on the pipeline function to execute this SQL statement. For details, see [Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference).
**Syntax**
```sql SQL theme={null}
DROP PIPELINE FUNCTION [ IF EXISTS ] function_name [, ...]
```
| **Parameter** | **Data** **Type** | **Description** |
| --------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `function_name` | string | The name of the specified data pipeline function to remove. You can drop multiple pipelines by specifying additional function names, separated by commas. |
**Examples**
**Remove the Existing Pipeline Function**
Remove an existing pipeline function named `sort_function`.
```sql SQL theme={null}
DROP PIPELINE FUNCTION sort_function;
```
**Remove an Existing Pipeline Function by Checking for Existence**
Remove an existing pipeline function named `sort_function` or return a warning if the Ocient System does not find the function in the database.
```sql SQL theme={null}
DROP PIPELINE FUNCTION IF EXISTS sort_function;
```
## Related Links
[Load Data](/load-data)
[Data Pipeline Load of CSV Data from S3](/data-pipeline-load-of-csv-data-from-s3)
[Data Pipeline Load of Parquet Data from S3](/data-pipeline-load-of-parquet-data-from-s3)
[Transform Data in Data Pipelines](/transform-data-in-data-pipelines)
[Data Pipeline Behavior Considerations](/data-pipeline-behavior-considerations)
[Load Metadata and File-Based Partitioned Data in Data Pipelines](/load-metadata-and-file-based-partitioned-data-in-data-pipelines)
[Data Control Language (DCL) Statement Reference](/data-control-language-dcl-statement-reference)
[Identifiers](/identifiers)
# Data Preparation
Source: https://docs.ocient.com/data-preparation
Use Ocient SQL lag generators and vector assemblers to simplify time series feature engineering for regression, VAR, and neural network model inputs.
Lag generator and vector assembler SQL functions simplify generating and organizing lagged features for time series data. Each function expands into standard SQL during query processing, so developers can reduce boilerplate and create feature sets with minimal code.
These functions fall into two main types:
* [Lag Generator Functions](#lag-generator-functions) — Create individual lag feature columns.
* [Vector Assembler Functions](#vector-assembler-function) — Group generated lag columns into vectors.
Developers can apply lag features across many -supported models, including:
* Simple Linear Regression (univariate forecasting with lag inputs)
* Multiple Linear Regression (multivariate regression with lagged predictors)
* Polynomial Regression (regression with higher-order lagged terms)
* Linear Combination Regression (custom functions of lagged inputs)
* Nonlinear Regression (arbitrary functions that include lag variables)
* Feedforward Neural Networks (lagged features as input vectors)
* Vector Autoregression (VAR) (multivariate time series with structured lag vectors)
* Autoregression (univariate time series modeled through lagged values)
* Vector Valued Regression (multivariate dependent variables with lagged inputs)
The functions provide general-purpose utilities for time series feature engineering. In particular, VAR models benefit the most from lag functions because the models require large numbers of structured lag vectors.
## Lag Generator Functions
Lag generator functions provide options for creating lagged columns for one or more variables in a single statement.
These functions follow the syntax rules of window aggregate functions as they define the window for the lag computation with an `OVER` and `ORDER BY` clause. For details, see [Window Aggregate Functions](/window-aggregate-functions).
The window parameters of lag generator functions are represented in these examples by ``.
### LAGS
Generates a series of lagged columns for a single variable in one statement. This function simplifies univariate time-series feature creation.
**Syntax**
```sql SQL theme={null}
LAGS(expression, start_lag, end_lag [, step])
OVER ()
```
| **Argument** | **Type** | **Description** |
| ------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `expression` | ANY | The column or expression to lag. |
| `start_lag` | INTEGER | First lag to generate. This value must be less than the `end_lag` value. |
| `end_lag` | INTEGER | Last lag to generate. This value must be greater than the `start_lag` value. |
| `step` | INTEGER | Optional. Defines the gap between successive lags. Must be a positive integer. If unspecified, this value defaults to `1`. |
**Example**
This query produces three lagged columns (`sales_lag1`, `sales_lag2`, `sales_lag3`) from the sales column.
```sql SQL theme={null}
SELECT
LAGS(sales, 1, 3) OVER (ORDER BY day)
FROM store_sales;
```
*Output*
```sql SQL theme={null}
sales_lag1 | sales_lag2 | sales_lag3
-----------+------------+------------
NULL | NULL | NULL
100 | NULL | NULL
120 | 100 | NULL
130 | 120 | 100
```
### LAGS\_ZEROFILL
Generates lagged columns for a single variable and replaces NULL values with `0`.
**Syntax**
```sql SQL theme={null}
LAGS_ZEROFILL(expression, start_lag, end_lag [, step])
OVER ()
```
| **Argument** | **Type** | **Description** |
| ------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `expression` | ANY | The column or expression to lag. |
| `start_lag` | INTEGER | First lag to generate. This value must be less than the `end_lag` value. |
| `end_lag` | INTEGER | Last lag to generate. This value must be greater than the `start_lag` value. |
| `step` | INTEGER | Optional. Defines the gap between successive lags. Must be a positive integer. If unspecified, this value defaults to `1`. |
**Example**
This query produces three lagged sales columns and replaces NULL values with 0.
```sql SQL theme={null}
SELECT
LAGS_ZEROFILL(sales, 1, 3) OVER (ORDER BY day)
FROM store_sales;
```
*Output*
```sql SQL theme={null}
sales_lag1 | sales_lag2 | sales_lag3
-----------+------------+------------
0 | 0 | 0
100 | 0 | 0
120 | 100 | 0
130 | 120 | 100
```
### MULTI\_LAGS
Generates lagged columns for multiple variables at once. This function is intended primarily for creating features for multivariate time-series models.
**Syntax**
```sql SQL theme={null}
MULTI_LAGS(expr1, expr2, [ ,... ] start_lag, end_lag [, step])
OVER ()
```
| **Argument** | **Type** | **Description** |
| ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `expr1, expr2, [ ,... ] ` | ANY | One or more columns or expressions to lag. Applies the same lag range and step to each input. |
| `start_lag` | INTEGER | First lag to generate. This value must be less than the `end_lag` value. |
| `end_lag` | INTEGER | Last lag to generate. This value must be greater than the `start_lag` value. |
| `step` | INTEGER | Optional. Defines the gap between successive lags. Must be a positive integer. If unspecified, this value defaults to `1`. |
**Example**
This query creates four lagged columns for both `interest_rate` and `gdp_growth`.
```sql SQL theme={null}
SELECT
MULTI_LAGS(interest_rate, gdp_growth, 1, 4) OVER (ORDER BY quarter)
FROM economic_data;
```
*Output*
```sql SQL theme={null}
interest_rate_lag1 | interest_rate_lag2 | interest_rate_lag3 | interest_rate_lag4 | gdp_growth_lag1 | gdp_growth_lag2 | gdp_growth_lag3 | gdp_growth_lag4
-------------------+--------------------+--------------------+--------------------+-----------------+-----------------+-----------------+-----------------
NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL
2.5 | NULL | NULL | NULL | 1.1 | NULL | NULL | NULL
2.7 | 2.5 | NULL | NULL | 1.2 | 1.1 | NULL | NULL
2.8 | 2.7 | 2.5 | NULL | 1.3 | 1.2 | 1.1 | NULL
```
### MULTI\_LAGS\_ZEROFILL
Generates lagged columns for multiple variables and replaces NULL values with `0`.
**Syntax**
```sql SQL theme={null}
MULTI_LAGS_ZEROFILL(expr1, expr2, [ ,... ] start_lag, end_lag [, step])
OVER ()
```
| **Argument** | **Type** | **Description** |
| ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `expr1, expr2, [ ,... ] ` | ANY | One or more columns or expressions to lag. Applies the same lag range and step to each input. |
| `start_lag` | INTEGER | First lag to generate. This value must be less than the `end_lag` value. |
| `end_lag` | INTEGER | Last lag to generate. This value must be greater than the `start_lag` value. |
| `step` | INTEGER | Optional. Defines the gap between successive lags. Must be a positive integer. If unspecified, this value defaults to `1`. |
**Example**
This query generates four lagged columns each for `x1`, `x2`, and `x3`, replacing missing values with 0.
```sql SQL theme={null}
SELECT
MULTI_LAGS_ZEROFILL(x1, x2, x3, 1, 4) OVER (ORDER BY time_col)
FROM public.my_time_series_table;
```
*Output*
```sql SQL theme={null}
x1_lag1 | x1_lag2 | x1_lag3 | x1_lag4 | x2_lag1 | x2_lag2 | x2_lag3 | x2_lag4 | x3_lag1 | x3_lag2 | x3_lag3 | x3_lag4
--------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------+---------
0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
10 | 0 | 0 | 0 | 20 | 0 | 0 | 0 | 30 | 0 | 0 | 0
11 | 10 | 0 | 0 | 21 | 20 | 0 | 0 | 31 | 30 | 0 | 0
12 | 11 | 10 | 0 | 22 | 21 | 20 | 0 | 32 | 31 | 30 | 0
```
## Vector Assembler Function
A vector assembler function provides options for grouping multiple lagged columns into structured vectors in a single statement. This function makes preparing input data for time series models easier, especially those that require organized lag structures, such as VAR.
### LAG\_VECTORS
Groups lagged columns generated by the `MULTI_LAGS` or `MULTI_LAGS_ZEROFILL` functions into vector columns. Models such as VAR require these structured lag vectors.
The resulting vectors are named `lag_vector_`.
**Syntax**
```sql SQL theme={null}
LAG_VECTORS(expr1, expr2, [ ..., ] start_lag, end_lag [, step])
```
| **Argument** | **Type** | **Description** |
| ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `expr1, expr2, [ ,... ] ` | NUMERIC | Two or more lagged columns to group. Applies the same lag range and step to each input. |
| `start_lag` | INTEGER | First lag to assemble. This value must be less than the `end_lag` value. |
| `end_lag` | INTEGER | Last lag to assemble. This value must be greater than the `start_lag` value. |
| `step` | INTEGER | Optional. Defines the gap between successive lags. Must be a positive integer. If unspecified, this value defaults to `1`. |
**Examples**
**Assemble Lagged Columns into Vectors**
This query uses `MULTI_LAGS_ZEROFILL` to generate lagged columns for `x1`, `x2`, and `x3`, then uses `LAG_VECTORS` to group them into `lag_vector1` through `lag_vector4`.
```sql SQL theme={null}
SELECT
{x1, x2, x3} AS current_vector,
LAG_VECTORS(x1, x2, x3, 1, 4)
FROM (
SELECT
x1, x2, x3,
MULTI_LAGS_ZEROFILL(x1, x2, x3, 1, 4) OVER (ORDER BY time_col)
FROM public.my_time_series_table
) s;
e;
```
*Output*
```sql SQL theme={null}
current_vector | lag_vector1 | lag_vector2 | lag_vector3 | lag_vector4
---------------+-------------+-------------+-------------+-------------
{10, 20, 30} | {0, 0, 0} | {0, 0, 0} | {0, 0, 0} | {0, 0, 0}
{11, 21, 31} | {10, 20, 30}| {0, 0, 0} | {0, 0, 0} | {0, 0, 0}
{12, 22, 32} | {11, 21, 31}| {10, 20, 30}| {0, 0, 0} | {0, 0, 0}
{13, 23, 33} | {12, 22, 32}| {11, 21, 31}| {10, 20, 30}| {0, 0, 0}
```
**Prepare Data for a VAR Model**
This example shows how to prepare training data for a VAR model with three variables (`x1`, `x2`, `x3`) and four lags. The example demonstrates how the lag generator functions and vector assembler can simplify feature creation compared to writing out every LAG expression manually.
* `MULTI_LAGS_ZEROFILL` generates all individual lagged columns (`x1_lag1`…`x3_lag4`) in a single call, replacing NULL values with zero.
* `LAG_VECTORS` automatically groups these lagged columns into vector inputs (`lag_vector1` ... `lag_vector4`), which the model requires.
```sql SQL theme={null}
CREATE MLMODEL my_var_model
TYPE VECTOR_AUTOREGRESSION ON (
SELECT
{x1, x2, x3},
LAG_VECTORS(x1, x2, x3, 1, 4)
FROM (
SELECT
x1, x2, x3,
MULTI_LAGS_ZEROFILL(x1, x2, x3, 1, 4) OVER (ORDER BY t)
FROM public.my_time_series_table
)
)
OPTIONS (
'numVariables' -> '3',
'numLags' -> '4'
);
```
**Prepare Data for a VAR Model with Manual Vector Assembly**
This version of the univariate regression example uses repeated `LAG` invocations instead of the `LAGS` function. Although it produces the exact same set of lagged features (`sales_lag1`, `sales_lag2`, `sales_lag3`), the query requires writing each `LAG` expression manually. This makes the SQL longer, more repetitive, and harder to maintain compared to the concise single-line `LAGS` version.
```sql SQL theme={null}
CREATE MLMODEL my_var_model_manual
TYPE VECTOR_AUTOREGRESSION ON (
SELECT
{x1, x2, x3},
{x1_lag1, x2_lag1, x3_lag1},
{x1_lag2, x2_lag2, x3_lag2},
{x1_lag3, x2_lag3, x3_lag3},
{x1_lag4, x2_lag4, x3_lag4}
FROM (
SELECT
x1, x2, x3,
COALESCE(LAG(x1, 1) OVER (ORDER BY t), 0) AS x1_lag1,
COALESCE(LAG(x1, 2) OVER (ORDER BY t), 0) AS x1_lag2,
COALESCE(LAG(x1, 3) OVER (ORDER BY t), 0) AS x1_lag3,
COALESCE(LAG(x1, 4) OVER (ORDER BY t), 0) AS x1_lag4,
COALESCE(LAG(x2, 1) OVER (ORDER BY t), 0) AS x2_lag1,
COALESCE(LAG(x2, 2) OVER (ORDER BY t), 0) AS x2_lag2,
COALESCE(LAG(x2, 3) OVER (ORDER BY t), 0) AS x2_lag3,
COALESCE(LAG(x2, 4) OVER (ORDER BY t), 0) AS x2_lag4,
COALESCE(LAG(x3, 1) OVER (ORDER BY t), 0) AS x3_lag1,
COALESCE(LAG(x3, 2) OVER (ORDER BY t), 0) AS x3_lag2,
COALESCE(LAG(x3, 3) OVER (ORDER BY t), 0) AS x3_lag3,
COALESCE(LAG(x3, 4) OVER (ORDER BY t), 0) AS x3_lag4
FROM public.my_time_series_table
)
)
OPTIONS (
'numVariables' -> '3',
'numLags' -> '4'
);
```
## Related Links
[Window Aggregate Functions](/window-aggregate-functions)
[Machine Learning in Ocient](/machine-learning-in-ocient)
[Machine Learning Models](/machine-learning-models)
# Data Query Language (DQL) Statement Reference
Source: https://docs.ocient.com/data-query-language-dql-statement-reference
Explore Ocient SQL syntax rules, enabling users to write clear, efficient queries for data retrieval and manipulation at scale.
The supports querying using the SQL syntax that follows ANSI SQL standards.
## Ocient SQL Syntax
This code block shows the general syntax to perform SQL querying in and the order in which commands should go.
For specific descriptions and syntax for the commands, see the respective SQL statement sections on this page.
**Syntax**
```sql SQL theme={null}
[ WITH ... ]
SELECT ...
[ EXCEPT(...) ]
[ FROM ...
[ JOIN ... ] ]
[ WHERE ... ]
[ GROUP BY ...
[ HAVING ... ] ]
[ ORDER BY ... ]
[ LIMIT ... ]
[ OFFSET ... ]
[ INTERSECT ... ]
[ EXCEPT ... ]
[ UNION ... ] ]
[ USING ... ]
[ TRACE ... ]
[ TAG ... ]
```
## Default Schema
Ocient identifies every table using a database and schema. For example, the fully qualified path to the `movies` table is `cinema.adventure.movies`, where `cinema` is the database and `adventure` is the schema.
When you do not fully qualify a table name, the Ocient System uses a default schema. When you first log into the system, the default schema is your fully qualified username. You can change the default schema using the [SET SCHEMA](/commands-supported-by-the-ocient-jdbc-cli-program#set-schema) command.
## Querying SQL Statement Reference
Ocient supports the following SQL statements.
### WITH
Assigns a name to a common table expression, allowing an auxiliary query to be used in the main query. This helps break complex queries into smaller parts.
**Syntax**
```sql SQL theme={null}
WITH
[ ( [ ,... ] ) ]
AS ( )
```
**Parameters**
| **Parameter** | **Description** |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `` | A name for the common table expression populated with the result set from the `sub_query` statement. |
| `` | Optional. This is a list of column names for common table expressions populated with the `sub_query` result set. If no column names are provided, the column names are the same as the table referenced in the `sub_query` statement. |
| `` | An auxiliary query that collects data for a common table expression. `sub_query` can use regular query commands, including ORDER BY, LIMIT, OFFSET, UNION, INTERSECT, EXCEPT, WHERE, GROUP BY, and HAVING. See the respective SQL statement reference sections for usage rules. |
| `` | The main SELECT query. Note that the `FROM` statement in the main `SELECT` query must also include the `cte_name` if the query uses its values. |
**Example**
In this example, the subquery calculates the average budget for all rows in the `movies` table. The main query uses that average to find all movies that spent more.
```sql SQL theme={null}
WITH avg_budget_table (average_budget) AS (
SELECT AVG(budget)
FROM movies
)
SELECT title,
budget,
revenue
FROM movies,
avg_budget_table
WHERE budget > avg_budget_table.average_budget;
```
*Output*
| title | budget | revenue |
| ----------------------- | --------- | ---------- |
| CGI Why | 237000000 | 2787965087 |
| Titania | 200000000 | 1845034188 |
| Merchandise Vehicle 5 | 200000000 | 1066969703 |
| The Tentpole | 220000000 | 1519557910 |
| Pirates of Palm Springs | 140000000 | 655011224 |
| Spyman 16 | 200000000 | 1108561013 |
| Frigid | 150000000 | 1274219009 |
| Fury 7 | 190000000 | 1506249360 |
| Superhero 23 | 250000000 | 1084939099 |
| Triassic World | 150000000 | 1513528810 |
| Iron Chef 3 | 200000000 | 1215439994 |
| The Last Airman | 150000000 | 318502923 |
### SELECT
Initiates a query statement or a subquery clause within other statements.
You can query the data of tables where you have the SELECT privilege.
For information on using SELECT as a subquery for filtering or ordering results, see the [WHERE](#where) and [HAVING](#having) sections.
For information on using SELECT as a subquery for a common table expression, see the [WITH](#with) section.
`SELECT *` queries that lack a `FROM` clause automatically reference the `sys.dummy1` table.
For example, `SELECT *;` is the same as `SELECT * FROM sys.dummy1;`.
**Syntax**
```sql SQL theme={null}
SELECT [ ALL | DISTINCT ]
[ * [ EXCEPT ( column_name [ , ... ] ) ]
| [ , ... ] ]
[ ]
```
**Parameters**
| **Parameter** | Description |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `ALL` | `SELECT` and `SELECT ALL` are both the same. Returns all valid data rows from the database that meet the criteria of your query. |
| `DISTINCT` | `SELECT DISTINCT` returns only unique rows that do not match other rows based on the criteria of your query. |
| `*` | Returns all columns from the specified tables in the result set for the query. |
| `EXCEPT` | When used with `*`, `EXCEPT` allows specific columns to be excluded from the query results. |
| `column_name` | The name of one or more columns from the specified table that you want to exclude (using `EXCEPT`) from your query results. |
#### **\