MaxCompute SQL node
The MaxCompute SQL node in DataWorks periodically schedules MaxCompute SQL tasks and integrates with other node types in a unified workflow. MaxCompute SQL uses a SQL-like syntax suited for distributed processing of large-scale (TB-level) data where real-time results are not critical.
Introduction
MaxCompute SQL processes and queries data in MaxCompute. It supports common SQL operations such as SELECT, INSERT, UPDATE, and DELETE, along with MaxCompute-specific syntax and functions. For more information about the SQL syntax, see SQL overview.
Prerequisites
You have bound a MaxCompute compute engine to the DataWorks workspace.
(Optional, for RAM users) The RAM user responsible for task development must be a member of the workspace and have the Development or Workspace Administrator role. The Workspace Administrator role includes extensive permissions and should be granted with caution. For more information about how to add a member to a workspace, see Add members to a workspace.
NoteIf you are using an Alibaba Cloud account, you can skip this step.
Limitations
The following limitations apply to SQL development in the MaxCompute SQL node:
Category | Description |
Comments | Only single-line comments that start with For more information, see MaxCompute SQL comments. The following limitations also apply to comments:
|
SQL submission | ODPS SQL does not support standalone SET or USE statements. They must be executed together with a specific SQL statement. |
SQL development | The SQL code size cannot exceed128 KB, and the number of SQL statements cannot exceed200. |
Query results | Only SQL statements that start with SELECT or WITH can output formatted result sets. Query results have the following limitations:
Note If you encounter query result limitations, you can download the query results to your local machine by using the following methods:
|
Notes
Make sure that the account used to run MaxCompute SQL tasks has the required permissions on the corresponding MaxCompute project. For more information, see DataWorks On MaxCompute permission control and MaxCompute authorization.
MaxCompute SQL task execution relies on quota resources. If your task takes a long time to run, go to the MaxCompute console to check quota resource consumption and make sure that sufficient resources are available for task execution. For more information, see View quota resource consumption.
When you develop MaxCompute SQL node tasks, special parameters such as OSS paths must be enclosed in double quotation marks. Missing quotation marks may cause task parsing exceptions, which lead to task execution failures.
When you run keyword-related statements (SET, USE) in different environments on DataWorks, the execution order varies. For more information, see Appendix 1: SQL execution order in different environments.
-
In some extreme cases, such as a server power outage or a primary/secondary switchover, DataWorks may not be able to completely terminate related MaxCompute tasks. In this situation, go to the corresponding MaxCompute project to terminate the job.
When the primary purpose of a task is to create a new table (for example,
DROP TABLEfollowed byCREATE TABLE AS SELECT), the MaxCompute engine performs a metadata pre-check before execution. If the table already exists, an error is returned directly. For initial table creation, useCREATE TABLE IF NOT EXISTS. For subsequent data writes, useINSERT OVERWRITE TABLE ... SELECT ...instead.You can control the SQL execution mode by setting the
odps.task.sql.realtimeparameter. Set the value totrueto enable Online mode for real-time execution, or set the value tofalseto force Offline mode. Place this parameter at the beginning of your SQL code, before the business SQL statements. Example:SET odps.task.sql.realtime=true; -- Your business SQL statements SELECT * FROM my_table;Directly modifying a column data type from STRING to complex types such as STRUCT is not supported. If error
ODPS-0130071is returned, check whether the field type conversion complies with the semantic rules and avoid unsupported type conversion operations.
Create a MaxCompute SQL node
For information about how to create a node, see Create a MaxCompute SQL node.
Develop a MaxCompute SQL node
On the MaxCompute SQL node editing page, perform the following operations.
Develop SQL code
DataWorks provides scheduling parameters for dynamically passing values to code in scheduling scenarios. You can define variables in a MaxCompute SQL node by using the ${variable_name} format, and then assign values to the variables in the Scheduling Parameters section of Scheduling Settings. For more information about supported formats, see Scheduling parameters. MaxCompute SQL uses a syntax similar to standard SQL and supports DDL, DML, and DQL statements, along with MaxCompute-specific syntax. For detailed syntax and examples, see SQL overview.
The following three examples are provided for different scenarios:
When MaxCompute 2.0 extended functions use new data types, you must add
SET odps.sql.type.system.odps2=true;before the SQL statement that contains the function, and submit and run it together with the SQL statement for the new data types to work properly. For more information about 2.0 data types, see MaxCompute 2.0 data types.MaxCompute SQL statements are executed in a different order in Data Studio and Operation Center environments. For more information, see Appendix 1: SQL execution order in different environments.
Create a table
You can use the CREATE TABLE statement to create non-partitioned tables, partitioned tables, external tables, and clustered tables. For more information, see CREATE TABLE. The following SQL example is provided:
-- Create a partitioned table named students
CREATE TABLE IF NOT EXISTS students
( id BIGINT,
name STRING,
age BIGINT,
birth DATE)
partitioned BY (gender STRING); Insert data
You can use the INSERT INTO or INSERT OVERWRITE statement to insert or update data in a destination table. For more information, see Insert or overwrite data.
Avoid using theINSERT INTOstatement to insert data because it may cause unexpected data duplication. We recommend that you useINSERT OVERWRITEinstead. For more information, see Insert or overwrite data.
The following SQL example is provided:
-- Insert data
INSERT OVERWRITE students PARTITION(gender='boy') VALUES (1,'ZhangSan',15,DATE '2008-05-15') ;The INSERT statement can trigger the Compare DDL Columns feature, which allows you to compare the columns in the SELECT clause of an SQL statement against the columns of the destination table.
This feature is not supported when the MaxCompute project has the schema-based three-layer model enabled at the project level but not at the tenant level.
-- Compare DDL columns
INSERT OVERWRITE TABLE dws_user_info_all_di PARTITION (dt='${workflow.var}')
SELECT COALESCE(a.uid, b.uid) AS uid
, b.gender
, b.age_range
, b.zodiac
, a.region
, a.device
, a.identity
, a.method
, a.url
, a.referer
, a.time
-- ...The FROM/JOIN and other clauses are omitted here. Complete them based on your actual business requirements.
;Query data
You can use the SELECT statement to perform nested queries, group queries, sorting, and other operations. For more information, see SELECT syntax. The following SQL example is provided:
-- (Optional) Enable full table scan at the project level. This operation requires elevated permissions.
-- SETPROJECT odps.sql.allow.fullscan=true;
-- Enable full table scan at the session level. This setting is effective only for the current session.
SET odps.sql.allow.fullscan=true;
-- Query information about all male students and sort the results by ID in ascending order.
SELECT * FROM students WHERE gender='boy' ORDER BY id;RAM users do not have the permission to query production tables by default. To request production table query permissions, go to Security Center. For more information about MaxCompute data permission presets and data access control on DataWorks, see MaxCompute data permission presets and access control. For more information about MaxCompute command-based authorization, see MaxCompute authorization.
Use SQL functions
MaxCompute supports built-in functions and user-defined functions (UDFs). You can create and use SQL functions based on your business requirements. For more information about built-in functions, see Built-in functions overview. For more information about UDFs, see UDF overview. The following examples show how to use SQL functions.
Built-in functions: Built-in functions are pre-installed in MaxCompute and can be called directly. Based on the preceding examples of creating a table, inserting data, and querying data, you can use the
dateaddfunction to modify thebirthcolumn by a specified unit and offset. The following command example is provided:--Enable full table scan at session level. Only effective for this session. SET odps.sql.allow.fullscan=true; SELECT id, name, age, birth, dateadd(birth,1,'mm') AS birth_dateadd FROM students;User-defined functions (UDFs): To use a UDF, you must write the function code, upload it as a resource, and register the function. For more information, see Create a MaxCompute UDF.
Debug a MaxCompute SQL node
Configure the relevant parameters in the Run Configuration panel on the right side of the node editing page.
Parameter
Description
Compute resource
Select the MaxCompute compute resource that you have associated with the workspace.
Compute quota
Select the compute quota to provide the required compute resources (CPU and memory) for compute jobs.
If no compute quota is available, click Create Compute Quota in the drop-down list and create a quota on the MaxCompute console. For more information, see Create a compute quota.
Resource group
Select a scheduling resource group that has passed the connectivity test with the compute resource. For more information, see Resource groups for scheduling.
In the parameter dialog on the toolbar, select the MaxCompute data source that you have created, and then click Run to run the MaxCompute SQL task.
Running a node directly in DataStudio is debug mode. In this mode, the node only validates SQL logic and does not depend on scheduling configuration. If you need to run the node in a workflow (scheduling mode), you must complete the following configurations before the workflow can execute the node:
In the run configuration, select the required Compute resource.
Configure the Scheduling properties of the node.
Deploy the node to the production environment.
View results
Results are displayed in a spreadsheet format. You can perform operations in DataWorks, open the results in a spreadsheet, or copy and paste the content to a local Excel file.
NoteDue to changes in the China time zone information released by the International Organization for Standardization (ISO), date display discrepancies may occur for certain time periods when you run related SQL statements through DataWorks: a difference of 5 minutes and 52 seconds for dates between 1900 and 1928, and a difference of 9 seconds for dates before 1900.
Runtime log: On the
tab of the results, click the Logview link to view the logs. For more information, see LogView.Sort results: On the results page, click the drop-down menu on the corresponding column header, select ascending or descending order in the Sort section, and then click confirm to sort the results.
View BLOB columns: MaxCompute supports the BLOB data type for storing binary objects such as images and audio files. In the results, double-click a cell of this data type to preview the content in the Current Field Value dialog (images are rendered directly; text is displayed in read-only mode). You can switch between Blob View, Text View, and JSON View by using the buttons at the bottom of the dialog.
Scientific notation display: In the DataWorks data development environment, numeric values in query results may be displayed in scientific notation. This is a frontend display issue and does not affect the actual data values. To ensure that numeric values are displayed as expected, use the
CASTfunction in your SQL to manually convert the data type. For example, useCAST(column_name AS STRING)to convert a numeric value to a string for display. You can also verify data accuracy in the DataAnalysis module.
Next steps
Configure schedule settings: If nodes in the project directory need to be periodically scheduled, configure the Scheduling Policy and related scheduling properties in the Scheduling Settings panel on the right side of the node.
Deploy a node: If a task needs to be deployed to the production environment, click the
icon on the page to initiate the deployment process. Nodes in the project directory are periodically scheduled only after they are deployed to the production environment.
Appendix 1: SQL execution order in different environments
When you run keyword-related statements (SET, USE) in different DataWorks environments for a MaxCompute SQL node, the execution order varies.
Running in Data Studio: All keyword statements (SET, USE) in the current task code are merged and prepended to all SQL statements.
Running in the scheduling environment: Statements are executed in the order they are written.
Assume that the following code is defined in a node.
SET a=b;
CREATE TABLE name1(id string);
SET c=d;
CREATE TABLE name2(id string);The execution order varies by environment as follows:
SQL statement | Data Studio | Scheduling environment |
First SQL statement | | |
Second SQL statement | | |
Appendix 2: Lakehouse practices
To read from and write to DLF data tables in MaxCompute SQL tasks, use MaxCompute external projects (External Project). External projects enable real-time access to metadata and data by mapping DLF catalogs. They delegate permission management to DLF and support metadata access and read/write operations on DLF-managed data stored in OSS. For more information, see MaxCompute external projects.
FAQ
Q: Must the destination table of an auto triggered task be a partitioned table?
A: No. The destination table of an auto triggered task does not have to be a partitioned table. If you do not specify partition fields when you create the table, each run of INSERT OVERWRITE overwrites the entire non-partitioned table.
Q: How do I handle the MaxCompute error ODPS-0429311?
A: This error may be related to both the input parameters and how the node SQL is written. A common cause is that multiple tasks concurrently execute DDL operations on the same table, causing a metadata conflict. Try adjusting the relevant settings (for example, set the concurrency parameter to false) and verify whether the issue is resolved.
References
For more MaxCompute SQL task examples, see the following topics: