The SQL language includes Data Definition Language (DDL), query and Data Manipulation Language (DML). Flink has a preliminary supports for DDL, query and DML features.
Before the existence of the SQL CLI, queries written in the Flink SQL can only be embedded in a table program written in Java or Scala. The tables accessed in the SQL query must be registered in the TableEnvironment first. It’s impossible to use SQL only to complete the work.
The SQL CLI is designed to provide an easy way to write, debug, and submit table programs without writing a single line of Java or Scala code. For SQL CLI, DDL replaces the table definition and registration process in the table programs. By passing a SQL DDL description text to the SQL CLI, it will be parsed into table objects and registered to the TableEnvironment, then follow up SQL queries can access these tables directly.
For convenience, Table.toString() automatically registers the table under a unique name in its TableEnvironment and returns the name. Hence, Table objects can be directly inlined into SQL queries (by string concatenation) as shown in the examples below.
Note: The current DDL is not persistent and can not be shared, only exists in a single SQL query (along with the life cycle of a query), so currently only CREATE operations are supported (ALTER/DROP is not introduced). Later versions will support persistence and the corresponding DDL objects will be saved into persistent catalogs and are easier to use or modify (does not need to be declared every time, and can be shared).
For example, user A produced a table T1 in a query, then T1 can be shared as a data source in another query of user B. Flink’s SQL support is not yet feature complete. Queries that include unsupported SQL features cause a TableException. The supported features of SQL on batch and streaming tables are listed in the following sections.
Flink parses SQL using Apache Calcite, which supports standard ANSI SQL.
The following BNF-grammar describes the superset of supported SQL features in batch and streaming queries. The Operations section shows examples for the supported features and indicates which features are only supported for batch or streaming queries.
Table options can not only be specified in DDL but also be specified in query statements.
Supported DML Syntax
DML (Insert Only)
The following BNF-grammar describes the superset of supported SQL features in batch and streaming queries. Currently, only INSERT operation is supported.
Note: The EMIT clause is only valid for window queries currently. See more about EMIT Strategy in window queries.
Flink SQL uses a lexical policy for identifier (table, attribute, function names) similar to Java:
The case of identifiers is preserved whether or not they are quoted.
After which, identifiers are matched case-sensitively.
Unlike Java, back-ticks allow identifiers to contain non-alphanumeric characters (e.g. "SELECT a AS my field FROM t").
String literals must be enclosed in single quotes (e.g., SELECT 'Hello World'). Duplicate a single quote for escaping (e.g., SELECT 'It''s me.'). Unicode characters are supported in string literals. If explicit unicode code points are required, use the following syntax:
Use the backslash (\) as escaping character (default): SELECT U&'\263A'
Use a custom escaping character: SELECT U&'#263A' UESCAPE '#'
Use a group window to compute a single result row per group. See Group Windows section for more details.
Over Window aggregation BatchStreaming
Over window aggregations are supported differently for streaming and batch queries.
For streaming queries, all aggregates must be defined over the same window, i.e., same partitioning, sorting, and range. Currently, only windows with PRECEDING (UNBOUNDED and bounded) to CURRENT ROW range are supported. Ranges with FOLLOWING are not supported yet. ORDER BY must be specified on a single time attribute. Besides, TOPN is also implemented based on Over Window Aggregation. See TOPN for more details.
For batch queries, aggregates can be defined over different windows. Ranges with FOLLOWING are supported. ORDER BY can be specified on any column.
Distinct BatchStreaming Result Updating
Note: For streaming queries the required state to compute the query result might grow infinitely depending on the number of distinct fields. Please provide a query configuration with valid retention interval to prevent excessive state size. See Streaming Concepts for details.
Currently, only equi-joins are supported, i.e., joins that have at least one conjunctive condition with an equality predicate. Arbitrary cross or theta joins are not supported.
Note: Joins without equality predicates are supported for batch queries (implemented with nested loop joins).
Note: The order of joins is not optimized if join-reorder is disabled (sql.cbo.joinReorder.enabled is false). Tables are joined in the order in which they are specified in the FROM clause. Make sure to specify tables in an order that does not yield a cross join (Cartesian product) which are not supported and would cause a query to fail. If join-reorder is enabled(`sql.cbo.joinReorder.enabled` is true), the optimizer will try to find best join order based on cost.
Note: For streaming queries the required state to compute the query result might grow infinitely depending on the number of distinct input rows. Please provide a query configuration with valid retention interval to prevent excessive state size. See Streaming Concepts for details.
Outer Join Batch
Note: Joins without equality predicates are supported for batch queries (implemented with nested loop joins).
Note: The order of joins is not optimized. Tables are joined in the order in which they are specified in the FROM clause. Make sure to specify tables in an order that does not yield a cross join (Cartesian product) which are not supported and would cause a query to fail.
Time-windowed Join BatchStreaming
Note: Time-windowed joins are a subset of regular joins that can be processed in a streaming fashion.
A time-windowed join requires at least one equi-join predicate and a join condition that bounds the time on both sides. Such a condition can be defined by two appropriate range predicates (<, <=, >=, >), a BETWEEN predicate, or a single equality predicate that compares time attributes of the same type (i.e., processing time or event time) of both input tables.
For example, the following predicates are valid window join conditions:
ltime BETWEEN rtime - INTERVAL '10' SECOND AND rtime + INTERVAL '5' SECOND
The example above will join all orders with their corresponding shipments if the order was shipped four hours after the order was received.
Expanding arrays into a relation BatchStreaming
Unnesting WITH ORDINALITY is not supported yet.
Join with User Defined Table Functions (UDTF) BatchStreaming
UDTFs must be registered in the TableEnvironment. See the UDF documentation for details on how to specify and register UDTFs.
Left Outer Join
Note: Currently, only literal TRUE is supported as predicate for a left outer join against a lateral table.
Join with Temporal Table Function Streaming
Temporal Table Functions are tables that track changes over time.
A Temporal Table Function provides access to the state of a temporal table at a specific point in time.
The syntax to join a table with a temporal table function is the same as in join with table functions.
Currently only inner joins with temporal tables are supported.
For more information please check the more detailed Temporal Tables concept description.
Join with Temporal Table BatchStreaming
Temporal Tables are tables that track changes over time.
A Temporal Table provides access to the versions of a temporal table at a specific point in time.
Only inner and left joins with processing-time temporal tables are supported.
The following example assumes that LatestRates is a Temporal Table which is usually an external database table (dimension table).
For more information please check the more detailed Temporal Tables concept description.
Left Semi-Join BatchStreaming
The left semi-join is a joining similar to the natural join, and only returns the rows of the left table where it can find a match in the right table. Sub-queries using IN and EXISTS will be converted to left semi-joins.
Note: IN and EXISTS in conjunctive condition is supported.
Left Anti-Join BatchStreaming
The left anti-join is a joining similar to the left semi-join, and only returns the rows of the left table where it can not find a match in the right table. Sub-queries using NOT IN and NOT EXISTS will be converted to left anti-joins.
Note: NOT IN and NOT EXISTS in conjunctive condition are supported.
TOPN is used to calculate the maximum/minimum N records in a stream. It can be flexibly completed based on OVER window aggregation. The grammar is shown as below:
ROW_NUMBER(): An over window function to calculate the row number, starting from 1.
PARTITION BY col1[, col2..]: Specifying the columns by which the records are partitioned.
ORDER BY col1[,asc|desc] [, col2 [asc|desc]…]: Specifying the columns by which the records are ordered. The ordering directions can be different on different columns.
Flink SQL will sort the input data stream according to the order key, so if the top N records have been changed, the changed ones will be sent as retract records to downstream. In addition, if the top N records need to be stored in external storage, the result table must be defined with a primary key.
NOTE: The usage of TOPN has some constraints. To enable Flink SQL to recognize that this query is a TOPN query, the where rownum <= N clause is necessary for the outer sql query and cannot be substituted by expressions containing rownum (for example, where rownum - 5 <= N). Besides, it is free to add other conditions in the where clause, but they can only be joined using and.
No Ranking Number Optimization
As stated above, the rownum field will be written into the result table as one field of the primary key, which leads to many duplicate records being written to the result table. For example, when the record of rank 9 is updated and its rank is changed to 1, all the first 9 records will be rewritten to the result table as updating result. If the result table receives too many data, it will become the bottleneck of the SQL job.
The optimization method is discarding rownum field when writing records to the result table. This is reasonable because the number of the top N records is usually not large, thus the consumers can sort the records themselves quickly. Without rownum field, in the example above, only the changed record needs to be sent to downstream, which can reduce much burden of the result table.
Note: When this optimization is enabled, the primary keys of the result table should be consistent with keys of group by aggregation upstream before TOPN operator. Otherwise, the results may be incorrect.
The following examples show how to specify SQL queries with TOPN on streaming tables.
Group windows are defined in the GROUP BY clause of a SQL query. Just like queries with regular GROUP BY clauses, queries with a GROUP BY clause that includes a group window function compute a single result row per group. The following group windows functions are supported for SQL on batch and streaming tables.
Group Window Function
Defines a tumbling time window. A tumbling time window assigns rows to non-overlapping, continuous windows with a fixed duration (interval). For example, a tumbling window of 5 minutes groups rows in 5 minutes intervals. Tumbling windows can be defined on event-time (stream + batch) or processing-time (stream).
HOP(time_attr, interval, interval)
Defines a hopping time window (called sliding window in the Table API). A hopping time window has a fixed duration (second interval parameter) and hops by a specified hop interval (first interval parameter). If the hop interval is smaller than the window size, hopping windows are overlapping. Thus, rows can be assigned to multiple windows. For example, a hopping window of 15 minutes size and 5 minute hop interval assigns each row to 3 different windows of 15 minute size, which are evaluated in an interval of 5 minutes. Hopping windows can be defined on event-time (stream + batch) or processing-time (stream).
Defines a session time window. Session time windows do not have a fixed duration but their bounds are defined by a time interval of inactivity, i.e., a session window is closed if no event appears for a defined gap period. For example a session window with a 30 minute gap starts when a row is observed after 30 minutes inactivity (otherwise the row would be added to an existing window) and is closed if no row is added within 30 minutes. Session windows can work on event-time (stream + batch) or processing-time (stream).
For SQL queries on streaming tables, the time_attr argument of the group window function must refer to a valid time attribute that specifies the processing time or event time of rows. See the documentation of time attributes to learn how to define time attributes.
For SQL on batch tables, the time_attr argument of the group window function must be an attribute of type TIMESTAMP.
Selecting Group Window Start and End Timestamps
The start and end timestamps of group windows as well as time attributes can be selected with the following auxiliary functions:
Note: Auxiliary functions must be called with exactly the same arguments as the group window function in the GROUP BY clause.
The EMIT strategy (such as the allowed latency) of the aggregation result varies in different streaming SQL scenarios. For example, users may desire the functionality that they can get the newest result every minute before the end of an 1 hour tumble window and wait for late data for 1 day after the end of the window. This type of demands are not support in conventional ANSI SQL, thus the Flink SQL grammar is extended to include the EMIT strategy.
The purpose of EMIT strategy is concluded as two aspects:
Control the latency: setting the firing frequency before the end of “big” windows to enable users get newest result in time.
Data accuracy: waiting for late data in a specified time, and updating window results on arrival of late data.
The Maxmium Allowed Lateness
It is necessary to specify how long the late data can be waited for by user configurations when AFTER strategy is used. Flink SQL provides a parameter sql.exec.state.ttl.ms, to indicate the maximum allowed lateness. For example, blink.state.ttl.ms=3600000 means only data that arrives 1 hour late after the end of window will be discarded.
The following examples show how to specify SQL queries with group windows and the EMIT strategy on streaming tables.
The SQL runtime is built on top of Flink’s DataStream APIs. Internally, it uses table’s InternalType to define data types. Fully supported types are listed in org.apache.flink.table.api.Types. The following table summarizes the relation between SQL Types, Table API types, and the resulting Java class.
INTERVAL YEAR TO MONTH
INTERVAL DAY TO SECOND(3)
e.g. java.util.HashMap<String, Integer> for a multiset of String
Generic types and composite types (e.g., POJOs or Tuples) can be fields of a row as well. Generic types are treated as a black box and can be passed on or processed by user-defined functions. Composite types can be accessed with built-in functions (see Value access functions section).
Flink’s SQL support comes with a set of built-in functions for data transformations. This section gives a brief overview of the available functions.
The Flink SQL functions (including their syntax) are a subset of Apache Calcite’s built-in functions. Most of the documentation has been adopted from the Calcite SQL reference.
Greater than or equal.
Less than or equal.
Returns TRUE if value is null.
Returns TRUE if value is not null.
Returns TRUE if two values are not equal, treating null values as the same.
Returns TRUE if two values are equal, treating null values as the same.
Returns TRUE if value1 is greater than or equal to value2 and less than or equal to value3.
Returns TRUE if value1 is less than value2 or greater than value3.
Returns TRUE if string1 matches pattern string2. An escape character can be defined if necessary.
Returns TRUE if string1 does not match pattern string2. An escape character can be defined if necessary.
Returns TRUE if string1 matches regular expression string2. An escape character can be defined if necessary.
Returns TRUE if string1 does not match regular expression string2. An escape character can be defined if necessary.
Returns TRUE if an expression exists in a given list of expressions. This is a shorthand for multiple OR conditions. If the testing set contains NULL, the result will be NULL if the element can not be found and TRUE if it can be found. If the element is NULL, the result is always NULL. E.g. "42 IN (1, 2, 3)" leads to FALSE.
Returns TRUE if value is not equal to every value in a list.
Returns TRUE if sub-query returns at least one row. Only supported if the operation can be rewritten in a join and group operation.
Returns TRUE if value is equal to a row returned by sub-query. This operation is not supported in a streaming environment yet.
Returns TRUE if value is not equal to every row returned by sub-query. This operation is not supported in a streaming environment yet.
Returns TRUE if boolean1 is TRUE or boolean2 is TRUE. Supports three-valued logic.
Returns TRUE if boolean1 and boolean2 are both TRUE. Supports three-valued logic.
Returns TRUE if boolean is not TRUE; returns UNKNOWN if boolean is UNKNOWN.
Returns TRUE if boolean is FALSE; returns FALSE if boolean is UNKNOWN.
Returns TRUE if boolean is not FALSE; returns TRUE if boolean is UNKNOWN.
Returns TRUE if boolean is TRUE; returns FALSE if boolean is UNKNOWN.
Returns TRUE if boolean is not TRUE; returns TRUE if boolean is UNKNOWN.
Returns TRUE if boolean is UNKNOWN.
Returns TRUE if boolean is not UNKNOWN.
Returns negative numeric.
Returns numeric1 plus numeric2.
Returns numeric1 minus numeric2.
Returns numeric1 multiplied by numeric2.
Returns numeric1 divided by numeric2.
Returns numeric1 raised to the power of numeric2.
Returns the absolute value of numeric.
Returns the remainder (modulus) of numeric1 divided by numeric2. The result is negative only if numeric1 is negative.
Returns the square root of numeric.
Returns the natural logarithm (base e) of numeric.
Returns the base 10 logarithm of numeric.
Returns the base 2 logarithm of numeric.
Returns e raised to the power of numeric.
Rounds numeric up, and returns the smallest number that is greater than or equal to numeric.
Rounds numeric down, and returns the largest number that is less than or equal to numeric.
Calculates the sine of a given number.
Calculates the cosine of a given number.
Calculates the tangent of a given number.
Calculates the cotangent of a given number.
Calculates the arc sine of a given number.
Calculates the arc cosine of a given number.
Calculates the hyperbolic sine of a given number.
Calculates the arc tangent of a given number.
Calculates the hyperbolic tangent of a given number.
Converts numeric from radians to degrees.
Converts numeric from degrees to radians.
Calculates the signum of a given number.
Rounds the given number to integer places right to the decimal point.
Returns a value that is closer than any other value to pi.
Returns a value that is closer than any other value to e.
Returns a pseudorandom double value between 0.0 (inclusive) and 1.0 (exclusive).
Returns a pseudorandom double value between 0.0 (inclusive) and 1.0 (exclusive) with a initial seed. Two RAND functions will return identical sequences of numbers if they have same initial seed.
Returns a pseudorandom integer value between 0.0 (inclusive) and the specified value (exclusive).
Returns a pseudorandom integer value between 0.0 (inclusive) and the specified value (exclusive) with a initial seed. Two RAND_INTEGER functions will return identical sequences of numbers if they have same initial seed and same bound.
Returns the natural logarithm of a specified number of a specified base. If called with one parameter, this function returns the natural logarithm of x. If called with two parameters, this function returns the logarithm of x to the base b. x must be greater than 0. b must be greater than 1.
Returns a string representation of an integer numeric value in binary format. Returns null if numeric is null. E.g. "4" leads to "100", "12" leads to "1100".
Concatenates two character strings.
Returns the number of characters in a character string.
Returns a character string converted to upper case.
Returns a character string converted to lower case.
Returns the position of the first occurrence of string1 in string2.
Removes leading and/or trailing characters from string2. By default, whitespaces at both sides are removed.
Replaces a substring of string1 with string2.
Returns a substring of a character string starting at a given point.
Returns a substring of a character string starting at a given point with a given length.
Returns string with the first letter of each word converter to upper case and the rest to lower case. Words are sequences of alphanumeric characters separated by non-alphanumeric characters.
Returns the string that results from concatenating the arguments. Returns NULL if any argument is NULL. E.g. CONCAT("AA", "BB", "CC") returns AABBCC.
Returns the string that results from concatenating the arguments using a separator. The separator is added between the strings to be concatenated. Returns NULL If the separator is NULL. CONCAT_WS() does not skip empty strings. However, it does skip any NULL argument. E.g. CONCAT_WS("~", "AA", "BB", "", "CC") returns AA~BB~~CC
Returns the string text left-padded with the string pad to a length of len characters. If text is longer than len, the return value is shortened to len characters. E.g. LPAD('hi',4,'??') returns ??hi, LPAD('hi',1,'??') returns h.
Returns the string text right-padded with the string pad to a length of len characters. If text is longer than len, the return value is shortened to len characters. E.g. RPAD('hi',4,'??') returns hi??, RPAD('hi',1,'??') returns h.
Returns NULL if the values are the same. For example, NULLIF(5, 5) returns NULL; NULLIF(5, 0) returns 5.
Provides a value if the first value is null. For example, COALESCE(NULL, 5) returns 5.
Type conversion functions
Converts a value to a given type.
Parses a date string in the form "yy-mm-dd" to a SQL date.
Parses a time string in the form "hh:mm:ss" to a SQL time.
Parses a timestamp string in the form "yy-mm-dd hh:mm:ss.fff" to a SQL timestamp.
Parses an interval string in the form "dd hh:mm:ss.fff" for SQL intervals of milliseconds or "yyyy-mm" for SQL intervals of months. An interval range might be e.g. DAY, MINUTE, DAY TO HOUR, or DAY TO SECOND for intervals of milliseconds; YEAR or YEAR TO MONTH for intervals of months. E.g. INTERVAL '10 00:00:00.004' DAY TO SECOND, INTERVAL '10' DAY, or INTERVAL '2-10' YEAR TO MONTH return intervals.
Returns the current SQL date in UTC time zone.
Returns the current SQL time in UTC time zone.
Returns the current SQL timestamp in UTC time zone.
Returns the current SQL time in local time zone.
Returns the current SQL timestamp in local time zone.
Extracts parts of a time point or time interval. Returns the part as a long value. E.g. EXTRACT(DAY FROM DATE '2006-06-05') leads to 5.
Rounds a time point down to the given unit. E.g. FLOOR(TIME '12:44:31' TO MINUTE) leads to 12:44:00.
Rounds a time point up to the given unit. E.g. CEIL(TIME '12:44:31' TO MINUTE) leads to 12:45:00.
Returns the quarter of a year from a SQL date. E.g. QUARTER(DATE '1994-09-27') leads to 3.
Determines whether two anchored time intervals overlap. Time point and temporal are transformed into a range defined by two time points (start, end). The function evaluates leftEnd >= rightStart && rightEnd >= leftStart. E.g. (TIME '2:55:00', INTERVAL '1' HOUR) OVERLAPS (TIME '3:30:00', INTERVAL '2' HOUR) leads to true; (TIME '9:00:00', TIME '10:00:00') OVERLAPS (TIME '10:15:00', INTERVAL '3' HOUR) leads to false.
Formats timestamp as a string using a specified format string. The format must be compatible with MySQL's date formatting syntax as used by the date_parse function. The format specification is given in the Date Format Specifier table below.
For example DATE_FORMAT(ts, '%Y, %d %M') results in strings formatted as "2017, 05 May".
Adds a (signed) integer interval to a timestamp. The unit for the interval is given by the unit argument, which should be one of the following values: SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR. E.g. TIMESTAMPADD(WEEK, 1, '2003-01-02') leads to 2003-01-09.
Returns the number of input rows for which value is not null. Use COUNT(DISTINCT value) for the number of unique values in the column or expression.
Returns the number of input rows.
Returns the average (arithmetic mean) of numeric across all input values.
Returns the sum of numeric across all input values.
Returns the maximum value of value across all input values.
Returns the minimum value of value across all input values.
Returns the population standard deviation of the numeric field across all input values.
Returns the sample standard deviation of the numeric field across all input values.
Returns the population variance (square of the population standard deviation) of the numeric field across all input values.
Returns the sample variance (square of the sample standard deviation) of the numeric field across all input values.
Returns a multiset of the values. null input value will be ignored. Return an empty multiset if only null values are added.
Concat all the column values to one string, will ignore null values, a separator can be specified.
Fetch the first not null value of a group and return, if all the values are null, then return null.
Fetch the last not null value of a group and return, if all the values are null, then return null.
Returns an integer that uniquely identifies the combination of grouping keys.
Returns 1 if expression is rolled up in the current row’s grouping set, 0 otherwise.
Returns a bit vector of the given grouping expressions.
Value access functions
Accesses the field of a Flink composite type (such as Tuple, POJO, etc.) by name and returns it's value.
Converts a Flink composite type (such as Tuple, POJO, etc.) and all of its direct subtypes into a flat representation where every subtype is a separate field.
Value constructor functions
Creates a row from a list of values.
Creates a row from a list of values.
Creates an array from a list of values.
Creates a map from a list of key-value pairs.
Returns the number of elements of an array.
Returns the element at a particular position in an array. The index starts at 1.
Returns the sole element of an array with a single element. Returns null if the array is empty. Throws an exception if the array has more than one element.
Returns the number of entries of a map.
Returns the value specified by a particular key in a map.
Returns the MD5 hash of the string argument as a string of 32 hexadecimal digits; null if string is null.
Returns the SHA-1 hash of the string argument as a string of 40 hexadecimal digits; null if string is null.
Returns the SHA-256 hash of the string argument as a string of 64 hexadecimal digits; null if string is null.
Although not every SQL feature is implemented yet, some string combinations are already reserved as keywords for future use. If you want to use one of the following strings as a field name, make sure to surround them with backticks (e.g. `value`, `count`).
Date Format Specifier
Abbreviated weekday name (Sun .. Sat)
Abbreviated month name (Jan .. Dec)
Month, numeric (1 .. 12)
Day of the month with English suffix (0th, 1st, 2nd, 3rd, ...)
Day of the month, numeric (01 .. 31)
Day of the month, numeric (1 .. 31)
Fraction of second (6 digits for printing: 000000 .. 999000; 1 - 9 digits for parsing: 0 .. 999999999) (Timestamp is truncated to milliseconds.)
Hour (00 .. 23)
Hour (01 .. 12)
Hour (01 .. 12)
Minutes, numeric (00 .. 59)
Day of year (001 .. 366)
Hour (0 .. 23)
Hour (1 .. 12)
Month name (January .. December)
Month, numeric (01 .. 12)
AM or PM
Time, 12-hour (hh:mm:ss followed by AM or PM)
Seconds (00 .. 59)
Seconds (00 .. 59)
Time, 24-hour (hh:mm:ss)
Week (00 .. 53), where Sunday is the first day of the week
Week (00 .. 53), where Monday is the first day of the week
Week (01 .. 53), where Sunday is the first day of the week; used with %X
Week (01 .. 53), where Monday is the first day of the week; used with %x
Weekday name (Sunday .. Saturday)
Day of the week (0 .. 6), where Sunday is the first day of the week
Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v