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. 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, allowing an auxiliary query to be used in the main 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
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> ) [#types-of-join-operations]
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
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. SyntaxSQL
Examples
Limit Returned Rows Using a Number
This example uses
LIMIT to restrict the number of returned movie titles to only three.
SQL
SQL
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
OFFSET
Skips a specified number of rows from the result set. The returned rows are nondeterministic unless you use an ORDER BY clause. SyntaxSQL
Examples
Skip Rows From the Result Set Using a Number
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 Rows From the Result Set Using an Expression
The
OFFSET SQL statement 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
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 to the workload as a query run 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
Examples
These examples show how the system interprets strings with and without escape sequences.
String Without an Escape Sequence
This example selects the simple string literal
'\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

