Ocient SQL Syntax
This code block shows the general syntax to perform SQL querying in Ocient® 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. SyntaxSQL
Default Schema
Ocient identifies every table using a database and schema. For example, the fully qualified path to themovies 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 command.
Querying SQL Statement Reference
Ocient supports the following SQL statements.WITH
Assigns a name to a common table expression (CTE) so that the main query can reference an auxiliary query. This helps break complex queries into smaller parts. SyntaxSQL
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
WITH RECURSIVE
TheWITH RECURSIVE clause defines a recursive common table expression (CTE) that references itself. Recursive CTEs enable iterative computations, such as traversing hierarchical data, generating sequences, and walking graph structures.
A recursive CTE consists of two parts joined by UNION ALL or UNION:
- Anchor member — A non-recursive base query that produces the initial result set.
- Recursive member — A query that references the CTE by name and produces additional rows in each iteration.
RECURSIVE keyword is optional. If you omit it but the CTE references itself, the database automatically detects the self-reference and treats the CTE as recursive.
Syntax
SQL
Choose Between
UNION ALL and UNION Keywords
UNION ALL— Accumulates all rows from every iteration without deduplication. Use this keyword for most recursive queries.UNION— Removes duplicate rows at each iteration by comparing new rows against all previously accumulated rows. Use this keyword to guarantee termination on cyclic data, for example, a graph traversal where a node can appear in multiple paths. This keyword is theUNIONset operator, which is unrelated to theDISTINCTkeyword that the recursive member cannot contain.
sql.maxRecursiveQueryIterations system parameter controls the maximum number of iterations a recursive CTE can perform, which prevents runaway recursion. The system enables recursive queries by default.
You can set this parameter with the
ALTER SYSTEM ALTER CONFIG SET statement. The change applies system-wide and propagates asynchronously, so there might be a brief delay before the new value takes effect on all SQL Nodes.
SQL
- The recursive member must use the
UNION ALLorUNIONkeywords to combine with the anchor. The member cannot use theEXCEPTorINTERSECTset operator keywords. - The recursive member cannot contain the
GROUP BYclause, theHAVINGclause, or aggregate functions. - The recursive member cannot contain the
DISTINCTkeyword, theLIMITclause, or theOFFSETclause. - The recursive member cannot contain window functions.
- The recursive reference cannot appear on the NULL-producing side of an outer join (
LEFT JOIN,RIGHT JOIN, orFULL OUTER JOIN). - The recursive reference cannot appear inside
NOT IN,NOT EXISTS, or other negation predicates. - The recursive member cannot reference the CTE more than once, which rules out self-joins and nonlinear recursion.
- Two CTEs cannot reference each other. The system does not support mutual recursion.
EXPLAIN SQL Statement Support
Executing the EXPLAIN SQL statement on a recursive query returns the data flow script that the database generates to execute the recursion. You can execute the EXPLAIN statement on individual statements within that script to inspect their execution plans.
Examples
Generate a Sequence of Integers
This recursive CTE generates a sequence of integers from 1 to 10.
SQL
Traverse an Employee Hierarchy
This example traverses an employee hierarchy starting from the top-level manager (
WHERE manager_id is NULL) and walks down to all reports.
SQL
Traverse a Graph with Cycles
This example uses the
UNION keyword to traverse a graph with cycles and guarantee termination. Because the UNION keyword removes duplicate rows, the recursion stops when the database does not recover any new nodes.
SQL
Use Recursive CTEs with DML Statements
You can use recursive CTEs withINSERT INTO ... SELECT, CREATE TABLE AS SELECT (CTAS), and DELETE SQL statements. In each case, the WITH RECURSIVE clause follows the table name of the DML statement, for example, after INSERT INTO table_name.
Examples
Insert Rows Using a Recursive CTE
This example inserts the result of a recursive CTE into an existing table. The target table must already exist with a compatible schema.
SQL
1 through 100) into the number_sequences table.
SQL
Create a Table Using a Recursive CTE
This example creates a new table from the result of a recursive CTE. For the
CREATE TABLE AS SELECT SQL statement, add the AS keyword between the table name and the WITH RECURSIVE clause.
SQL
SQL
Delete Rows Using a Recursive CTE
This example uses a recursive CTE to delete a range of rows from the
number_sequences table. The CTE generates the rows to delete, and the DELETE SQL statement removes any row whose n value matches the CTE result.
SQL
91 through 100), leaving 90 rows in the number_sequences table.
SQL
Use Recursive CTEs in Views
You can define a view that contains a recursive CTE. TheCREATE VIEW SQL statement succeeds even when the sql.maxRecursiveQueryIterations configuration parameter is 0 (disabled), because the system detects the recursion when you query the view, not when you create it.
SQL
SQL
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 and HAVING sections. For information on using SELECT as a subquery for a common table expression, see the 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;.SQL
<select_list_entry>
Theselect_list_entry defines a column or expression to include in your query result set.
Syntax
SQL
<from_clause>
For information on the<from_clause>, see the FROM documentation.
Examples
Using SELECT *
This example usesSELECT * to return all the columns in the movies table.
SQL
Using SELECT * EXCEPT
This example usesSELECT * EXCEPT to exclude certain columns from the result set.
SQL
Using Lateral Column Aliases
Ocient SQL queries support lateral column aliases, meaning you can immediately reuse aliases for calculations in the same query as new inputs. Hence, you can simplify queries that normally require subqueries and common table expressions. These examples use theproducts table with these columns:
product_id— Product identifier as an integerproduct_name— Product name as a stringprice— Price as a floating point number
CREATE TABLE SQL statement.
SQL
products table.
SQL
DiscountedPrices. Use the WITH keyword to create the subquery.
SQL
discounted_price alias immediately to calculate the total_price_after_tax value in the same query.
SQL
FROM
Specifies the table or view to use in aSELECT statement.
Syntax
SQL
JOIN
Combines rows from multiple tables so they can be accessed by a query. SyntaxSQL
Types of Join Operations ( <join_operation> )
Ocient supports the following types of JOIN operations.
Syntax
SQL
JOIN Type Descriptions
By default, Lateral joins are primarily useful when a cross-referenced column is necessary for computing the rows to join. A common application is providing an argument value for a set-returning function.
JOIN statements that involve subqueries can operate laterally if necessary. This behavior allows subqueries to reference joined columns from the preceding items included in the FROM clause.For example, both parts of this join operation use subqueries that reference table x. The LATERAL keyword is optional; the join operation acts the same regardless of whether it is included.Text
games— A table of video game titles and their genre_ids. Note that some games have a NULL value assigned to their genre_id.
genre— A table of video game genres, which are identified by IDs.
INNER JOIN
This example uses anINNER JOIN operation to capture only the rows that exist in both tables. Games with NULL values for their genre_id are eliminated from the result set.
SQL
LEFT OUTER JOIN
This example uses aLEFT OUTER JOIN operation to capture all rows from the left table (game), even if they have no matching row in the right table (genre).
SQL
RIGHT OUTER JOIN
This example uses aRIGHT`` OUTER JOIN operation to capture all rows from the right table (genre), even if they have no matching row in the left table (game).
SQL
FULL OUTER JOIN
This example uses aFULL OUTER JOIN operation to capture all rows from both tables, even if they do not match.
SQL
CROSS JOIN
This example uses aCROSS JOIN operation to capture every possible combination of rows from both tables, regardless of whether they match. Note that, unlike other JOIN operations, CROSS JOIN does not require an ON statement.
SQL
As the result set for this CROSS JOIN example is more than 200 rows, the results are abbreviated.
SEMI JOIN
This example uses aSEMI JOIN operation to capture genre names that have at least one match in the games table. Rows are only included once, even if there are multiple matches.
SQL
ANTI JOIN
This example uses anANTI JOIN operation to capture any rows in the game table that do not match any rows in the genre table.
SQL
WHERE
Filters rows based on a specified condition. SyntaxSQL
<filter_condition>
A logical combination of predicates used to evaluate the referencedcolumn_name based on the filter_value.
Syntax
SQL
EXISTS
AnEXISTS clause used in a WHERE statement evaluates if a subquery returns any rows.
For each row that the database computes in the outer query, if the subquery returns at least one row, the EXISTS clause evaluates to true. In this outcome, the outer query returns its row.
If the subquery returns zero rows, the EXISTS clause evaluates to false, and the outer query excludes those rows.
The NOT EXISTS clause performs the opposite Boolean logic. In this case, the outer query returns rows only when the subquery has no matches.
Examples
These examples use two tables, one for company departments and the other for employees assigned to those departments.
Create the departments table for department data.
SQL
employees table for employee data.
SQL
HR, IT, and Marketing, into the departments table.
SQL
Alice, Bob, Charlie, and David, into the employees table.
SQL
EXISTS clause to find any names from the employees table who are assigned to a department listed in the departments table.
SQL
David, who is assigned to a department that does not exist in the departments table.
Output
Text
SELECT 1 to check whether any matching rows exist in the employees table. The output is the same if the query uses SELECT * instead.
SQL
Marketing department because no employees belong to it.
Output
Text
departments table where id != 3 (excluding the Marketing department). The subquery checks if there is at least one employee with a department identifier less than 4.
The query is uncorrelated because the subquery does not reference the departments table.
SQL
Text
NOT EXISTS clause. The example returns only employees who are assigned to a department identifier department_id not listed in the departments table.
SQL
David
SIMILAR TO Operator
SIMILAR TO is a keyword that extends the LIKE operator, adding more features for match filtering, including many metacharacters used in regular expressions.
% and _ both act as wildcard operators, but other supported metacharacters match traditional regular expressions.
Syntax
SQL
SIMILAR TO keyword.
SIMILAR TO also supports escaping these metacharacters with \ and certain escape sequences supported by C family languages.
Array Filters
A filter expression can use the functionsFOR_SOME() and FOR_ALL() to apply a predicate against all values of an input array.
Array filter functions have the following rules:
- They can only evaluate array types.
- They can go on either the left or right side of a Boolean comparison expression, but not both sides at the same time.
- They must directly use a Boolean comparison operator.
- They cannot use the
SOMEandALLSQL keywords.
FOR_ALL()evaluates an empty array asTRUE.FOR_SOME()evaluates an empty array asFALSE.
ARRAY_LENGTH function to specify a minimum array length. For example, this statement would evaluate an array as TRUE only if it is not empty and all values matched %ocient%:
SQL
FOR_SOME() or FOR_ALL() evaluates a NULL row (the row itself is NULL, not that the array contains NULL values), then the result is always FALSE.
To check an array for the presence of NULL values, you must use the IS NULL operator. For example:
SQL
@>, <@, and &&, do not adhere to Boolean logic for NULL values. For details, see the Array Functions and Operators page.
GROUP BY
Groups rows with the same values into summary rows, based on a specified aggregate function. SyntaxSQL
Example
This example uses a movie database to calculate the total amount spent on movie production per year.
SQL
HAVING
Filters aggregated rows based on a specified condition.HAVING operates in a GROUP BY statement by setting a filter for the rows to be aggregated and grouped.
For information on using GROUP BY in a query statement, see GROUP BY.
Syntax
SQL
Example
This example calculates the total amount spent on movie production per year. The
HAVING clause filters out any rows that do not have a sum of at least $100 million.
SQL
QUALIFY
Filters rows based on the results of window functions. TheQUALIFY clause is analogous to HAVING for aggregate functions, except that QUALIFY filters rows after the system computes the window functions.
The system evaluates the QUALIFY clause after the window functions but before the DISTINCT keyword and ORDER BY clause. The logical execution order is:
FROMWHEREGROUP BYHAVINGSELECT(where the Ocient System computes the window functions)QUALIFYDISTINCTORDER BYLIMITandOFFSET
SQL
Examples
Top-N per Group
This example returns the top three highest-paid employees per department.
SQL
Filter on a Running Aggregate
This example returns only rows where the running sum reaches at least 100.
SQL
Add Additional Filtering Using the
WHERE Clause
Return rows where the value val is greater than 20. The WHERE clause filters rows before the system computes the window functions. The QUALIFY clause filters rows after the computation.
SQL
Rank Items Using the
DENSE_RANK Function
This example ranks each row within each group and returns only the first two ranks.
SQL
The
QUALIFY clause cannot contain window functions inside the recursive member of a recursive common table expression (CTE).WINDOW
Defines one or more named window specifications that you can reference in window functionOVER clauses within the same SELECT SQL statement. Named windows reduce repetition when multiple window functions share the same partitioning, ordering, or framing.
Place the WINDOW clause after the QUALIFY clause, if present, and before the ORDER BY clause.
Syntax
SQL
Reference a Named Window
You can reference a named window in an
OVER clause in two ways.
Examples
Bare Named Window Reference
SQL
SQL
ORDER BY clause when the base window already has this clause.
Window Chaining
Named windows can reference other named windows, which lets you build up specifications incrementally.
SQL
WINDOW clause.
You cannot create a cyclic reference between named windows.
SELECT SQL statement that defines it. Named windows are not visible inside subqueries, and a subquery cannot expose its named windows to the outer query.
You cannot reference a named window outside the
SELECT statement that defines it.SELECT is valid:
SELECTSQL statementsCREATE VIEWandCREATE OR REPLACE VIEWstatementsCREATE TABLE ... AS SELECT(CTAS) statementINSERT INTO ... SELECTstatement- Subqueries and CTEs
SQL
Chain Multiple Named Windows
This example chains three named windows to build a complex window specification incrementally. The
w_base window partitions rows by department, the w_ordered window adds ordering by hire date, and the w_framed window adds a frame that runs from the first row to the current row. The query uses the w_framed window to calculate a running total of salary within each department, ordered by hire date.
SQL
ORDER BY
Sorts the result set in ascending or descending order based on one or more specified columns. If you specify multiple columns, they are sorted hierarchically from left to right. SyntaxSQL
Example
In this example, the
ORDER BY statement orders the movies from newest to oldest.
SQL
LIMIT
Limits the number of returned rows from a query to a specified amount. The returned rows are nondeterministic unless you use an ORDER BY clause. Syntaxes Limit RowsSQL
SQL
Examples
Return the First Three Rows Using the
LIMIT Clause
This example uses LIMIT to restrict the number of returned movie titles to only three.
SQL
SQL
LIMIT Clause
The LIMIT SQL statement can also accept expressions. This query uses the 1+2 expression with the sys.dummy table to create a table of three incrementing integers. For details, see Generate Tables Using sys.dummy.
SQL
SQL
LIMIT Clause
This example returns the top three salaries in each department. The PER clause extends the LIMIT clause to operate per group rather than globally.
SQL
The query returns the top three highest-paid employees per department. The
ORDER BY salary DESC clause inside the PER clause specifies within-group ordering. The inter-group ordering is nondeterministic because there is no outer ORDER BY clause.
Return an Arbitrary Set of Rows per Group Using the LIMIT Clause
When you do not specify the ORDER BY clause inside the PER clause, the query returns an arbitrary set of N rows per group.
SQL
The result contains five rows per department (or fewer if the department has fewer than five rows total). Both the rows selected and their order are nondeterministic.
Return Rows per Group Using Multiple Grouping Columns
You can specify multiple columns for grouping.
SQL
Order the Final Result Using an Outer
ORDER BY Clause
This example returns the top three salaries per department using the LIMIT ... PER clause, then sorts the combined result by department and descending salary using an outer ORDER BY clause. The ORDER BY clause inside the PER clause controls which rows the database selects within each group. An outer ORDER BY clause controls the final result ordering.
SQL
FETCH
Limits the number of returned rows from a query. This is an alternative to the LIMIT clause. The query returns rows in nondeterministic order unless you use an ORDER BY clause.You can use
FETCH FIRST and FETCH NEXT interchangeably. The system accepts both ROW and ROWS regardless of the value of limit_number.SQL
Examples
Fetch First Three Rows
This example uses
FETCH FIRST to restrict the number of returned movie titles to only three.
SQL
SQL
limit_number, FETCH FIRST ROW ONLY returns a single row.
SQL
SQL
OFFSET
Skips a specified number of rows from the result set. The returned rows are nondeterministic unless you use an ORDER BY clause. Syntaxes Skip RowsSQL
SQL
Examples
Skip the Six Oldest Rows Using the
OFFSET Clause
In this example, the ORDER BY statement orders the results chronologically. As a result, the OFFSET clause removes the oldest six movies from the result set.
SQL
Skip a Calculated Number of Rows Using the
OFFSET Clause
The OFFSET clause can also accept expressions. This query uses the expression 3+4 with the sys.dummy table to create a column of incrementing integers by skipping the first seven out of 10 rows. For details, see Generate Tables Using sys.dummy.
SQL
SQL
OFFSET and LIMIT Clauses
This example skips the five highest salaries in each department, then returns the next five, producing the second page of a five-row-per-page pagination within each department. The PER clause extends the OFFSET clause to skip rows per group rather than globally. Combine the OFFSET ... PER clause with the LIMIT ... PER clause to paginate within each group.
SQL
This query returns rows six through ten for each department, ordered by salary in descending order. This result is the second page of results, where each page contains five rows per department. Marketing has only nine employees, so only four rows appear for that department. Sales has only three employees, so
OFFSET 5 skips past all of them and returns no Sales rows.
INTERSECT
Returns any rows that match between two separateSELECT queries. To use INTERSECT, the two queries must be compatible, meaning they must return the same number of columns and have similar data types.
By default, the SQL statement eliminates duplicate rows unless the query includes the optional ALL keyword. Using the DISTINCT keyword is the same as this default behavior.
Syntax
SQL
Example
This example has two
SELECT queries with an INTERSECT statement. The full query retrieves movies that had a budget of at least 1 billion in revenues.
SQL
EXCEPT
TheEXCEPT keyword returns the result set of a first SELECT query minus any matching rows from a second SELECT query.
EXCEPT requires the two queries to be compatible, meaning they must return the same number of columns and have similar data types. By default, the result set eliminates duplicate rows unless the query includes the optional ALL keyword. Using the DISTINCT keyword is the same as this default behavior.
The EXCEPT keyword can also be used to exclude specific columns from a SELECT * query. For information on that alternate usage, see the SELECT syntax and example.
Syntax
SQL
Example
In this example, the first
SELECT statement queries all rows in the movies table. The EXCEPT clause and the second SELECT statement eliminate from the results any rows with movies that had a budget greater than 20000000.
SQL
UNION
Returns the combined result set of two or moreSELECT queries.
By default, UNION eliminates duplicate rows from the result set unless you specify the ALL keyword. Using the DISTINCT keyword is the same as this default behavior.
Syntax
SQL
Example
This example uses
UNION to merge two separate queries for identical columns into the same result set.
SQL
USING
Overrides various system configurations for processing a specified query. TheUSING keyword is required for only the first query override, not for subsequent ones.
For descriptions of the supported query configurations, see the parameter table below.
Syntax
SQL
Example
SQL
SQL
TRACE
An optional clause that executes the query, but discards the original result set. Instead,TRACE returns a result set of tracing data that describes the execution of the query.
Append the TRACE SQL statement to the end of a query. The statement can include optional parameters to control its frequency and level of detail.
To understand the results of this statement, see TRACE Results.
Trace queries have the same effect on the workload as a query executed without the clause.
SQL
TRACE Results
Each row of the trace output provides some information about what an operator instance has done in the time between the previous trace sample and the most current sample.
Sample and Value Columns
The
sample and value columns describe what occurred in a specified trace period.
Example
SQL
TAG
An optional clause that adds one or more tags to the SQL query. You can also add tags to a common table expression in theWITH clause. After you define tags, you can find them in the sys.queries and sys.completed_queries system catalog tables.
Syntax
SQL
Examples
SQL Query with One Tag
Select the count of a table with one row and tag the query with the name
count1.
SQL
device_model and phones.
SQL
average_budget tag. You can also add another tag for the whole query overall_budget.
SQL
String Literals and Escape Sequences
All string literals in SQL statements must be enclosed in single quotes. To use a single quote within a string, you can use another single quote as an escape,''*. *
For other escape sequences, include an e character before the string literal, i.e., before the opening single quote. This directs the system to recognize escape sequences in the string literal. This means:
- All single
\characters in the string now escape themselves. - Any subsequent character after the
\is also escaped if it matches an escape sequence (see the table).
\, such as directory paths.
Supported Escape Sequences
The
\o, \oo, \ooo and \xh, \xhh escape sequences specify raw UTF-8 bytes, not Unicode code points. To represent multi-byte UTF-8 characters using these sequences, you must provide each byte separately (e.g., e'\xc3\xa9' for é). For Unicode code points, use \uxxxx or \Uxxxxxxxx instead. String literals containing invalid UTF-8 byte sequences result in a syntax error.The
\' escape sequence is not supported in e-strings. Use '' to include a single quote within an e-string.'\my\directory\path' that does not use escape sequences.
SQL
\my\directory\path
String With an Escape Sequence
This example selects the simple string literal '\my\directory\path' and uses an escape sequence. The result omits the backslashes.
SQL
mydirectorypath
String With an Escape Sequence to Retain the Backslashes
This example uses the '\\my\\directory\\path' string with an escape sequence to include backslashes in the result.
SQL
\my\directory\path
Escape Sequences with Regular Expressions
Be careful using escape sequences with strings that also use regular expressions. Escape sequences in SQL syntax override those in regular expressions.
\w+ to match any word characters.
SQL
abcdefghijklmnopqrstuvwxyz
The function behaves differently if the regular expression is an escape sequence because it overrides the \ character. The regular expression searches only for the character w.
SQL
w
Octal Escape Sequence
This example uses an octal escape sequence to produce the letter A (octal 101).
SQL
A
Hexadecimal Escape Sequence
This example uses hexadecimal escape sequences to produce the character é (UTF-8 bytes \xc3\xa9).
SQL
é
Unicode Escape Sequence
This example uses a 16-bit Unicode escape sequence to produce the character é (U+00E9).
SQL
é
32-bit Unicode Escape Sequence
This example uses a 32-bit Unicode escape sequence to produce an emoji (U+1F600).
SQL
😀

